Skip to content

Commit 721c56f

Browse files
committed
Fix forwarded attributes with negative values
1 parent e071ed2 commit 721c56f

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/Models/TypedConstantInfo.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,17 @@ public sealed record Enum(string TypeName, object Value) : TypedConstantInfo
135135
public override ExpressionSyntax GetSyntax()
136136
{
137137
// We let Roslyn parse the value expression, so that it can automatically handle both positive and negative values. This
138-
// is needed because negative values have a different syntax tree (UnaryMinuxExpression holding the numeric expression).
139-
return CastExpression(IdentifierName(TypeName), ParseExpression(Value.ToString()));
138+
// is needed because negative values have a different syntax tree (UnaryMinusExpression holding the numeric expression).
139+
ExpressionSyntax valueExpression = ParseExpression(Value.ToString());
140+
141+
// If the value is negative, we have to put parentheses around them (to avoid CS0075 errors)
142+
if (valueExpression is PrefixUnaryExpressionSyntax unaryExpression && unaryExpression.IsKind(SyntaxKind.UnaryMinusExpression))
143+
{
144+
valueExpression = ParenthesizedExpression(valueExpression);
145+
}
146+
147+
// Now we can safely return the cast expression for the target enum type (with optional parentheses if needed)
148+
return CastExpression(IdentifierName(TypeName), valueExpression);
140149
}
141150
}
142151

0 commit comments

Comments
 (0)