Skip to content

Commit

Permalink
Fix forwarded attributes with negative values
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio0694 committed Jul 11, 2023
1 parent e071ed2 commit 721c56f
Showing 1 changed file with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,17 @@ public sealed record Enum(string TypeName, object Value) : TypedConstantInfo
public override ExpressionSyntax GetSyntax()
{
// We let Roslyn parse the value expression, so that it can automatically handle both positive and negative values. This
// is needed because negative values have a different syntax tree (UnaryMinuxExpression holding the numeric expression).
return CastExpression(IdentifierName(TypeName), ParseExpression(Value.ToString()));
// is needed because negative values have a different syntax tree (UnaryMinusExpression holding the numeric expression).
ExpressionSyntax valueExpression = ParseExpression(Value.ToString());

// If the value is negative, we have to put parentheses around them (to avoid CS0075 errors)
if (valueExpression is PrefixUnaryExpressionSyntax unaryExpression && unaryExpression.IsKind(SyntaxKind.UnaryMinusExpression))
{
valueExpression = ParenthesizedExpression(valueExpression);
}

// Now we can safely return the cast expression for the target enum type (with optional parentheses if needed)
return CastExpression(IdentifierName(TypeName), valueExpression);
}
}

Expand Down

0 comments on commit 721c56f

Please sign in to comment.