Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn C# incrementing change

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)) };
 }
like image 626
Maloz Avatar asked Nov 02 '22 00:11

Maloz


1 Answers

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.

like image 153
Matt Warren Avatar answered Nov 08 '22 05:11

Matt Warren