Roslyn - Call ToString on SyntaxNode, not preserving priority

If I create a binary expression add (expressionExpression) of two int literals, for example:

BinaryExpressionSyntax addExpression = SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, SyntaxFactory.LiteralExpression (SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(10)), SyntaxFactory.LiteralExpression (SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(100))); 

. and then a binary multiplier expression, where left is the addExpression expression and right is int literal

 BinaryExpressionSyntax multExpression = SyntaxFactory.BinaryExpression(SyntaxKind.MultiplyExpression, addExpression, SyntaxFactory.LiteralExpression (SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(5))); 

Call multExpression.ToString() outputs 10+100*5 . I expect it to output (10+100)*5 .
Is this the right behavior?

+7
c # roslyn
source share
1 answer

The Roslyn Syntax design API does not support that you can only create live programs. It is completely possible to create a program that will not pass through the parser using the API factory, as you discovered.

It would be difficult and expensive to ensure that all trees built were round. We will need to duplicate all the logic that is in the parser, and also spend a lot of time checking the correctness.

Refer to the comment to add parentheses throughout. You can add the brackets marked with the Microsoft.CodeAnalysis.Simplification.Simplifier.Annotation annotation, and then call Simplifier.Simplify after construction to remove the unnecessary brackets.

+6
source share

All Articles