Fix Autofix for LambdaReturnCheck (#151)

This commit is contained in:
Vladiwostok 2024-11-09 21:44:41 +02:00 committed by Vladiwostok
parent e1c1a3958d
commit 6f33134a00
1 changed files with 35 additions and 7 deletions

View File

@ -8,7 +8,6 @@ module dscanner.analysis.lambda_return_check;
import dscanner.analysis.base;
import dmd.tokens : Token, TOK;
// TODO: Fix AutoFix
extern (C++) class LambdaReturnCheck(AST) : BaseAnalyzerDmd
{
alias visit = BaseAnalyzerDmd.visit;
@ -52,15 +51,45 @@ extern (C++) class LambdaReturnCheck(AST) : BaseAnalyzerDmd
if (lambda.fbody.isReturnStatement() is null)
return;
auto tokenRange = tokens.filter!(t => t.loc.fileOffset > lambda.loc.fileOffset)
.filter!(t => t.loc.fileOffset < lambda.endloc.fileOffset)
.find!(t => t.value == TOK.goesTo);
auto lambdaRange = tokens.filter!(t => t.loc.fileOffset > lambda.loc.fileOffset)
.filter!(t => t.loc.fileOffset < lambda.endloc.fileOffset);
auto tokenRange = lambdaRange.find!(t => t.value == TOK.goesTo);
if (!tokenRange.canFind!(t => t.value == TOK.leftCurly))
return;
if (!tokenRange.canFind!(t => t.value == TOK.leftParenthesis))
addErrorMessage(cast(ulong) lambda.loc.linnum, cast(ulong) lambda.loc.charnum, KEY, MSG);
{
auto start = tokenRange.front.loc.fileOffset;
AutoFix fix0;
auto firstParam = (*(lambda.getParameterList().parameters))[0];
if (hasParensOnParams((*(lambda.getParameterList().parameters))[0]))
fix0 = AutoFix.replacement(start, start + 3, "", "Remove arrow (use function body)");
else
fix0 = AutoFix.insertionAt(firstParam.loc.fileOffset, "(")
.concat(AutoFix.insertionAt(start - 1, ")"))
.concat(AutoFix.replacement(start, start + 3, "", "Remove arrow (use function body)"));
addErrorMessage(
cast(ulong) lambda.loc.linnum, cast(ulong) lambda.loc.charnum, KEY, MSG,
[fix0, AutoFix.insertionAt(start + 2, " ()")]
);
}
}
private bool hasParensOnParams(AST.Parameter param)
{
int idx;
foreach (token; tokens)
{
if (token.loc.fileOffset == param.loc.fileOffset)
break;
idx++;
}
return tokens[idx - 1].value == TOK.leftParenthesis && tokens[idx - 2].value == TOK.leftParenthesis;
}
}
@ -88,7 +117,6 @@ unittest
}
}c.format(msg, msg, msg), sac);
/+ TODO: Fix AutoFix
assertAutoFix(q{
void main()
{
@ -111,7 +139,7 @@ unittest
pragma(msg, typeof((a) { return a; })); // fix:0
pragma(msg, typeof((a) => () { return a; })); // fix:1
}
}c, sac);+/
}c, sac, true);
stderr.writeln("Unittest for LambdaReturnCheck passed.");
}