Trying with a Diagnostic and a CodeFix to make a code who transform that:
variable = variable + 1;
otherVariable = otherVariable -1;
Into:
variable++;
otherVariable--;
Already done the diagnostic (it works):
var incrementing = node as BinaryExpressionSyntax;
if (incrementing != null)
{
string right = incrementing .Right.ToString();
string left = incrementing .Left.ToString();
if (right == left + " - 1" || right == left + " + 1")
{
addDiagnostic(Diagnostic.Create(Rule, incrementation.GetLocation(), "Use the shorter way"));
}
}
Edit: I've made some change. Now the incrementating is always recognized. The program go in the CodeFix, but my ReplaceToken with a SyntaxFactory don't work. (It's now only for "++" and not "--"):
if (node.IsKind(SyntaxKind.SimpleAssignmentExpression)) //I use a node instead of a token
{
var IncrementationClause = (BinaryExpressionSyntax)node;
string left = IncrementationClause.Left.ToString();
left = left + "++";
string rigt = IncrementationClause.Right.ToString();
var newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.Left.ToString()), SyntaxFactory.Identifier(left));
newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.Right.ToString()), SyntaxFactory.Identifier(String.Empty));
newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.OperatorToken.ToString()), SyntaxFactory.Identifier(String.Empty));
var newRoot = root.ReplaceNode(IncrementationClause, newIncrementationClause);
return new[] { CodeAction.Create("Changer la mise en forme", document.WithSyntaxRoot(newRoot)) };
}
Try using the source span of the diagnostic and not the span argument. Also, the parent of the first token in the span won't necessarily be the binary expression you are looking for. You'll have to either search up the parent chain using .AncestorsAndSelf() or use FindNode() to find the node that best matches the span.
Also you are checking a token to see if it has the kind of a node. As a rule all token kinds end in Token or Keyword. You need to be finding the node that has that SyntaxKind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With