If I create a binary add expression (addExpression) of two int literals like this:
BinaryExpressionSyntax addExpression = SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression,
SyntaxFactory.LiteralExpression
(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(10)),
SyntaxFactory.LiteralExpression
(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(100)));
. . and then a binary multiply expression, where left is addExpression and right is an int literal
BinaryExpressionSyntax multExpression = SyntaxFactory.BinaryExpression(SyntaxKind.MultiplyExpression,
addExpression,
SyntaxFactory.LiteralExpression
(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(5)));
Calling multExpression.ToString()
outputs 10+100*5
. I would expect it to output (10+100)*5
.
Is this correct behavior?
The Roslyn Syntax construction API does not guarantee that you can only build valid programs. It is entirely possible to construct a program that will not round-trip through the parser using the factory APIs as you have discovered.
It would be both difficult and expensive to ensure that all constructed trees were round-trippable. We would need to duplicate all of the logic that is in the parser, as well as spend a lot of time verifying correctness.
Regardng the comment to add parenthesis everywhere. It is possible to add parenthesis marked with the Microsoft.CodeAnalysis.Simplification.Simplifier.Annotation
annotation, and then call Simplifier.Simplify
after construction to remove unnecessary parenthesis.
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