Skip to content

Commit d74f908

Browse files
Scala: fix support for parsing of underscore numeric literals (#7393)
1 parent 0b08138 commit d74f908

2 files changed

Lines changed: 20 additions & 4 deletions

File tree

rewrite-scala/src/main/scala/org/openrewrite/scala/internal/ScalaTreeVisitor.scala

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,11 @@ class ScalaTreeVisitor(
246246
// Strip them so we can parse the number correctly.
247247
val valueSource = rawSource.replaceAll("[^0-9a-fA-FxXlLfFdDeE._+-]", "")
248248

249+
// Strip underscore digit separators; valueSource keeps them for printing.
250+
val parseSource = valueSource.replace("_", "")
251+
249252
// Parse the number to determine its type and value
250-
val (value: Any, javaType: JavaType.Primitive) = valueSource match {
253+
val (value: Any, javaType: JavaType.Primitive) = parseSource match {
251254
case s if s.startsWith("0x") || s.startsWith("0X") =>
252255
// Hexadecimal literal
253256
val hexStr = s.substring(2)
@@ -257,11 +260,11 @@ class ScalaTreeVisitor(
257260
} else {
258261
(java.lang.Long.valueOf(longVal), JavaType.Primitive.Long)
259262
}
260-
case s if s.endsWith("L") || s.endsWith("l") =>
263+
case s if s.endsWith("L") || s.endsWith("l") =>
261264
(java.lang.Long.valueOf(s.dropRight(1)), JavaType.Primitive.Long)
262-
case s if s.endsWith("F") || s.endsWith("f") =>
265+
case s if s.endsWith("F") || s.endsWith("f") =>
263266
(java.lang.Float.valueOf(s.dropRight(1)), JavaType.Primitive.Float)
264-
case s if s.endsWith("D") || s.endsWith("d") =>
267+
case s if s.endsWith("D") || s.endsWith("d") =>
265268
(java.lang.Double.valueOf(s.dropRight(1)), JavaType.Primitive.Double)
266269
case s if s.contains(".") || s.contains("e") || s.contains("E") =>
267270
(java.lang.Double.valueOf(s), JavaType.Primitive.Double)

rewrite-scala/src/test/java/org/openrewrite/scala/tree/LiteralTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ void integerLiteral() {
2929
);
3030
}
3131

32+
@Test
33+
void numericLiteralsWithUnderscoreSeparator() {
34+
rewriteRun(
35+
scala(
36+
"""
37+
val i = 60_000
38+
val l = 1_000_000L
39+
val d = 3.141_592
40+
"""
41+
)
42+
);
43+
}
44+
3245
@Test
3346
void hexLiteral() {
3447
rewriteRun(

0 commit comments

Comments
 (0)