7

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?

7
  • 1
    I wonder if Roslyn has a way of determining/telling you that the original tree is "invalid". (I.e. it would never be parsed out of a string.)
    – Rawling
    Jun 30, 2014 at 14:50
  • 1
    It seems like it's that way: social.msdn.microsoft.com/Forums/vstudio/en-US/…
    – fhelwanger
    Jun 30, 2014 at 14:54
  • @Rawling I don't think such thing exists... :(
    – Marcote
    Jun 30, 2014 at 14:56
  • @Markust It's possible to convert it to string, parse it back from the string, and then call a Roslyn Equivalent property, but that "parse it back from a string" step was pretty horrible last time I tried.
    – Rawling
    Jun 30, 2014 at 15:00
  • 2
    A solution would be to create a parenthesized expression for every binary expression, you would end up with pointless parenthesis but it would parse back correctly. Jun 30, 2014 at 15:07

1 Answer 1

6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.