[apex] ASTLiteralExpression - add workaround for decimal

This commit is contained in:
Andreas Dangel
2024-02-09 11:11:28 +01:00
parent 5964add71f
commit bf008596bf
2 changed files with 57 additions and 3 deletions

View File

@ -4,6 +4,8 @@
package net.sourceforge.pmd.lang.apex.ast;
import net.sourceforge.pmd.lang.document.Chars;
import com.google.summit.ast.expression.LiteralExpression;
import com.google.summit.ast.expression.VariableExpression;
@ -38,7 +40,12 @@ public final class ASTLiteralExpression extends AbstractApexNode.Single<LiteralE
} else if (node instanceof LiteralExpression.IntegerVal) {
return LiteralType.INTEGER;
} else if (node instanceof LiteralExpression.DoubleVal) {
return LiteralType.DOUBLE;
Chars source = getTextDocument().getText().slice(getTextRegion());
if (source.indexOf('d') > -1 || source.indexOf('D') > -1) {
return LiteralType.DOUBLE;
} else {
return LiteralType.DECIMAL;
}
} else if (node instanceof LiteralExpression.LongVal) {
return LiteralType.LONG;
/* TODO(b/239648780): the parser must distinguish decimal vs. double
@ -88,8 +95,8 @@ public final class ASTLiteralExpression extends AbstractApexNode.Single<LiteralE
/**
* Returns the name of this literal when it is labeled in an object initializer with named
* arguments ({@link ASTNewKeyValueObjectExpression}).
* <p>
* For example, in the Apex code
*
* <p>For example, in the Apex code
* <pre>{@code
* new X(a = 1, b = 2)
* }</pre>

View File

@ -0,0 +1,47 @@
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.apex.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class ASTLiteralExpressionTest extends ApexParserTestBase {
@Test
void doubleLiteral() {
ASTLiteralExpression literal = createLiteral("1.2d");
assertTrue(literal.isDouble());
assertEquals(ASTLiteralExpression.LiteralType.DOUBLE, literal.getLiteralType());
assertEquals("1.2", literal.getImage());
literal = createLiteral("1.2D");
assertTrue(literal.isDouble());
assertEquals(ASTLiteralExpression.LiteralType.DOUBLE, literal.getLiteralType());
}
@Test
void decimalLiteral() {
ASTLiteralExpression literal = createLiteral("1.2");
assertTrue(literal.isDecimal());
assertEquals(ASTLiteralExpression.LiteralType.DECIMAL, literal.getLiteralType());
assertEquals("1.2", literal.getImage());
}
@Test
void stringLiteral() {
ASTLiteralExpression literal = createLiteral("'foo'");
assertTrue(literal.isString());
assertEquals(ASTLiteralExpression.LiteralType.STRING, literal.getLiteralType());
assertEquals("foo", literal.getImage());
}
private ASTLiteralExpression createLiteral(String code) {
return parse("class Foo { object field = " + code + "; }")
.descendants(ASTLiteralExpression.class)
.first();
}
}