Skip to content

C#: Fix numeric literal type attribution to reflect suffix#7187

Merged
knutwannheden merged 1 commit intomainfrom
fix-literal-type-attribution-0l-should-have-long-type-not-int
Mar 28, 2026
Merged

C#: Fix numeric literal type attribution to reflect suffix#7187
knutwannheden merged 1 commit intomainfrom
fix-literal-type-attribution-0l-should-have-long-type-not-int

Conversation

@knutwannheden
Copy link
Copy Markdown
Contributor

Motivation

Numeric literals with type suffixes (e.g., 0L, 1.0F, 2.0D) were all attributed as JavaType.Primitive(Int) because GetPrimitiveType hardcoded NumericLiteralExpression to Int, ignoring the actual type. This forced downstream recipes like MarkLocalVariableAsConst (in recipes-csharp) to implement a workaround (InferTypeFromLiteralSuffix) that manually parsed suffixes from ValueSource — which itself had bugs (e.g., interpreting . in string literals as double).

Summary

  • Use Roslyn's SemanticModel.GetTypeInfo() via _typeMapping?.Type(node) to resolve the correct type for numeric literals, falling back to the hardcoded Int only when no semantic model is available
  • Add Parse() and FindFirst<T>() test helpers to RewriteTest for tests that need to inspect AST node properties beyond round-trip printing
  • Add parameterized test covering 0L, 0l, 42, 1.0f, 1.0F, 1.0d, 1.0D, and 1.0 with their expected primitive kinds

Test plan

  • All 8 new NumericLiteralTypeAttribution test cases pass
  • All 15 LiteralTests pass (existing + new)
  • Full C# test suite passes (1780 tests, 0 failures)

Numeric literals with type suffixes (e.g., 0L, 1.0F, 1.0D) were all
attributed as JavaType.Primitive(Int) because GetPrimitiveType hardcoded
NumericLiteralExpression to Int. Now uses Roslyn's semantic model to
resolve the actual type for numeric literals, correctly producing Long,
Float, Double, etc.
@github-project-automation github-project-automation bot moved this to In Progress in OpenRewrite Mar 28, 2026
@knutwannheden knutwannheden merged commit e3f84a1 into main Mar 28, 2026
1 check passed
@knutwannheden knutwannheden deleted the fix-literal-type-attribution-0l-should-have-long-type-not-int branch March 28, 2026 08:05
@github-project-automation github-project-automation bot moved this from In Progress to Done in OpenRewrite Mar 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant