Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn - Calling ToString on SyntaxNode not preserving precedence

Tags:

c#

roslyn

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?

like image 588
user2697817 Avatar asked Jun 30 '14 14:06

user2697817


1 Answers

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.

like image 179
Kevin Pilch Avatar answered Oct 10 '22 04:10

Kevin Pilch