|
23 | 23 | import org.sonar.plugins.java.api.semantic.Symbol; |
24 | 24 | import org.sonar.plugins.java.api.semantic.SymbolMetadata; |
25 | 25 | import org.sonar.plugins.java.api.semantic.Type; |
| 26 | +import org.sonar.plugins.java.api.tree.ExpressionTree; |
26 | 27 | import org.sonar.plugins.java.api.tree.IdentifierTree; |
27 | 28 | import org.sonar.plugins.java.api.tree.LiteralTree; |
| 29 | +import org.sonar.plugins.java.api.tree.Tree; |
28 | 30 | import org.sonar.plugins.java.api.tree.VariableTree; |
29 | 31 |
|
30 | 32 | final class JVariableSymbol extends JSymbol implements Symbol.VariableSymbol { |
@@ -70,14 +72,47 @@ public Optional<Object> constantValue() { |
70 | 72 | return constant; |
71 | 73 | } |
72 | 74 |
|
| 75 | + /** A constant is a static final field with a compile time value, typed as its declaration. */ |
73 | 76 | @Nullable |
74 | 77 | private Object declaredConstant() { |
75 | 78 | VariableTree declaration = declaration(); |
76 | | - if (declaration == null || !(declaration.initializer() instanceof LiteralTree literal) |
77 | | - || !(isFinal() || owner().isInterface() || isEnum())) { |
| 79 | + if (declaration == null || declaration.initializer() == null || declaration.type() == null || !isFinal() && !owner().isInterface() && !isEnum() |
| 80 | + || !isStatic() && !owner().isInterface()) { |
78 | 81 | return null; |
79 | 82 | } |
80 | | - return LiteralUtils.constantValue(literal); |
| 83 | + ExpressionTree initializer = declaration.initializer(); |
| 84 | + Object value = initializer.is(Tree.Kind.LONG_LITERAL, Tree.Kind.FLOAT_LITERAL, Tree.Kind.DOUBLE_LITERAL) |
| 85 | + ? literalNumber((LiteralTree) initializer) |
| 86 | + : ExpressionUtils.resolveAsConstant(initializer); |
| 87 | + return convert(value, declaration.type().symbolType()); |
| 88 | + } |
| 89 | + |
| 90 | + @Nullable |
| 91 | + private static Object literalNumber(LiteralTree literal) { |
| 92 | + String text = literal.value().replace("_", ""); |
| 93 | + try { |
| 94 | + return switch (literal.kind()) { |
| 95 | + case LONG_LITERAL -> LiteralUtils.longLiteralValue(literal); |
| 96 | + case FLOAT_LITERAL -> Float.valueOf(text); |
| 97 | + default -> Double.valueOf(text); |
| 98 | + }; |
| 99 | + } catch (NumberFormatException e) { |
| 100 | + return null; |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + @Nullable |
| 105 | + private static Object convert(@Nullable Object value, Type type) { |
| 106 | + if (value instanceof Number number) { |
| 107 | + if (type.is("long")) { |
| 108 | + return number.longValue(); |
| 109 | + } else if (type.is("double")) { |
| 110 | + return number.doubleValue(); |
| 111 | + } else if (type.is("float")) { |
| 112 | + return number.floatValue(); |
| 113 | + } |
| 114 | + } |
| 115 | + return value; |
81 | 116 | } |
82 | 117 |
|
83 | 118 | @Override |
|
0 commit comments