Skip to content

Commit fb0301b

Browse files
committed
constraining special hex literal case to integer values
1 parent c24caeb commit fb0301b

1 file changed

Lines changed: 16 additions & 13 deletions

File tree

CodeConverter/CSharp/LiteralConversions.cs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -149,19 +149,22 @@ private static (string textForUser, ExpressionSyntax MaybeFullExpression) Conver
149149
string hexValue = textForUser.Substring(2);
150150
textForUser = "0x" + hexValue;
151151

152-
int parsedHexValue = int.Parse(hexValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
153-
154-
// This is a very special case where for 8 digit hex strings, C# interprets them as unsigned ints, but VB interprets them as ints
155-
// This can lead to a compile error if assigned to an int in VB. So in a case like 0x91234567, we generate `unchecked((int)0x91234567)`
156-
// This way the value looks pretty close to before and remains a compile time constant
157-
if (parsedHexValue < 0) {
158-
var hexValueExpr = NumericLiteral(SyntaxFactory.Literal(textForUser, parsedHexValue));
159-
var checkedExpr = SyntaxFactory.CheckedExpression(
160-
CSSyntaxKind.UncheckedExpression,
161-
SyntaxFactory.CastExpression(
162-
SyntaxFactory.PredefinedType(SyntaxFactory.Token(CSSyntaxKind.IntKeyword)),
163-
hexValueExpr));
164-
return (null, checkedExpr);
152+
// ulong/long/uint hex literals have suffixes, so we just handle ints
153+
if (value is int) {
154+
int parsedHexValue = int.Parse(hexValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
155+
156+
// This is a very special case where for 8 digit hex strings, C# interprets them as unsigned ints, but VB interprets them as ints
157+
// This can lead to a compile error if assigned to an int in VB. So in a case like 0x91234567, we generate `unchecked((int)0x91234567)`
158+
// This way the value looks pretty close to before and remains a compile time constant
159+
if (parsedHexValue < 0) {
160+
var hexValueExpr = NumericLiteral(SyntaxFactory.Literal(textForUser, parsedHexValue));
161+
var checkedExpr = SyntaxFactory.CheckedExpression(
162+
CSSyntaxKind.UncheckedExpression,
163+
SyntaxFactory.CastExpression(
164+
SyntaxFactory.PredefinedType(SyntaxFactory.Token(CSSyntaxKind.IntKeyword)),
165+
hexValueExpr));
166+
return (null, checkedExpr);
167+
}
165168
}
166169
} else if (canBeBinaryOrHex && textForUser.StartsWith("&B", StringComparison.OrdinalIgnoreCase)) {
167170
textForUser = "0b" + textForUser.Substring(2);

0 commit comments

Comments
 (0)