diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/BinaryNames.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/BinaryNames.java new file mode 100644 index 00000000000..5f9ff5dd98f --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/BinaryNames.java @@ -0,0 +1,79 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + +/** The binary names Java gives the types SemSitter names, and back, for the types of one file. */ +final class BinaryNames { + + private static final Pattern LAMBDA_SEGMENTS = Pattern.compile("^(?:\\$lambda\\$[^$()]*+\\(\\))++"); + + private final Map binaryById = new HashMap<>(); + private final Map idByBinary = new HashMap<>(); + + /** + * The binary name Java gives the type SemSitter names {@code id}: a local class {@code p.C#f()$Local} becomes + * {@code p.C$1Local}, numbered by the first index not yet taken in its enclosing class, in declaration order. + */ + String binaryName(String id) { + String known = binaryById.get(id); + if (known != null) { + return known; + } + int hash = id.lastIndexOf('#'); + int open = id.indexOf('(', hash); + int close = open < 0 ? -1 : id.indexOf(')', open); + String afterMethod = close < 0 ? "" : id.substring(close + 1); + var lambdaPrefix = LAMBDA_SEGMENTS.matcher(afterMethod); + int lambdaEnd = lambdaPrefix.find() ? lambdaPrefix.end() : 0; + String rest = afterMethod.substring(lambdaEnd); + if (hash < 0 || !rest.startsWith("$") || rest.length() == 1) { + return id; + } + int nested = rest.indexOf('$', 1); + String name = nested < 0 ? rest.substring(1) : rest.substring(1, nested); + String localId = id.substring(0, close + 1 + lambdaEnd) + "$" + name; + String local = binaryById.get(localId); + if (local == null) { + String enclosing = binaryName(id.substring(0, hash)); + int index = 1; + while (idByBinary.containsKey(enclosing + "$" + index + name)) { + index++; + } + local = enclosing + "$" + index + name; + binaryById.put(localId, local); + idByBinary.put(local, localId); + } + String binary = nested < 0 ? local : (local + rest.substring(nested)); + binaryById.put(id, binary); + idByBinary.putIfAbsent(binary, id); + return binary; + } + + /** The binary name already given to {@code name}, or {@code name} itself. */ + String binaryOf(String name) { + return binaryById.getOrDefault(name, name); + } + + /** The SemSitter name of the type Java names {@code fqn}, or {@code fqn} itself. */ + String sourceName(String fqn) { + return idByBinary.getOrDefault(fqn, fqn); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DeclaredAnnotation.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DeclaredAnnotation.java new file mode 100644 index 00000000000..ae45eef9716 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DeclaredAnnotation.java @@ -0,0 +1,23 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.List; +import org.sonar.plugins.java.api.semantic.SymbolMetadata; + +record DeclaredAnnotation(String name, List values) { +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DeclaredMembers.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DeclaredMembers.java new file mode 100644 index 00000000000..3f432f61e15 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DeclaredMembers.java @@ -0,0 +1,34 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.sonarsource.semsitter.wire.Fact; + +/** What the {@code types} answers declare about members and packages, by symbol id, for one {@link JSema}. */ +final class DeclaredMembers { + final Map> libraryAnnotations = new HashMap<>(); + final Map> projectThrows = new HashMap<>(); + final Map projectMemberFacts = new HashMap<>(); + final Map projectVarArgs = new HashMap<>(); + final Map projectFieldTypes = new HashMap<>(); + final Map projectConstants = new HashMap<>(); + final Map annotationDefaults = new HashMap<>(); +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FactTypes.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FactTypes.java new file mode 100644 index 00000000000..3ab3dbefb79 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FactTypes.java @@ -0,0 +1,348 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.TypeRef; + +import static org.sonar.java.semsitter.SemaFacts.erase; +import static org.sonar.java.semsitter.SemaFacts.parameterKey; +import static org.sonar.java.semsitter.SemaFacts.text; + +/** Builds types from the type references written in facts and descriptors. */ +final class FactTypes { + + private static final String OBJECT = "java.lang.Object"; + private final JSema sema; + private final Map placeholders = new HashMap<>(); + private final Map> descriptorParameters = new HashMap<>(); + + @Nullable + private Map> typeVariablesByOwner; + + FactTypes(JSema sema) { + this.sema = sema; + } + + void invalidateDeclaredVariables() { + typeVariablesByOwner = null; + } + + JType typeFromFact(JsonObject fact) { + return typeFromFact(fact, Map.of()); + } + + JType typeFromFact(JsonObject fact, Map substitution) { + return typeFromFact(fact, substitution, false); + } + + JType typeFromFact(JsonObject fact, Map substitution, boolean captureWildcard) { + String kind = text(fact, "kind"); + if (JSema.ARRAY.equals(kind) && fact.getAsJsonObject("elem") != null) { + return JType.array(sema, typeFromFact(fact.getAsJsonObject("elem"), substitution, captureWildcard)); + } + if (JSema.WILDCARD.equals(kind)) { + return wildcardFromFact(fact, substitution, captureWildcard); + } + if ("typevar".equals(kind)) { + return typeVariable(text(fact, "id"), substitution); + } + if ("unknown".equals(kind)) { + return JType.unknown(sema); + } + String id = text(fact, "id"); + if (id == null) { + return JType.unknown(sema); + } + List args = new ArrayList<>(); + if (fact.has("args")) { + for (JsonElement arg : fact.getAsJsonArray("args")) { + if (arg.isJsonObject()) { + args.add(typeFromFact(arg.getAsJsonObject(), substitution, captureWildcard)); + } + } + } + return namedType(id, args, captureWildcard); + } + + /** The type a document declares for a symbol; its wildcards are unbounded. */ + JType typeFromRef(TypeRef type) { + String kind = type.getKind(); + if (JSema.ARRAY.equals(kind) && type.hasElement()) { + return JType.array(sema, typeFromRef(type.getElement())); + } + if (JSema.WILDCARD.equals(kind)) { + return JType.wildcard(sema, sema.asJType(sema.getClassType(OBJECT))); + } + if ("typevar".equals(kind)) { + return typeVariable(text(type.getId()), Map.of()); + } + if ("unknown".equals(kind) || type.getId().isEmpty()) { + return JType.unknown(sema); + } + List args = new ArrayList<>(); + for (TypeRef argument : type.getArgumentsList()) { + args.add(typeFromRef(argument)); + } + return namedType(type.getId(), args, false); + } + + /** A supertype fact: the loaded raw type, parameterized when the fact has type arguments. */ + Type supertypeFromFact(JsonObject fact) { + Type raw = sema.getClassType(erase(Objects.requireNonNull(text(fact, "id")))); + JsonArray args = fact.getAsJsonArray("args"); + if (args == null || args.isEmpty() || !(raw instanceof JType rawType)) { + return raw; + } + List resolved = new ArrayList<>(); + for (JsonElement arg : args) { + if (arg.isJsonObject()) { + resolved.add(typeFromFact(arg.getAsJsonObject())); + } + } + return JType.named(sema, rawType.fullyQualifiedName(), resolved); + } + + static List objects(JsonObject object, String key) { + if (!object.has(key) || !object.get(key).isJsonArray()) { + return List.of(); + } + List values = new ArrayList<>(); + for (JsonElement item : object.getAsJsonArray(key)) { + if (item.isJsonObject()) { + values.add(item.getAsJsonObject()); + } + } + return values; + } + + Type typeFromName(String name) { + JTypeSymbol variable = typeParameterItem(name); + if (variable != null) { + return variable.type(); + } + String erased = erase(name); + if (JSema.PRIMITIVES.contains(erased)) { + return sema.primitiveType(erased); + } + if (erased.endsWith(SemaFacts.ARRAY_SUFFIX)) { + return JType.array(sema, sema.asJType(typeFromName(erased.substring(0, erased.length() - SemaFacts.ARRAY_SUFFIX.length())))); + } + return sema.getClassType(erased); + } + + /** The parameter of a method no source declares: one symbol per method and position, whichever call it is seen from. */ + Symbol parameterPlaceholder(JMethodSymbol method, int index, Type type) { + String key = method.id + "#" + index + "#" + type.fullyQualifiedName(); + if (method.id != null && sema.declaredMembers.libraryAnnotations.containsKey(parameterKey(method.id, index))) { + return placeholders.computeIfAbsent(key, k -> { + JVariableSymbol annotated = new JVariableSymbol(sema, parameterKey(method.id, index), "arg" + index, "param"); + annotated.owner(method); + annotated.type(type); + return annotated; + }); + } + return method.id == null ? new JVariableSymbol.ParameterPlaceholderSymbol(index, method, type) + : placeholders.computeIfAbsent(key, k -> new JVariableSymbol.ParameterPlaceholderSymbol(index, method, type)); + } + + List parameterTypesOf(String descriptor) { + List cached = descriptorParameters.get(descriptor); + if (cached != null) { + return cached; + } + List types = new ArrayList<>(); + int[] index = {1}; + while (index[0] < descriptor.length() && descriptor.charAt(index[0]) != ')') { + types.add(readDescriptor(descriptor, index)); + } + List immutable = List.copyOf(types); + descriptorParameters.put(descriptor, immutable); + return immutable; + } + + Type readDescriptor(String descriptor, int[] index) { + int array = 0; + while (descriptor.charAt(index[0]) == '[') { + array++; + index[0]++; + } + Type type; + char kind = descriptor.charAt(index[0]); + if (kind == 'L') { + int semi = descriptor.indexOf(';', index[0]); + String binary = descriptor.substring(index[0] + 1, semi).replace('/', '.'); + index[0] = semi + 1; + type = sema.getClassType(binary); + } else { + index[0]++; + type = sema.primitiveType(switch (kind) { + case 'B' -> "byte"; + case 'C' -> "char"; + case 'D' -> "double"; + case 'F' -> "float"; + case 'I' -> "int"; + case 'J' -> "long"; + case 'S' -> "short"; + case 'Z' -> "boolean"; + default -> "void"; + }); + } + for (int i = 0; i < array; i++) { + type = JType.array(sema, sema.asJType(type)); + } + return type; + } + + private JType typeVariable(@Nullable String id, Map substitution) { + Type substituted = substitution.get(id); + if (substituted != null) { + return sema.asJType(substituted); + } + int open = id == null ? -1 : id.lastIndexOf('<'); + String name = open >= 0 && id.endsWith(">") ? id.substring(open + 1, id.length() - 1) : id; + return JType.typeVar(sema, name == null ? "" : name, id); + } + + private JType namedType(String id, List args, boolean captureWildcard) { + String erased = erase(id); + if (JSema.PRIMITIVES.contains(erased)) { + return sema.primitiveType(erased); + } + if (captureWildcard) { + boundCaptures(erased, args); + } + return JType.named(sema, erased, args); + } + + /** An unbounded wildcard argument is captured with the bound its type parameter declares. */ + private void boundCaptures(String owner, List arguments) { + for (int i = 0; i < arguments.size(); i++) { + JType argument = arguments.get(i); + if (argument.isCapture() && argument.element != null && argument.element.is(OBJECT)) { + JType bound = declaredBound(owner, i); + if (bound != null) { + arguments.set(i, JType.capture(sema, bound)); + } + } + } + } + + /** The class bound the {@code index}th type parameter of {@code owner} declares, when it is more than Object. */ + @Nullable + private JType declaredBound(String owner, int index) { + JsonObject info = sema.typeInfos.get(sema.sourceName(owner)); + if (info == null || !(info.get("typeVarBounds") instanceof JsonArray bounds) || bounds.size() <= index + || !(bounds.get(index) instanceof JsonArray list) || list.isEmpty() || !(list.get(0) instanceof JsonObject fact)) { + return null; + } + JType bound = typeFromFact(fact); + return bound.isUnknown() || bound.is(OBJECT) ? null : bound; + } + + private JType wildcardFromFact(JsonObject fact, Map substitution, boolean capture) { + JType object = sema.asJType(sema.getClassType(OBJECT)); + JType upper = fact.get(JSema.EXTENDS) instanceof JsonObject bound ? typeFromFact(bound, substitution) : object; + if (capture) { + return JType.capture(sema, upper.isUnknown() ? object : upper); + } + if (fact.get("super") instanceof JsonObject bound) { + return JType.superWildcard(sema, typeFromFact(bound, substitution)); + } + return JType.wildcard(sema, upper); + } + + /** + * The type variable a result names as {@code ::``} for a callable, the position-th variable the dump + * declares as {@code }, or as {@code ::`} for a class, where the variables of the + * enclosing classes come first. + */ + @Nullable + private JTypeSymbol typeParameterItem(String name) { + int marker = name.lastIndexOf("::`"); + boolean callable = marker >= 0 && name.startsWith("::``", marker); + int digits = -1; + if (marker >= 0) { + digits = marker + (callable ? 4 : 3); + } + if (marker <= 0 || name.length() == digits || !name.substring(digits).chars().allMatch(Character::isDigit)) { + return null; + } + String owner = name.substring(0, marker); + int position = Integer.parseInt(name.substring(digits)); + List variables = new ArrayList<>(); + if (!callable) { + for (int nested = owner.indexOf('$'); nested > 0; nested = owner.indexOf('$', nested + 1)) { + variables.addAll(declaredVariables(owner.substring(0, nested))); + } + } + variables.addAll(declaredVariables(owner)); + if (position >= variables.size() || !(sema.resolve(variables.get(position)) instanceof JTypeSymbol variable) || !variable.isTypeParameter()) { + return null; + } + if (variable.type().isUnknown()) { + variable.type(JType.typeVar(sema, variable.name(), variables.get(position))); + } + return variable; + } + + private List declaredVariables(String owner) { + if (typeVariablesByOwner == null) { + typeVariablesByOwner = indexDeclaredVariables(); + } + List direct = typeVariablesByOwner.get(owner); + String erased = erase(owner); + if (erased.equals(owner)) { + return direct == null ? List.of() : direct; + } + List byErased = typeVariablesByOwner.get(erased); + if (direct == null) { + return byErased == null ? List.of() : byErased; + } + if (byErased == null) { + return direct; + } + List combined = new ArrayList<>(direct.size() + byErased.size()); + combined.addAll(direct); + combined.addAll(byErased); + return combined; + } + + private Map> indexDeclaredVariables() { + Map> index = new HashMap<>(); + for (Map.Entry entry : sema.dumpSymbols.entrySet()) { + String key = entry.getKey(); + if ("type".equals(entry.getValue().getKind()) && key.endsWith(">")) { + int open = key.lastIndexOf('<'); + if (open > 0 && key.length() > open + 2) { + index.computeIfAbsent(key.substring(0, open), k -> new ArrayList<>()).add(key); + } + } + } + return index; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JMethodSymbol.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JMethodSymbol.java new file mode 100644 index 00000000000..368d97f77c7 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JMethodSymbol.java @@ -0,0 +1,258 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.ArrayTypeTree; +import org.sonar.plugins.java.api.tree.MethodTree; +import org.sonar.plugins.java.api.tree.TypeTree; +import org.sonar.plugins.java.api.tree.VariableTree; + +final class JMethodSymbol extends JSymbol implements Symbol.MethodSymbol { + + private static final String DEFAULT = "default"; + private static final String NATIVE = "native"; + private static final String SYNCHRONIZED = "synchronized"; + private List parameterTypes = List.of(); + private TypeSymbol returnTypeSymbol = TypeSymbol.UNKNOWN_TYPE; + private boolean varArgs; + private boolean varArgsKnown; + private boolean parametrized; + private final String signature; + + @Nullable + private List declaredParameters; + + private List overridden; + + @Nullable + private List thrownTypes; + + @Nullable + private String descriptorSignature; + + JMethodSymbol(JSema sema, @Nullable String id, String name) { + super(sema, Kind.METHOD, id, name); + owner(Symbol.TypeSymbol.UNKNOWN_TYPE); + this.signature = id == null ? name : SemaFacts.erase(id); + } + + void parameterTypes(List parameterTypes) { + this.parameterTypes = List.copyOf(parameterTypes); + } + + void returnTypeSymbol(TypeSymbol returnTypeSymbol) { + this.returnTypeSymbol = returnTypeSymbol == null ? TypeSymbol.UNKNOWN_TYPE : returnTypeSymbol; + } + + void varArgs(boolean varArgs) { + this.varArgs = varArgs; + } + + /** The declaring answer says whether the method is variable arity, so a trailing array parameter proves nothing. */ + void varArgsKnown(boolean known) { + this.varArgsKnown = known; + } + + void parametrized(boolean parametrized) { + this.parametrized = parametrized; + } + + void declaredParameters(List declaredParameters) { + this.declaredParameters = declaredParameters; + } + + @Nullable + List declaredParameters() { + return declaredParameters; + } + + @Override + public List parameterTypes() { + return parameterTypes; + } + + @Override + public List declarationParameters() { + if (declaration() instanceof MethodTree method && method.closeParenToken() != null) { + return method.parameters().stream().map(VariableTree::symbol).toList(); + } + List placeholders = new ArrayList<>(); + for (int i = 0; i < parameterTypes.size(); i++) { + placeholders.add(sema.factTypes().parameterPlaceholder(this, i, parameterTypes.get(i))); + } + return placeholders; + } + + @Override + public TypeSymbol returnType() { + return returnTypeSymbol; + } + + void thrownTypes(List thrownTypes) { + this.thrownTypes = List.copyOf(thrownTypes); + } + + @Override + public List thrownTypes() { + if (thrownTypes != null) { + return thrownTypes; + } + MethodTree method = declaration(); + if (method == null) { + List served = sema.libraryMembers().projectThrown(id); + return served == null ? Collections.emptyList() : served; + } + return method.throwsClauses().stream().map(TypeTree::symbolType).toList(); + } + + @Override + public List overriddenSymbols() { + if (overridden == null) { + overridden = new OverriddenMethods(this).find(); + } + return overridden; + } + + /** + * The ECJ form, {@code binaryOwner#name(descriptors)returnDescriptor}, from the erased parameter and return + * types. Falls back to the SemSitter id when the owner is not a type. + */ + @Override + public String signature() { + if (descriptorSignature == null) { + descriptorSignature = descriptorSignature(); + } + return descriptorSignature; + } + + @Override + public boolean isOverridable() { + return !isUnknown() && !(isPrivate() || isStatic() || isFinal() || owner().isFinal()); + } + + @Override + public boolean isParametrizedMethod() { + return !isUnknown() && (parametrized || (declaration() instanceof MethodTree method && !method.typeParameters().isEmpty())); + } + + @Override + public boolean isDefaultMethod() { + return !isUnknown() && hasModifier(DEFAULT); + } + + @Override + public boolean isSynchronizedMethod() { + return !isUnknown() && hasModifier(SYNCHRONIZED); + } + + @Override + public boolean isVarArgsMethod() { + if (isUnknown()) { + return false; + } + if (varArgs) { + return true; + } + if (varArgsKnown) { + return false; + } + if (declaration() instanceof MethodTree method) { + List parameters = method.parameters(); + if (parameters.isEmpty()) { + return false; + } + return parameters.get(parameters.size() - 1).type() instanceof ArrayTypeTree arrayType + && arrayType.ellipsisToken() != null; + } + return !parameterTypes.isEmpty() && parameterTypes.get(parameterTypes.size() - 1).isArray(); + } + + @Nullable + @Override + public MethodTree declaration() { + return (MethodTree) super.declaration(); + } + + @Nullable + @Override + public Object annotationElementDefaultValue() { + MethodTree method = declaration(); + if (method == null) { + return sema.annotationFacts().annotationDefault(this); + } + if (method.defaultValue() == null) { + return null; + } + Object value = TreeAnnotation.literal(sema, method.defaultValue()); + return value instanceof Object[] || !returnType().type().isArray() ? value : new Object[] {value}; + } + + @Override + public boolean isNativeMethod() { + return !isUnknown() && hasModifier(NATIVE); + } + + private String descriptorSignature() { + Symbol owner = owner(); + if (!(owner instanceof TypeSymbol ownerType) || isUnknown()) { + return signature; + } + StringBuilder out = new StringBuilder(ownerType.type().fullyQualifiedName()).append('#').append(name()).append('('); + if (SemaFacts.CONSTRUCTOR_NAME.equals(name()) && ownerType.isEnum()) { + out.append("Ljava/lang/String;I"); + } else if (SemaFacts.CONSTRUCTOR_NAME.equals(name()) && !ownerType.isStatic() && ownerType.owner() instanceof TypeSymbol enclosing) { + out.append(descriptor(enclosing.type())); + } + parameterTypes.forEach(parameter -> out.append(descriptor(parameter))); + out.append(')'); + if (SemaFacts.CONSTRUCTOR_NAME.equals(name())) { + out.append('V'); + } else { + out.append(descriptor(returnTypeSymbol.type())); + } + return out.toString(); + } + + private static String descriptor(@Nullable Type type) { + if (type == null || type.isUnknown()) { + return "Ljava/lang/Object;"; + } + Type erased = type.erasure(); + if (erased.isArray()) { + return "[" + descriptor(((Type.ArrayType) erased).elementType()); + } + return switch (erased.fullyQualifiedName()) { + case "byte" -> "B"; + case "char" -> "C"; + case "double" -> "D"; + case "float" -> "F"; + case "int" -> "I"; + case "long" -> "J"; + case "short" -> "S"; + case "boolean" -> "Z"; + case "void" -> "V"; + default -> "L" + erased.fullyQualifiedName().replace('.', '/') + ";"; + }; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JPackageSymbol.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JPackageSymbol.java new file mode 100644 index 00000000000..e4e1a154124 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JPackageSymbol.java @@ -0,0 +1,29 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +final class JPackageSymbol extends JSymbol { + + JPackageSymbol(JSema sema, String name) { + super(sema, Kind.PACKAGE, name, name); + } + + @Override + public boolean isUnknown() { + return false; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSema.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSema.java new file mode 100644 index 00000000000..a498e81f2fb --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSema.java @@ -0,0 +1,403 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Sema; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactEntry; +import org.sonarsource.semsitter.wire.TypeRef; + +import static org.sonar.java.semsitter.SemaFacts.addTypeName; +import static org.sonar.java.semsitter.SemaFacts.collectFactNames; +import static org.sonar.java.semsitter.SemaFacts.erase; +import static org.sonar.java.semsitter.SemaFacts.isWellKnown; +import static org.sonar.java.semsitter.SemaFacts.packageName; +import static org.sonar.java.semsitter.SemaFacts.simpleName; +import static org.sonar.java.semsitter.SemaFacts.text; +import static org.sonar.java.semsitter.SemaFacts.typeFact; + +/** + * Semantic model of one translated file. Symbols are created from the SemSitter dump and from the + * {@code types} response (project graph, classpath declarations including the JDK image, embedded JDK table). + */ +final class JSema implements Sema { + + static final String ANNOTATIONS = "annotations"; + static final String EXTENDS = "extends"; + static final String WILDCARD = "wildcard"; + static final String MEMBERS = "members"; + static final String STATIC = "static"; + static final String ABSTRACT = "abstract"; + static final String RECORD = "record"; + static final String ARRAY = "array"; + static final Set PRIMITIVES = Set.of("byte", "short", "int", "long", "char", "float", "double", "boolean", "void"); + final Map facts = new HashMap<>(); + final Map dumpSymbols = new LinkedHashMap<>(); + final Map typeInfos = new HashMap<>(); + final DeclaredMembers declaredMembers = new DeclaredMembers(); + final Map symbols = new HashMap<>(); + final Map typesByName = new HashMap<>(); + final Map declarations = new HashMap<>(); + final Map> usages = new HashMap<>(); + Function, JsonObject> typeLoader = names -> new JsonObject(); + private boolean typesLoaded; + final JSymbol unknownSymbol = new JVariableSymbol(this, null, "", "local"); + + /** Types of the built-in library table, which are not on the analyzed classpath; off to leave them unresolved. */ + private static final boolean FRAMEWORK_TYPES = Boolean.parseBoolean(System.getProperty("sonar.java.semsitter.frameworkTypes", "true")); + + private static final MemberId NOT_A_MEMBER = new MemberId("", "", null, false, -1, List.of()); + + private record SubtypeKey(JType sub, JType sup) { + } + + private static final class Caches { + private final Map rawTypes = new HashMap<>(); + private final BinaryNames binaryNames = new BinaryNames(); + private final Set requestedTypes = new HashSet<>(); + private final Map subtypeCache = new HashMap<>(); + private final Map parsedMemberIds = new HashMap<>(); + private int typeRevision; + } + + private final Caches caches = new Caches(); + private final SemaAnnotations annotationFacts = new SemaAnnotations(this); + private final Substitution substitution = new Substitution(this); + private final LibraryMembers libraryMembers = new LibraryMembers(this); + private final MemberFactory memberFactory = new MemberFactory(this); + private final MemberLookup lookup = new MemberLookup(this); + private final FactTypes factTypes = new FactTypes(this); + + JSema() { + unknownSymbol.unknown(true); + } + + SemaAnnotations annotationFacts() { + return annotationFacts; + } + + Substitution substitution() { + return substitution; + } + + LibraryMembers libraryMembers() { + return libraryMembers; + } + + MemberFactory memberFactory() { + return memberFactory; + } + + MemberLookup lookup() { + return lookup; + } + + FactTypes factTypes() { + return factTypes; + } + + int typeRevision() { + return caches.typeRevision; + } + + void invalidateTypeCaches() { + caches.typeRevision++; + caches.subtypeCache.clear(); + } + + boolean isSubtype(JType sub, Type sup) { + if (!(sup instanceof JType target) || sub.kind == JType.Kind.CAPTURE || target.kind == JType.Kind.CAPTURE + || sub.kind == JType.Kind.TYPEVAR || target.kind == JType.Kind.TYPEVAR) { + return Subtyping.isSubtype(sub, sup, new HashSet<>()); + } + SubtypeKey key = new SubtypeKey(sub, target); + Boolean cached = caches.subtypeCache.get(key); + if (cached != null) { + return cached; + } + boolean result = Subtyping.isSubtype(sub, target, new HashSet<>()); + caches.subtypeCache.put(key, result); + return result; + } + + @Nullable + MemberId parseMember(String id) { + MemberId cached = caches.parsedMemberIds.computeIfAbsent(id, key -> { + MemberId parsed = SemaFacts.parseMember(key); + return parsed == null ? NOT_A_MEMBER : parsed; + }); + return cached == NOT_A_MEMBER ? null : cached; + } + + @Nullable + String memberName(String id) { + MemberId parsed = parseMember(id); + return parsed == null ? null : parsed.name(); + } + + /** + * Reads the symbols and graph facts of one CST document. Type declarations already known by + * erased name are reused, so a later {@link #ingestTypes} call fills them in instead of + * creating a second symbol. + */ + void ingestDocument(Document document) { + factTypes.invalidateDeclaredVariables(); + for (FactEntry entry : document.getFactsList()) { + facts.put(entry.getKey(), entry.getValue()); + } + for (org.sonarsource.semsitter.wire.Symbol element : document.getSymbolsList()) { + String id = element.getId(); + if (!id.isEmpty()) { + dumpSymbols.put(id, element); + if ("type".equals(element.getKind()) && id.indexOf('<') < 0) { + caches.binaryNames.binaryName(erase(id)); + } + } + } + for (String id : dumpSymbols.keySet()) { + libraryMembers().createDumpSymbol(id); + } + for (String id : new ArrayList<>(dumpSymbols.keySet())) { + libraryMembers().linkDumpSymbol(id); + } + } + + String sourceName(String fqn) { + return caches.binaryNames.sourceName(fqn); + } + + /** Whether the document of this file declares the symbol {@code id}. */ + boolean inDocument(String id) { + return dumpSymbols.containsKey(id); + } + + /** + * Loads the declarations of every type the document references, then keeps {@code loader} to + * fetch the types reached later, like the return type of a library method. + */ + void loadTypes(Function, JsonObject> loader) { + typeLoader = names -> { + JsonObject answer = loader.apply(names); + return answer == null ? new JsonObject() : answer; + }; + Set names = referencedTypeNames(); + caches.requestedTypes.addAll(names); + ingestTypes(typeLoader.apply(names)); + markUndeclared(); + } + + void ingestTypes(JsonObject types) { + typesLoaded = true; + boolean changed = false; + for (Map.Entry entry : types.entrySet()) { + JsonObject info = entry.getValue().getAsJsonObject(); + if (!FRAMEWORK_TYPES && "framework-db".equals(text(info, "origin"))) { + continue; + } + changed = true; + typeInfos.put(entry.getKey(), info); + lookup().invalidate(entry.getKey()); + libraryMembers().registerProjectMembers(info); + JTypeSymbol symbol = typesByName.get(entry.getKey()); + if (symbol == null) { + symbol = new JTypeSymbol(this, entry.getKey(), simpleName(entry.getKey()), false); + symbol.owner(packageSymbol(packageName(entry.getKey()))); + symbol.type(rawNamed(entry.getKey())); + typesByName.put(entry.getKey(), symbol); + symbols.putIfAbsent(entry.getKey(), symbol); + } + memberFactory().applyTypeInfo(symbol, info); + } + if (changed) { + invalidateTypeCaches(); + } + } + + Set referencedTypeNames() { + Set names = new HashSet<>(); + for (String id : facts.keySet()) { + addTypeName(names, id); + } + for (org.sonarsource.semsitter.wire.Symbol symbol : dumpSymbols.values()) { + addTypeName(names, symbol.getId()); + TypeRef type = typeFact(symbol); + if (type != null) { + collectFactNames(names, type); + } + } + return names; + } + + void declare(String id, Tree tree) { + declarations.put(id, tree); + if (symbols.get(id) instanceof JTypeSymbol type) { + type.invalidateMembers(); + } + } + + void use(String id, IdentifierTree tree) { + usages.computeIfAbsent(id, key -> new ArrayList<>()).add(tree); + } + + @Override + public Type getClassType(String fullyQualifiedName) { + if (fullyQualifiedName == null || fullyQualifiedName.isBlank() || SemaFacts.UNKNOWN_TYPE_NAME.equals(fullyQualifiedName)) { + return Type.UNKNOWN; + } + if (SemaFacts.NULL_TYPE_NAME.equals(fullyQualifiedName)) { + return JType.nullType(this); + } + if (fullyQualifiedName.endsWith(SemaFacts.ARRAY_SUFFIX)) { + JType element = asJType(getClassType(fullyQualifiedName.substring(0, fullyQualifiedName.length() - SemaFacts.ARRAY_SUFFIX.length()))); + return memberFactory().arraySymbol(element).type(); + } + if (PRIMITIVES.contains(fullyQualifiedName)) { + return primitiveType(fullyQualifiedName); + } + typeSymbol(fullyQualifiedName); + return rawNamed(fullyQualifiedName); + } + + JSymbol resolve(@Nullable String id) { + if (id == null || id.isEmpty()) { + return unknownSymbol; + } + JSymbol found = symbols.get(id); + if (found != null) { + return found; + } + if (dumpSymbols.containsKey(id)) { + libraryMembers().createDumpSymbol(id); + libraryMembers().linkDumpSymbol(id); + return symbols.getOrDefault(id, unknownSymbol); + } + if (id.indexOf('#') >= 0) { + return memberFactory().createMember(id); + } + if (id.indexOf('<') >= 0) { + return memberFactory().typeParameter(id); + } + return typeSymbol(erase(id)); + } + + Symbol.TypeSymbol resolveTypeSymbol(@Nullable String id) { + JSymbol symbol = resolve(id); + return symbol instanceof Symbol.TypeSymbol typeSymbol ? typeSymbol : Symbol.TypeSymbol.UNKNOWN_TYPE; + } + + JTypeSymbol typeSymbol(String name) { + String fqn = sourceName(name); + JTypeSymbol found = typesByName.get(fqn); + if (found != null) { + return found; + } + JTypeSymbol created = new JTypeSymbol(this, fqn, simpleName(fqn), false); + created.owner(packageSymbol(packageName(fqn))); + created.type(rawNamed(fqn)); + typesByName.put(fqn, created); + symbols.putIfAbsent(fqn, created); + if (typesLoaded && caches.requestedTypes.add(fqn)) { + JsonObject loaded = typeLoader.apply(Set.of(fqn)); + if (loaded == null) { + return created; + } + ingestTypes(loaded); + if (typeInfos.containsKey(fqn)) { + return created; + } + } + if (typesLoaded && !isWellKnown(fqn)) { + created.unknown(true); + } + return created; + } + + JType primitiveType(String name) { + return caches.rawTypes.computeIfAbsent(name, key -> JType.primitive(this, key)); + } + + JType asJType(Type type) { + return type instanceof JType jType ? jType : JType.unknown(this); + } + + JType rawNamed(String fqn) { + return caches.rawTypes.computeIfAbsent(sourceName(fqn), name -> JType.named(this, caches.binaryNames.binaryOf(name), List.of())); + } + + /** Whether the project, the classpath or the JDK declares the type {@code fqn}. */ + boolean declaresType(String name) { + String fqn = sourceName(name); + if (!typeInfos.containsKey(fqn) && typesLoaded && caches.requestedTypes.add(fqn)) { + ingestTypes(typeLoader.apply(Set.of(fqn))); + } + return typeInfos.containsKey(fqn); + } + + Symbol packageSymbol(String name) { + if (name == null || name.isEmpty()) { + return Symbol.ROOT_PACKAGE; + } + String key = "pkg:" + name; + JSymbol found = symbols.get(key); + if (found != null) { + return found; + } + JPackageSymbol pkg = new JPackageSymbol(this, name); + symbols.put(key, pkg); + pkg.owner(Symbol.ROOT_PACKAGE); + return pkg; + } + + /** A type some symbol names that no answer declares and the file does not declare is unknown, whenever its symbol was created. */ + private void markUndeclared() { + Set missing = new HashSet<>(); + for (Map.Entry entry : typesByName.entrySet()) { + String fqn = entry.getKey(); + JTypeSymbol symbol = entry.getValue(); + if (!typeInfos.containsKey(fqn) && !isWellKnown(fqn) && !facts.containsKey(fqn) && !dumpSymbols.containsKey(fqn) && !symbol.isUnknown() + && !symbol.isTypeParameter() && SemaFacts.isPlainTypeName(fqn)) { + missing.add(fqn); + } + } + Set fresh = new HashSet<>(missing); + fresh.removeIf(name -> !caches.requestedTypes.add(name)); + if (!fresh.isEmpty()) { + ingestTypes(typeLoader.apply(fresh)); + } + for (String fqn : missing) { + if (!typeInfos.containsKey(fqn)) { + typesByName.get(fqn).unknown(true); + } + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbol.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbol.java new file mode 100644 index 00000000000..f0c8c247e82 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbol.java @@ -0,0 +1,335 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import javax.annotation.Nullable; +import org.sonar.java.model.Symbols; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.SymbolMetadata; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.VariableTree; + +/** + * A symbol keyed by its SemSitter id. Two symbols with the same id are equal across files, + * which is what a rule needs when the declaration and the use were translated separately. + */ +abstract class JSymbol implements Symbol { + + enum Kind { + TYPE, METHOD, VARIABLE, PACKAGE + } + + final JSema sema; + final Kind kind; + + @Nullable + final String id; + + private final String name; + private Symbol owner = Symbol.UNKNOWN_SYMBOL; + private Type type = Type.UNKNOWN; + private boolean unknown; + private boolean enumSymbol; + private boolean interfaceSymbol; + private boolean annotationSymbol; + private boolean receiver; + private boolean deprecated; + private static final String PRIVATE = "private"; + private final Set modifiers = new HashSet<>(); + private int hash; + + JSymbol(JSema sema, Kind kind, @Nullable String id, String name) { + this.sema = Objects.requireNonNull(sema); + this.kind = kind; + this.id = id; + this.name = name; + } + + void owner(Symbol owner) { + this.owner = owner; + } + + void type(Type type) { + this.type = type == null ? Type.UNKNOWN : type; + } + + void unknown(boolean unknown) { + this.unknown = unknown; + } + + void enumSymbol(boolean enumSymbol) { + this.enumSymbol = enumSymbol; + } + + void interfaceSymbol(boolean interfaceSymbol) { + this.interfaceSymbol = interfaceSymbol; + } + + void annotationSymbol(boolean annotationSymbol) { + this.annotationSymbol = annotationSymbol; + } + + boolean isAnnotationSymbol() { + return annotationSymbol; + } + + /** {@code this} and {@code super}, which have no visibility. */ + void receiver(boolean receiver) { + this.receiver = receiver; + } + + void deprecated(boolean deprecated) { + this.deprecated = deprecated; + } + + void copyStateFrom(JSymbol other) { + owner = other.owner; + unknown = other.unknown; + enumSymbol = other.enumSymbol; + interfaceSymbol = other.interfaceSymbol; + annotationSymbol = other.annotationSymbol; + deprecated = other.deprecated; + modifiers.addAll(other.modifiers); + } + + void addModifiers(Collection values) { + for (String value : values) { + for (String part : value.split(",")) { + if (!part.isBlank()) { + modifiers.add(part.trim()); + } + } + } + } + + boolean hasModifier(String modifier) { + return modifiers.contains(modifier); + } + + @Override + public final boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof JSymbol other) || kind != other.kind) { + return false; + } + if (id != null && other.id != null) { + return id.equals(other.id); + } + return name.equals(other.name) && Objects.equals(owner, other.owner); + } + + @Override + public final int hashCode() { + if (hash == 0) { + hash = Objects.hash(kind, id != null ? id : name); + } + return hash; + } + + @Override + public final String name() { + return name; + } + + @Override + public final Symbol owner() { + return owner; + } + + @Override + public Type type() { + return type; + } + + @Override + public final boolean isVariableSymbol() { + return kind == Kind.VARIABLE; + } + + @Override + public final boolean isTypeSymbol() { + return !isUnknown() && kind == Kind.TYPE; + } + + @Override + public final boolean isMethodSymbol() { + return kind == Kind.METHOD; + } + + @Override + public final boolean isPackageSymbol() { + return kind == Kind.PACKAGE; + } + + @Override + public final boolean isStatic() { + return hasModifier("static") || (inInterface() && (isVariableSymbol() || isTypeSymbol())) || enumConstant() || implicitlyStaticType(); + } + + @Override + public final boolean isFinal() { + return hasModifier("final") || (inInterface() && isVariableSymbol()) || enumConstant() || multiCatchParameter(); + } + + @Override + public final boolean isEnum() { + return enumSymbol; + } + + @Override + public final boolean isInterface() { + return interfaceSymbol; + } + + @Override + public final boolean isAbstract() { + if (interfaceSymbol) { + return false; + } + return hasModifier("abstract") + || (inInterface() && isMethodSymbol() && !hasModifier("default") && !hasModifier("static") && !hasModifier(PRIVATE)); + } + + @Override + public final boolean isPublic() { + return hasModifier("public") || (inInterface() && !hasModifier(PRIVATE)) || enumConstant() || implicitRecordAccessor(); + } + + @Override + public final boolean isPrivate() { + return hasModifier(PRIVATE) || enumConstructor(); + } + + @Override + public final boolean isProtected() { + return hasModifier("protected"); + } + + @Override + public final boolean isPackageVisibility() { + return !receiver && !isPublic() && !isPrivate() && !isProtected(); + } + + @Override + public final boolean isDeprecated() { + return deprecated; + } + + @Override + public final boolean isVolatile() { + return hasModifier("volatile"); + } + + @Override + public boolean isUnknown() { + return unknown; + } + + @Override + public final SymbolMetadata metadata() { + return Symbols.EMPTY_METADATA; + } + + @Nullable + @Override + public TypeSymbol enclosingClass() { + if (this instanceof JTypeSymbol typeSymbol && typeSymbol.isTypeParameter()) { + return owner() instanceof TypeSymbol ownerType ? ownerType : null; + } + // A nested or local type is enclosed by the class declaring it; a top-level one by itself. + boolean declaresType = kind == Kind.TYPE; + Symbol current = declaresType ? owner() : this; + if (declaresType && !(current instanceof Symbol.MethodSymbol) && !isTypeKind(current)) { + return (TypeSymbol) this; + } + while (!isTypeKind(current)) { + if (current.isPackageSymbol() || current.isUnknown()) { + return null; + } + current = current.owner(); + } + return (TypeSymbol) current; + } + + @Override + public final List usages() { + if (id == null) { + return Collections.emptyList(); + } + List found = sema.usages.get(id); + return found == null ? Collections.emptyList() : found; + } + + @Nullable + @Override + public Tree declaration() { + return id == null ? null : sema.declarations.get(id); + } + + @Override + public String toString() { + return id == null ? name : id; + } + + /** A nested or local record, enum or interface is implicitly static. */ + private boolean implicitlyStaticType() { + return isTypeSymbol() && !owner.isPackageSymbol() + && (enumSymbol || interfaceSymbol + || (declaration() instanceof ClassTree declared && declared.is(Tree.Kind.RECORD, Tree.Kind.ENUM, Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE))); + } + + private boolean multiCatchParameter() { + return isVariableSymbol() && declaration() instanceof VariableTree variable && variable.type().is(Tree.Kind.UNION_TYPE); + } + + /** The accessor a record declares implicitly for each of its components is public. */ + private boolean implicitRecordAccessor() { + return isMethodSymbol() && declaration() == null && owner instanceof JSymbol ownerType && ownerType.declaration() instanceof ClassTree recordTree + && recordTree.is(Tree.Kind.RECORD) && recordTree.recordComponents().stream().anyMatch(component -> component.simpleName().name().equals(name)); + } + + /** Whether this is a member of an interface or annotation type, which gives it implicit modifiers. */ + private boolean inInterface() { + return owner instanceof JSymbol ownerType && ownerType.isTypeSymbol() && ownerType.interfaceSymbol + && !(this instanceof JTypeSymbol typeSymbol && typeSymbol.isTypeParameter()); + } + + private boolean enumConstant() { + return isVariableSymbol() && enumSymbol; + } + + /** Enum constructors are private whatever they declare. */ + private boolean enumConstructor() { + return isMethodSymbol() && SemaFacts.CONSTRUCTOR_NAME.equals(name) && owner instanceof JSymbol ownerType && ownerType.isTypeSymbol() && ownerType.enumSymbol; + } + + /** Whether {@code symbol} is declared as a type, resolved or not. */ + private static boolean isTypeKind(Symbol symbol) { + return symbol instanceof JSymbol declared ? (declared.kind == Kind.TYPE) : symbol.isTypeSymbol(); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JType.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JType.java new file mode 100644 index 00000000000..8b42803d361 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JType.java @@ -0,0 +1,453 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import javax.annotation.Nullable; +import org.sonar.java.model.JUtils; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; + +/** + * A type recovered from a SemSitter symbol fact or a JVM descriptor. + * Fully-qualified names are erased binary names ({@code java.util.Map$Entry}). + */ +final class JType implements Type.ArrayType { + + enum Kind { + NAMED, PRIMITIVE, VOID, NULL, ARRAY, TYPEVAR, UNKNOWN, INTERSECTION, CAPTURE, WILDCARD + } + + private static final Set NUMERIC = Set.of("byte", "char", "short", "int", "long", "float", "double"); + final JSema sema; + final Kind kind; + final String fqn; + final List args; + + @Nullable + final JType element; + + @Nullable + final String typeVarId; + + final List intersectionBounds; + + @Nullable + final JType lower; + + @Nullable + private String cachedName; + + @Nullable + private Boolean cachedParameterized; + + private boolean cachedUnknown; + private int cachedUnknownRevision = -1; + + @Nullable + private JTypeSymbol parameterizedSymbol; + + private int parameterizedSymbolRevision = -1; + + private record Parts(@Nullable JType element, @Nullable String typeVarId, List intersectionBounds, @Nullable JType lower) { + } + + private JType(JSema sema, Kind kind, String fqn, List args, @Nullable JType element, @Nullable String typeVarId, List intersection) { + this(sema, kind, fqn, args, new Parts(element, typeVarId, intersection, null)); + } + + private JType(JSema sema, Kind kind, String fqn, List args, Parts parts) { + this.sema = sema; + this.kind = kind; + this.fqn = fqn; + this.args = args; + this.element = parts.element(); + this.typeVarId = parts.typeVarId(); + this.intersectionBounds = parts.intersectionBounds(); + this.lower = parts.lower(); + } + + static JType named(JSema sema, String fqn, List args) { + return new JType(sema, Kind.NAMED, fqn, List.copyOf(args), null, null, List.of()); + } + + static JType primitive(JSema sema, String name) { + return new JType(sema, "void".equals(name) ? Kind.VOID : Kind.PRIMITIVE, name, List.of(), null, null, List.of()); + } + + static JType nullType(JSema sema) { + return new JType(sema, Kind.NULL, SemaFacts.NULL_TYPE_NAME, List.of(), null, null, List.of()); + } + + static JType unknown(JSema sema) { + return new JType(sema, Kind.UNKNOWN, SemaFacts.UNKNOWN_TYPE_NAME, List.of(), null, null, List.of()); + } + + static JType array(JSema sema, JType element) { + return new JType(sema, Kind.ARRAY, element.fullyQualifiedName() + SemaFacts.ARRAY_SUFFIX, List.of(), element, null, List.of()); + } + + static JType typeVar(JSema sema, String name, String id) { + return new JType(sema, Kind.TYPEVAR, name, List.of(), null, id, List.of()); + } + + /** Replaces type variables named in {@code substitution} inside this type. */ + JType substitute(Map substitution) { + if (kind == Kind.TYPEVAR) { + JType replacement = typeVarReplacement(substitution); + if (replacement != null) { + return replacement; + } + } + if (kind == Kind.CAPTURE) { + JType replaced = element.substitute(substitution); + return replaced == element ? this : capture(sema, replaced); + } + if (kind == Kind.WILDCARD) { + return substituteWildcard(substitution); + } + if (kind == Kind.ARRAY) { + JType replaced = element.substitute(substitution); + return replaced == element ? this : array(sema, replaced); + } + if (kind == Kind.NAMED && !args.isEmpty()) { + return substituteArguments(substitution); + } + return this; + } + + static JType capture(JSema sema, JType upper) { + return new JType(sema, Kind.CAPTURE, "!capture!", List.of(), upper, null, List.of()); + } + + /** A wildcard type argument, named after the erasure of its upper bound as ECJ names it. */ + static JType wildcard(JSema sema, JType upper) { + if (upper.isUnknown()) { + return upper; + } + return new JType(sema, Kind.WILDCARD, upper.erasure().fullyQualifiedName(), List.of(), upper, null, List.of()); + } + + /** A {@code ? super lower} type argument, which ECJ names after its implicit upper bound {@code Object}. */ + static JType superWildcard(JSema sema, JType lower) { + JType object = (JType) sema.getClassType(SemaFacts.OBJECT_TYPE); + return new JType(sema, Kind.WILDCARD, object.fullyQualifiedName(), List.of(), new Parts(object, null, List.of(), lower)); + } + + boolean isWildcard() { + return kind == Kind.WILDCARD; + } + + static JType intersection(JSema sema, List bounds) { + String name = bounds.stream().map(JType::fullyQualifiedName).sorted().reduce((a, b) -> a + " & " + b).orElse(SemaFacts.UNKNOWN_TYPE_NAME); + return new JType(sema, Kind.INTERSECTION, name, List.of(), null, null, List.copyOf(bounds)); + } + + @Override + public boolean is(String fullyQualifiedName) { + return fullyQualifiedName.equals(this.fullyQualifiedName()); + } + + @Override + public boolean isSubtypeOf(String fullyQualifiedName) { + return isSubtypeOf(sema.getClassType(fullyQualifiedName)); + } + + @Override + public boolean isSubtypeOf(Type superType) { + return sema.isSubtype(this, superType); + } + + @Override + public boolean isArray() { + return kind == Kind.ARRAY; + } + + boolean isCapture() { + return kind == Kind.CAPTURE; + } + + @Override + public boolean isClass() { + return kind == Kind.NAMED && !isUnknown(); + } + + @Override + public boolean isVoid() { + return kind == Kind.VOID; + } + + @Override + public boolean isPrimitive() { + return kind == Kind.PRIMITIVE; + } + + @Override + public boolean isPrimitive(Primitives primitive) { + return primitive.name().toLowerCase(Locale.ROOT).equals(fullyQualifiedName()); + } + + @Override + public boolean isPrimitiveWrapper() { + return isClass() && JUtils.WRAPPER_TO_PRIMITIVE.containsKey(fullyQualifiedName()); + } + + @Nullable + @Override + public Type primitiveWrapperType() { + String name = JUtils.PRIMITIVE_TO_WRAPPER.get(fullyQualifiedName()); + return name == null ? null : sema.getClassType(name); + } + + @Nullable + @Override + public Type primitiveType() { + String name = JUtils.WRAPPER_TO_PRIMITIVE.get(fullyQualifiedName()); + return name == null ? null : sema.getClassType(name); + } + + @Override + public boolean isNullType() { + return kind == Kind.NULL; + } + + @Override + public boolean isTypeVar() { + return kind == Kind.TYPEVAR; + } + + @Override + public boolean isRawType() { + return kind == Kind.NAMED && !isUnknown() && args.isEmpty() && sema.typeSymbol(fqn).typeParameterCount() > 0; + } + + @Override + public Type declaringType() { + if (isUnknown() || kind != Kind.NAMED) { + return this; + } + if (isRawType()) { + return sema.typeSymbol(fqn).declaringType(this); + } + return sema.getClassType(fqn); + } + + @Override + public boolean isUnknown() { + if (kind == Kind.UNKNOWN) { + return true; + } + if (kind == Kind.ARRAY) { + return element.isUnknown(); + } + if (kind == Kind.NAMED) { + int revision = sema.typeRevision(); + if (cachedUnknownRevision == revision) { + return cachedUnknown; + } + Symbol.TypeSymbol owner = declaredSymbol(); + // the compiler cannot bind a parameterization with an argument nothing declares + boolean result = owner.isUnknown() || args.stream().anyMatch(JType::isUnknown); + cachedUnknown = result; + cachedUnknownRevision = sema.typeRevision(); + return result; + } + return false; + } + + @Override + public boolean isNumerical() { + return NUMERIC.contains(fullyQualifiedName()); + } + + @Override + public String fullyQualifiedName() { + return fqn; + } + + @Override + public String name() { + if (cachedName == null) { + cachedName = computeName(); + } + return cachedName; + } + + @Override + public String toString() { + return name(); + } + + @Override + public Symbol.TypeSymbol symbol() { + if (args.isEmpty()) { + return declaredSymbol(); + } + int revision = sema.typeRevision(); + if (parameterizedSymbol == null || parameterizedSymbolRevision != revision) { + parameterizedSymbol = sema.typeSymbol(fqn).parameterizedAs(this); + parameterizedSymbolRevision = sema.typeRevision(); + } + return parameterizedSymbol; + } + + Symbol.TypeSymbol declaredSymbol() { + return switch (kind) { + case ARRAY -> sema.memberFactory().arraySymbol(element); + case PRIMITIVE, VOID -> sema.memberFactory().primitiveSymbol(fqn); + case TYPEVAR -> sema.resolveTypeSymbol(typeVarId); + case NULL, UNKNOWN, INTERSECTION -> Symbol.TypeSymbol.UNKNOWN_TYPE; + case CAPTURE, WILDCARD -> element.symbol(); + case NAMED -> sema.typeSymbol(fqn); + }; + } + + @Override + public Type erasure() { + if (kind == Kind.CAPTURE || kind == Kind.WILDCARD) { + return element.erasure(); + } + if (kind == Kind.ARRAY) { + return JType.array(sema, (JType) element.erasure()); + } + if (kind == Kind.NAMED && !args.isEmpty()) { + return sema.getClassType(fqn); + } + if (kind == Kind.TYPEVAR && typeVarId != null) { + Type bound = sema.memberFactory().typeVariableBound(typeVarId); + return bound == this ? this : bound.erasure(); + } + return this; + } + + @Override + public boolean isParameterized() { + if (cachedParameterized == null) { + cachedParameterized = kind == Kind.NAMED && !args.isEmpty() && !isGenericSelf(); + } + return cachedParameterized; + } + + @Override + public List typeArguments() { + return Collections.unmodifiableList(args); + } + + @Override + public Type elementType() { + return element == null ? Type.UNKNOWN : element; + } + + @Override + public boolean isIntersectionType() { + return kind == Kind.INTERSECTION; + } + + @Override + public Type[] getIntersectionTypes() { + if (intersectionBounds.isEmpty()) { + return new Type[] {this}; + } + return intersectionBounds.toArray(Type[]::new); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof JType other) || kind == Kind.CAPTURE) { + return false; + } + if (kind == Kind.WILDCARD) { + return other.kind == Kind.WILDCARD && Objects.equals(element, other.element) && Objects.equals(lower, other.lower); + } + return kind == other.kind && fqn.equals(other.fqn) && args.equals(other.args) && (kind != Kind.ARRAY || Objects.equals(element, other.element)) && sameTypeVariable(other); + } + + @Override + public int hashCode() { + return fqn.hashCode(); + } + + @Nullable + private JType typeVarReplacement(Map substitution) { + Type found = typeVarId == null ? null : substitution.get(typeVarId); + if (found == null) { + found = substitution.get(fqn); + } + return found instanceof JType replaced ? replaced : null; + } + + private JType substituteWildcard(Map substitution) { + if (lower != null) { + JType replaced = lower.substitute(substitution); + return replaced == lower ? this : superWildcard(sema, replaced); + } + JType replaced = element.substitute(substitution); + return replaced == element ? this : wildcard(sema, replaced); + } + + private JType substituteArguments(Map substitution) { + List replaced = new ArrayList<>(); + boolean changed = false; + for (JType argument : args) { + JType next = argument.substitute(substitution); + changed |= next != argument; + replaced.add(next); + } + return changed ? named(sema, fqn, replaced) : this; + } + + private String computeName() { + if (kind == Kind.NULL) { + return SemaFacts.NULL_TYPE_NAME; + } + if (kind == Kind.ARRAY) { + return element.name() + SemaFacts.ARRAY_SUFFIX; + } + if (kind == Kind.WILDCARD) { + if (lower != null) { + return "? super " + lower.name(); + } + return element.is(SemaFacts.OBJECT_TYPE) ? "?" : ("? extends " + element.name()); + } + int boundary = Math.max(fqn.lastIndexOf('.'), fqn.lastIndexOf('$')); + String simple = boundary < 0 ? fqn : fqn.substring(boundary + 1); + return SemaFacts.isAnonymousName(simple) ? "" : simple; + } + + /** The type written with its own type parameters is the generic declaration itself, not a parameterization. */ + private boolean isGenericSelf() { + String owner = fqn + "`" + args.size() + "<"; + return args.stream().allMatch(argument -> argument.kind == Kind.TYPEVAR && argument.typeVarId != null && argument.typeVarId.startsWith(owner)); + } + + /** A type variable a signature names by its simple name is the one of that name the declaration spells with its full id. */ + private boolean sameTypeVariable(JType other) { + if (Objects.equals(typeVarId, other.typeVarId)) { + return true; + } + return typeVarId != null && other.typeVarId != null && (typeVarId.indexOf('<') < 0 || other.typeVarId.indexOf('<') < 0); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JTypeSymbol.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JTypeSymbol.java new file mode 100644 index 00000000000..fd4cd5f22bf --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JTypeSymbol.java @@ -0,0 +1,620 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.annotation.CheckForNull; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.MethodTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.TypeTree; +import org.sonar.plugins.java.api.tree.VariableTree; + +final class JTypeSymbol extends JSymbol implements Symbol.TypeSymbol { + + private static final String ENUM = "java.lang.Enum"; + private static final String OBJECT = "java.lang.Object"; + private final boolean typeParameter; + private int typeParameterCount; + private JType declaringType; + + @Nullable + private String superName; + + private List interfaceNames = List.of(); + + @Nullable + private JsonObject superTypeFact; + + private List interfaceTypeFacts = List.of(); + private List memberFacts = List.of(); + + @Nullable + private String elementFqn; + + private static final class HierarchyCache { + @Nullable + private Type superClass; + private int superClassRevision = -1; + @Nullable + private List interfaces; + private int interfacesRevision = -1; + @Nullable + private Set superTypes; + private int superTypesRevision = -1; + } + + private static final class MemberIndex { + @Nullable + private Map> byName; + @Nullable + private Map> factsByName; + @Nullable + private List unindexedFacts; + @Nullable + private Map> resolvedByName; + } + + private Collection members; + private final MemberIndex memberIndex = new MemberIndex(); + + @Nullable + private Type declaredSuperClass; + + private List declaredInterfaces = List.of(); + + @Nullable + private JTypeSymbol generic; + + private final HierarchyCache hierarchy = new HierarchyCache(); + + JTypeSymbol(JSema sema, @Nullable String id, String name, boolean typeParameter) { + super(sema, Kind.TYPE, id, name); + this.typeParameter = typeParameter; + } + + private List boundTrees = List.of(); + + @Override + void unknown(boolean unknown) { + if (isUnknown() != unknown) { + super.unknown(unknown); + sema.invalidateTypeCaches(); + } + } + + /** + * A view of this generic type symbol whose {@link #type()} is the given parameterization, + * so that {@code type.symbol().type()} keeps the type arguments. + */ + JTypeSymbol parameterizedAs(JType parameterized) { + JTypeSymbol view = new JTypeSymbol(sema, id, name(), typeParameter); + view.copyStateFrom(this); + view.type(parameterized); + view.typeParameterCount = typeParameterCount; + view.superName = superName; + view.interfaceNames = interfaceNames; + view.superTypeFact = superTypeFact; + view.interfaceTypeFacts = interfaceTypeFacts; + view.memberFacts = memberFacts; + view.elementFqn = elementFqn; + view.declaredSuperClass = declaredSuperClass; + view.declaredInterfaces = declaredInterfaces; + view.generic = this; + return view; + } + + void declaredSupertypes(@Nullable Type superClass, List interfaces) { + this.declaredSuperClass = superClass; + this.declaredInterfaces = List.copyOf(interfaces); + sema.invalidateTypeCaches(); + } + + boolean isTypeParameter() { + return typeParameter; + } + + void boundTrees(List bounds) { + this.boundTrees = List.copyOf(bounds); + sema.invalidateTypeCaches(); + } + + /** The first declared bound of a type parameter, or {@code null} when it has none. */ + @Nullable + Type firstBound() { + return boundTrees.isEmpty() ? null : boundTrees.get(0).symbolType(); + } + + /** Every declared bound of a type parameter. */ + List bounds() { + return boundTrees.stream().map(TypeTree::symbolType).toList(); + } + + /** The generic declaration of a raw use of this type: its type parameters as arguments, one instance per symbol. */ + JType declaringType(JType raw) { + if (declaringType == null) { + List variables = new ArrayList<>(); + for (int i = 0; i < typeParameterCount; i++) { + variables.add(JType.typeVar(sema, "T" + i, raw.fqn + "<" + i + ">")); + } + declaringType = JType.named(sema, raw.fqn, variables); + } + return declaringType; + } + + int typeParameterCount() { + return typeParameterCount; + } + + void typeParameterCount(int typeParameterCount) { + this.typeParameterCount = typeParameterCount; + } + + void superName(@Nullable String superName) { + this.superName = superName; + sema.invalidateTypeCaches(); + } + + void interfaceNames(List interfaceNames) { + this.interfaceNames = interfaceNames; + sema.invalidateTypeCaches(); + } + + /** Supertypes with their type arguments, used when they name the same classes as the erased ones. */ + void genericSupertypes(@Nullable JsonObject superType, List interfaceTypes) { + this.superTypeFact = superType; + this.interfaceTypeFacts = interfaceTypes; + sema.invalidateTypeCaches(); + } + + /** The parameterization an anonymous class takes from a diamond on its named supertype. */ + void declaredSupertype(Type inferred) { + if (inferred.symbol().isInterface()) { + declaredInterfaces = List.of(inferred); + } else { + declaredSuperClass = inferred; + } + sema.invalidateTypeCaches(); + } + + void memberFacts(List memberFacts) { + this.memberFacts = memberFacts; + memberIndex.factsByName = null; + memberIndex.unindexedFacts = null; + invalidateMembers(); + } + + void invalidateMembers() { + this.members = null; + memberIndex.byName = null; + memberIndex.resolvedByName = null; + } + + void elementFqn(@Nullable String elementFqn) { + this.elementFqn = elementFqn; + } + + @CheckForNull + @Override + public Type superClass() { + int revision = sema.typeRevision(); + if (hierarchy.superClassRevision == revision) { + return hierarchy.superClass; + } + Type computed = computeSuperClass(); + hierarchy.superClass = computed; + hierarchy.superClassRevision = sema.typeRevision(); + return computed; + } + + @Override + public List interfaces() { + int revision = sema.typeRevision(); + if (hierarchy.interfaces != null && hierarchy.interfacesRevision == revision) { + return hierarchy.interfaces; + } + List declared = ownInterfaces(); + List computed = (generic == null || !type().isParameterized()) + ? List.copyOf(declared) + : declared.stream().map(iface -> sema.substitution().instantiateSupertype(type(), iface)).toList(); + hierarchy.interfaces = computed; + hierarchy.interfacesRevision = sema.typeRevision(); + return computed; + } + + @Override + public Collection memberSymbols() { + if (generic != null) { + return generic.memberSymbols(); + } + if (members == null) { + List resolved = new ArrayList<>(); + for (JsonObject member : memberFacts) { + if (!isTypeParameterFact(member)) { + resolved.add(sema.libraryMembers().memberFromTypeInfo(this, member)); + } + } + addImplicitConstructor(resolved); + addImplicitEnumMethods(resolved); + addDeclaredMembers(resolved); + members = resolved; + } + return members; + } + + @Override + public Collection lookupSymbols(String name) { + return new HashSet<>(membersNamed(name)); + } + + /** + * The members named {@code name}, in the order of {@link #memberSymbols()}. Of a type another file or a library declares, + * only the members that may have that name are created, so a type with thousands of members costs a few per lookup. + */ + List membersNamed(String name) { + if (generic != null) { + return generic.membersNamed(name); + } + if (members != null || id == null || sema.inDocument(id) || declaration() != null) { + if (memberIndex.byName == null) { + memberIndex.byName = indexSymbolsByName(memberSymbols()); + } + return memberIndex.byName.getOrDefault(name, List.of()); + } + if (memberIndex.resolvedByName != null) { + List cached = memberIndex.resolvedByName.get(name); + if (cached != null) { + return cached; + } + } + List resolved = resolveMembersNamed(name); + if (memberIndex.resolvedByName == null) { + memberIndex.resolvedByName = new HashMap<>(); + } + memberIndex.resolvedByName.put(name, resolved); + return resolved; + } + + @Nullable + @Override + public ClassTree declaration() { + return super.declaration() instanceof ClassTree classTree ? classTree : null; + } + + @Override + public Set superTypes() { + if (isUnknown()) { + return Collections.emptySet(); + } + int revision = sema.typeRevision(); + if (hierarchy.superTypes != null && hierarchy.superTypesRevision == revision) { + return hierarchy.superTypes; + } + Set collected = new HashSet<>(); + collectSuperTypes(collected, new HashSet<>(), type()); + Set result = Collections.unmodifiableSet(collected); + hierarchy.superTypes = result; + hierarchy.superTypesRevision = sema.typeRevision(); + return result; + } + + @Nullable + @Override + public TypeSymbol outermostClass() { + Symbol current = this; + Symbol result = this; + while (!current.isPackageSymbol()) { + result = current; + current = current.owner(); + } + return result instanceof TypeSymbol typeSymbol ? typeSymbol : this; + } + + @Override + public boolean isAnnotation() { + return !isUnknown() && isAnnotationSymbol(); + } + + @Nullable + private Type computeSuperClass() { + if (typeParameter || elementFqn != null) { + return sema.getClassType(OBJECT); + } + if (isInterface()) { + return sema.getClassType(OBJECT); + } + String erased = SemaFacts.erase(id == null ? name() : id); + if (OBJECT.equals(erased)) { + return null; + } + boolean noSuper = superName == null || superName.isEmpty(); + if (isEnum() && superTypeFact == null && (noSuper || ENUM.equals(SemaFacts.erase(superName))) && type() instanceof JType self) { + sema.getClassType(ENUM); + return JType.named(sema, ENUM, List.of(self)); + } + if (noSuper || inheritsFrom(erased) || interfaceDeclaredAsSuper() != null) { + return sema.getClassType(OBJECT); + } + if (namesSameClass(superTypeFact, superName)) { + return sema.factTypes().supertypeFromFact(superTypeFact); + } + return withDeclaredArguments(sema.getClassType(SemaFacts.erase(superName)), declaredSuperClass == null ? List.of() : List.of(declaredSuperClass)); + } + + private static Type withDeclaredArguments(Type erased, List declared) { + return declared.stream().filter(type -> type.isParameterized() && type.erasure().equals(erased)).findFirst().orElse(erased); + } + + private boolean inheritsFrom(String erasedSelf) { + Set visited = new HashSet<>(); + String current = SemaFacts.erase(superName); + while (visited.add(current)) { + if (current.equals(erasedSelf)) { + return true; + } + if (!(sema.getClassType(current).symbol() instanceof JTypeSymbol parent) || parent.superName == null || parent.superName.isEmpty()) { + return false; + } + current = SemaFacts.erase(parent.superName); + } + return false; + } + + private List ownInterfaces() { + List resolved = resolvedInterfaces(); + if (declaredInterfaces.isEmpty()) { + return resolved; + } + Set resolvedNames = HashSet.newHashSet(resolved.size()); + for (Type known : resolved) { + resolvedNames.add(known.fullyQualifiedName()); + } + List unresolved = declaredInterfaces.stream() + .filter(Type::isUnknown) + .filter(distinctByName(new HashSet<>())) + .filter(declared -> !resolvedNames.contains(declared.fullyQualifiedName())) + .toList(); + if (unresolved.isEmpty()) { + return resolved; + } + List all = new ArrayList<>(resolved); + all.addAll(unresolved); + return all; + } + + private static java.util.function.Predicate distinctByName(Set seen) { + return type -> seen.add(type.name()); + } + + private List resolvedInterfaces() { + if (elementFqn != null) { + return List.of(sema.getClassType("java.lang.Cloneable"), sema.getClassType("java.io.Serializable")); + } + if (interfaceNames.isEmpty()) { + return withInterfaceSuper(isAnnotation() ? List.of(sema.getClassType("java.lang.annotation.Annotation")) : List.of()); + } + boolean hasTypeFacts = interfaceTypeFacts.size() == interfaceNames.size(); + List types = new ArrayList<>(); + for (int i = 0; i < interfaceNames.size(); i++) { + String name = interfaceNames.get(i); + JsonObject fact = hasTypeFacts ? interfaceTypeFacts.get(i) : null; + Type erased = sema.getClassType(SemaFacts.erase(name)); + types.add(namesSameClass(fact, name) ? sema.factTypes().supertypeFromFact(fact) : withDeclaredArguments(erased, declaredInterfaces)); + } + return withInterfaceSuper(types); + } + + /** + * An anonymous class whose named supertype is an interface is recorded with that interface as its superclass. + * Java implements the interface and extends Object. + */ + @Nullable + private Type interfaceDeclaredAsSuper() { + if (superName == null || superName.isEmpty() || isInterface() || typeParameter) { + return null; + } + String erased = SemaFacts.erase(superName); + JTypeSymbol parent = sema.typeSymbol(erased); + if (!parent.isInterface() || parent.isUnknown()) { + return null; + } + return withDeclaredArguments(sema.getClassType(erased), declaredInterfaces); + } + + private List withInterfaceSuper(List interfaces) { + Type superInterface = interfaceDeclaredAsSuper(); + if (superInterface == null || interfaces.stream().anyMatch(type -> type.erasure().equals(superInterface.erasure()))) { + return interfaces; + } + List combined = new ArrayList<>(interfaces.size() + 1); + combined.add(superInterface); + combined.addAll(interfaces); + return combined; + } + + private static boolean namesSameClass(@Nullable JsonObject fact, String name) { + return fact != null && fact.has("id") && fact.get("id").isJsonPrimitive() + && SemaFacts.erase(fact.get("id").getAsString()).equals(SemaFacts.erase(name)); + } + + /** A local type has no member facts besides its constructor: its members are those its declaration writes. */ + private void addDeclaredMembers(List resolved) { + if (!(declaration() instanceof ClassTree tree) || resolved.stream().anyMatch(member -> !member.name().endsWith(SemaFacts.CONSTRUCTOR_NAME))) { + return; + } + tree.recordComponents().forEach(component -> resolved.add(component.symbol())); + for (Tree member : tree.members()) { + if (member instanceof VariableTree variable) { + resolved.add(variable.symbol()); + } else if (member instanceof MethodTree method && !method.is(Tree.Kind.CONSTRUCTOR)) { + resolved.add(method.symbol()); + } + } + } + + /** A type parameter is listed among the members of a project type but is not a member symbol. */ + private static boolean isTypeParameterFact(JsonObject member) { + return member.get("facts") instanceof JsonObject facts && facts.get("kind") instanceof JsonPrimitive kind && "typeparameter".equals(kind.getAsString()); + } + + /** An enum declared in this file has the static methods {@code values()} and {@code valueOf(String)}. */ + private void addImplicitEnumMethods(List resolved) { + if (id == null || isUnknown() || !isEnum() || declaration() == null || !(type() instanceof JType declared)) { + return; + } + if (resolved.stream().noneMatch(member -> member.isMethodSymbol() && "values".equals(member.name()))) { + JMethodSymbol values = implicitEnumMethod("values", List.of(), JType.array(sema, declared)); + resolved.add(values); + } + if (resolved.stream().noneMatch(member -> member.isMethodSymbol() && "valueOf".equals(member.name()))) { + resolved.add(implicitEnumMethod("valueOf", List.of(sema.getClassType("java.lang.String")), declared)); + } + } + + private JMethodSymbol implicitEnumMethod(String name, List parameters, Type returned) { + JMethodSymbol method = new JMethodSymbol(sema, id + "#" + name + "(" + (parameters.isEmpty() ? "" : "java.lang.String") + ")", name); + method.owner(this); + method.addModifiers(List.of("public", "static")); + method.parameterTypes(parameters); + method.returnTypeSymbol(returned.symbol()); + return method; + } + + /** A class of this file that declares no constructor still has the default one as a member. */ + private void addImplicitConstructor(List resolved) { + if (id == null || isUnknown() || isTypeParameter() || isInterface() || declaration() == null + || resolved.stream().anyMatch(member -> member.isMethodSymbol() && SemaFacts.CONSTRUCTOR_NAME.equals(member.name()))) { + return; + } + Symbol constructor = sema.resolve(id + "#()"); + if (!constructor.isUnknown()) { + resolved.add(constructor); + } + } + + private List resolveMembersNamed(String name) { + if (memberIndex.factsByName == null || memberIndex.unindexedFacts == null) { + indexMemberFacts(); + } + List named = memberIndex.factsByName.getOrDefault(name, List.of()); + List unindexed = memberIndex.unindexedFacts; + List found = new ArrayList<>(); + for (JsonObject member : named) { + Symbol symbol = sema.libraryMembers().memberFromTypeInfo(this, member); + if (name.equals(symbol.name())) { + found.add(symbol); + } + } + for (JsonObject member : unindexed) { + Symbol symbol = sema.libraryMembers().memberFromTypeInfo(this, member); + if (name.equals(symbol.name())) { + found.add(symbol); + } + } + return List.copyOf(found); + } + + private void indexMemberFacts() { + memberIndex.factsByName = new HashMap<>(); + memberIndex.unindexedFacts = new ArrayList<>(); + for (JsonObject member : memberFacts) { + if (isTypeParameterFact(member)) { + continue; + } + String simple = indexedFactName(member); + if (simple != null) { + memberIndex.factsByName.computeIfAbsent(simple, key -> new ArrayList<>()).add(member); + } else { + memberIndex.unindexedFacts.add(member); + } + } + } + + @Nullable + private String indexedFactName(JsonObject member) { + if (member.get("id") instanceof JsonPrimitive memberId) { + String simple = sema.memberName(memberId.getAsString()); + return simple != null && isIdentifier(simple) ? simple : null; + } + return member.get("name") instanceof JsonPrimitive written ? written.getAsString() : null; + } + + private static Map> indexSymbolsByName(Collection symbols) { + Map> indexed = new HashMap<>(); + for (Symbol member : symbols) { + indexed.computeIfAbsent(member.name(), key -> new ArrayList<>()).add(member); + } + return indexed; + } + + private static boolean isIdentifier(String text) { + if (text.isEmpty() || !Character.isJavaIdentifierStart(text.charAt(0))) { + return false; + } + for (int i = 1; i < text.length(); i++) { + if (!Character.isJavaIdentifierPart(text.charAt(i))) { + return false; + } + } + return true; + } + + /** Collects the supertypes, each seen with the type arguments {@code from} gives the type declaring it. */ + private void collectSuperTypes(Set collected, Set visited, Type from) { + if (!visited.add(SemaFacts.erase(id == null ? name() : id))) { + return; + } + Type superClass = superClass(); + if (superClass != null && isRecovered(superClass)) { + collected.add(superClass); + } else if (superClass != null && !superClass.isUnknown()) { + Type instantiated = sema.substitution().instantiateSupertype(from, superClass); + collected.add(instantiated); + if (superClass.symbol() instanceof JTypeSymbol parent) { + parent.collectSuperTypes(collected, visited, instantiated); + } + } + for (Type iface : interfaces()) { + if (isRecovered(iface)) { + collected.add(iface); + } else if (!iface.isUnknown()) { + Type instantiated = sema.substitution().instantiateSupertype(from, iface); + collected.add(instantiated); + if (iface.symbol() instanceof JTypeSymbol parent) { + parent.collectSuperTypes(collected, visited, instantiated); + } + } + } + } + + /** A type the sources name but nothing declares: it is kept among supertypes, unlike the unknown type itself. */ + private static boolean isRecovered(Type type) { + return type.isUnknown() && !type.name().isEmpty() && !type.fullyQualifiedName().startsWith("!"); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JVariableSymbol.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JVariableSymbol.java new file mode 100644 index 00000000000..f5295f7c21c --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JVariableSymbol.java @@ -0,0 +1,219 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import javax.annotation.Nullable; +import org.sonar.java.model.ExpressionUtils; +import org.sonar.java.model.LiteralUtils; +import org.sonar.java.model.Symbols; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.SymbolMetadata; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.LiteralTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.VariableTree; + +final class JVariableSymbol extends JSymbol implements Symbol.VariableSymbol { + + private final boolean parameter; + private final boolean local; + private boolean effectivelyFinal; + + @Nullable + private Object constant; + + private boolean constantResolved; + + JVariableSymbol(JSema sema, @Nullable String id, String name, String dumpKind) { + super(sema, Kind.VARIABLE, id, name); + this.parameter = "param".equals(dumpKind); + this.local = "local".equals(dumpKind); + this.effectivelyFinal = "constant".equals(dumpKind) || "enum_member".equals(dumpKind); + enumSymbol("enum_member".equals(dumpKind)); + } + + void effectivelyFinal(boolean effectivelyFinal) { + this.effectivelyFinal = effectivelyFinal; + } + + void constantValue(@Nullable Object value) { + this.constant = value; + this.constantResolved = true; + } + + @Nullable + @Override + public VariableTree declaration() { + return (VariableTree) super.declaration(); + } + + @Override + public boolean isEffectivelyFinal() { + return isFinal() || effectivelyFinal; + } + + @Override + public Optional constantValue() { + if (!constantResolved) { + Object declared = declaredConstant(); + constant = declared != null ? declared : sema.libraryMembers().servedConstant(this); + constantResolved = true; + } + return Optional.ofNullable(constant); + } + + @Override + public boolean isLocalVariable() { + return local || owner().isMethodSymbol(); + } + + @Override + public boolean isParameter() { + return parameter; + } + + /** A constant is a static final field with a compile time value, typed as its declaration. */ + @Nullable + private Object declaredConstant() { + VariableTree declaration = declaration(); + if (declaration == null || declaration.initializer() == null || declaration.type() == null || !isFinal() || !isStatic()) { + return null; + } + Type declaredType = declaration.type().symbolType(); + if (!declaredType.isPrimitive() && !declaredType.is("java.lang.String")) { + // a boxed variable is never a constant variable + return null; + } + ExpressionTree initializer = declaration.initializer(); + Object value = initializer.is(Tree.Kind.LONG_LITERAL, Tree.Kind.FLOAT_LITERAL, Tree.Kind.DOUBLE_LITERAL) + ? literalNumber((LiteralTree) initializer) + : ExpressionUtils.resolveAsConstant(initializer); + return convert(value, declaration.type().symbolType()); + } + + private static Object literalNumber(LiteralTree literal) { + String text = literal.value().replace("_", ""); + return switch (literal.kind()) { + case LONG_LITERAL -> LiteralUtils.longLiteralValue(literal); + case FLOAT_LITERAL -> Float.valueOf(text); + default -> Double.valueOf(text); + }; + } + + @Nullable + private static Object convert(@Nullable Object value, Type type) { + if (value instanceof Number number) { + if (type.is("long")) { + return number.longValue(); + } else if (type.is("double")) { + return number.doubleValue(); + } else if (type.is("float")) { + return number.floatValue(); + } + } + return value; + } + + static class ParameterPlaceholderSymbol extends Symbols.DefaultSymbol implements Symbol.VariableSymbol { + + private final String name; + private final Symbol owner; + private final Type type; + + ParameterPlaceholderSymbol(int index, Symbol owner, Type type) { + this.name = "arg" + index; + this.owner = owner; + this.type = type; + } + + @Override + public String name() { + return name; + } + + @Override + public Symbol owner() { + return owner; + } + + @Override + public Type type() { + return type; + } + + @Override + public boolean isUnknown() { + return false; + } + + @Override + public TypeSymbol enclosingClass() { + return owner.enclosingClass(); + } + + @Override + public List usages() { + return Collections.emptyList(); + } + + @Nullable + @Override + public VariableTree declaration() { + return null; + } + + @Override + public boolean isEffectivelyFinal() { + return false; + } + + @Override + public Optional constantValue() { + return Optional.empty(); + } + + @Override + public boolean isLocalVariable() { + return false; + } + + @Override + public boolean isParameter() { + return true; + } + + @Override + public SymbolMetadata metadata() { + return Symbols.EMPTY_METADATA; + } + + @Override + public boolean isVariableSymbol() { + return true; + } + + @Override + public boolean isFinal() { + return false; + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/LibraryMembers.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/LibraryMembers.java new file mode 100644 index 00000000000..157fb1c072c --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/LibraryMembers.java @@ -0,0 +1,339 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactValue; +import org.sonarsource.semsitter.wire.TypeRef; + +import static org.sonar.java.semsitter.SemaFacts.applyMemberFlags; +import static org.sonar.java.semsitter.SemaFacts.constantOf; +import static org.sonar.java.semsitter.SemaFacts.erase; +import static org.sonar.java.semsitter.SemaFacts.fact; +import static org.sonar.java.semsitter.SemaFacts.packageName; +import static org.sonar.java.semsitter.SemaFacts.simpleName; +import static org.sonar.java.semsitter.SemaFacts.strings; +import static org.sonar.java.semsitter.SemaFacts.text; +import static org.sonar.java.semsitter.SemaFacts.truth; +import static org.sonar.java.semsitter.SemaFacts.typeFact; + +/** Members of library and project types, created from type information and symbol dumps. */ +final class LibraryMembers { + + private static final String THROWS = "throws"; + private static final String VARARGS = "varargs"; + private static final String CONSTANT = "constant"; + private final JSema sema; + + LibraryMembers(JSema sema) { + this.sema = sema; + } + + /** Thrown types a {@code types} answer gives a project method, or null when it was not answered. */ + @Nullable + List projectThrown(@Nullable String id) { + List names = id == null ? null : sema.declaredMembers.projectThrows.get(id); + return names == null ? null : names.stream().map(sema.factTypes()::typeFromName).toList(); + } + + /** The typed annotations and thrown types of the project members of a {@code types} answer. */ + void registerProjectMembers(JsonObject info) { + JsonElement membersElement = info.get(JSema.MEMBERS); + if (!"project".equals(text(info, "origin")) || !(membersElement instanceof JsonArray members)) { + return; + } + for (JsonElement element : members) { + if (element instanceof JsonObject member && member.get("id") instanceof JsonPrimitive memberId) { + registerProjectMember(member, memberId); + } + } + } + + JSymbol memberFromTypeInfo(JTypeSymbol owner, JsonObject member) { + if (member.has("id") && !member.get("id").isJsonNull()) { + return projectMember(member); + } + String name = text(member, "name"); + String descriptor = text(member, "desc"); + String id = (owner.id == null ? owner.name() : owner.id) + "#" + name + (descriptor == null ? "" : descriptor); + JSymbol existing = sema.symbols.get(id); + if (existing != null) { + return existing; + } + if ("f".equals(text(member, "k"))) { + return newField(owner, id, name, descriptor, member); + } + return newMethod(owner, id, name, descriptor, member); + } + + void createDumpSymbol(String id) { + if (sema.symbols.containsKey(id)) { + return; + } + org.sonarsource.semsitter.wire.Symbol dump = sema.dumpSymbols.get(id); + String kind = dump.getKind(); + String name = dump.getName(); + if ("label".equals(kind)) { + return; + } + JSymbol symbol; + if ("type".equals(kind) && id.indexOf('<') >= 0) { + symbol = new JTypeSymbol(sema, id, name, true); + } else if ("type".equals(kind)) { + symbol = new JTypeSymbol(sema, id, simpleName(erase(id)), false); + sema.typesByName.putIfAbsent(erase(id), (JTypeSymbol) symbol); + } else if ("method".equals(kind) || "constructor".equals(kind)) { + symbol = new JMethodSymbol(sema, id, "constructor".equals(kind) ? SemaFacts.CONSTRUCTOR_NAME : name); + } else { + symbol = new JVariableSymbol(sema, id, name, kind); + } + sema.symbols.put(id, symbol); + } + + void linkDumpSymbol(String id) { + JSymbol symbol = sema.symbols.get(id); + org.sonarsource.semsitter.wire.Symbol dump = sema.dumpSymbols.get(id); + if (symbol == null) { + return; + } + Fact fact = sema.facts.get(id); + String ownerId = linkedOwnerId(symbol, dump, fact); + linkOwner(symbol, id, ownerId); + if (fact != null) { + sema.memberFactory().applyFact(symbol, fact); + } + if ((symbol.isMethodSymbol() || symbol.isVariableSymbol()) && (fact == null || !"IN_PROJECT".equals(fact.getTier()))) { + applyLibraryMember(symbol, id); + } + applyDeclaredType(symbol, dump, fact); + if (symbol instanceof JMethodSymbol method) { + sema.memberFactory().fillMethod(method, fact, id); + implicitEnumMethod(method, id, ownerId, dump); + } else if (symbol instanceof JTypeSymbol typeSymbol && typeSymbol.isTypeParameter()) { + symbol.type(JType.typeVar(sema, symbol.name(), id)); + } else if (symbol.isTypeSymbol()) { + symbol.type(sema.rawNamed(erase(id))); + } + } + + /** The constant the served type information gives a field of another source file, if any. */ + @Nullable + Object servedConstant(JVariableSymbol field) { + String id = field.id; + int hash = id == null ? -1 : id.indexOf('#'); + if (hash < 0 || !sema.declaresType(erase(id.substring(0, hash)))) { + return null; + } + String constant = sema.declaredMembers.projectConstants.get(id); + return constant == null ? null : constantOf(field.type(), constant); + } + + private void registerProjectMember(JsonObject member, JsonPrimitive memberId) { + List spellings = new ArrayList<>(strings(member, "useIds")); + spellings.add(memberId.getAsString()); + List annotations = sema.annotationFacts().readAnnotations(member); + for (String id : spellings) { + registerProjectSpelling(id, member, annotations); + } + } + + private void registerProjectSpelling(String id, JsonObject member, List annotations) { + if (!annotations.isEmpty()) { + sema.declaredMembers.libraryAnnotations.put(id, annotations); + } + sema.annotationFacts().registerParameterAnnotations(id, member); + if (member.get(THROWS) instanceof JsonArray) { + sema.declaredMembers.projectThrows.put(id, strings(member, THROWS)); + } + if (member.get(VARARGS) instanceof JsonPrimitive varArgs && varArgs.isBoolean()) { + sema.declaredMembers.projectVarArgs.put(id, varArgs.getAsBoolean()); + } + if (member.get("facts") instanceof JsonObject memberFact) { + sema.declaredMembers.projectMemberFacts.computeIfAbsent(id, key -> fact(memberFact)); + } + if (member.get("declaredType") instanceof JsonObject declared + && (declared.get("args") instanceof JsonArray || "typevar".equals(text(declared, "kind")))) { + sema.declaredMembers.projectFieldTypes.putIfAbsent(id, declared); + } + String constant = text(member, CONSTANT); + if (constant != null) { + sema.declaredMembers.projectConstants.put(id, constant); + } + } + + private JSymbol projectMember(JsonObject member) { + JSymbol project = sema.resolve(member.get("id").getAsString()); + if (sema.annotationFacts().declaredAnnotations(project.id).stream().anyMatch(annotation -> SemaFacts.DEPRECATED_ANNOTATION.equals(annotation.name()))) { + project.deprecated(true); + } + String constant = text(member, CONSTANT); + if (constant != null && project instanceof JVariableSymbol field && field.declaration() == null) { + field.constantValue(constantOf(field.type(), constant)); + } + return project; + } + + private JSymbol newField(JTypeSymbol owner, String id, @Nullable String name, @Nullable String descriptor, JsonObject member) { + JVariableSymbol field = new JVariableSymbol(sema, id, name == null ? "" : name, "field"); + field.owner(owner); + if (descriptor != null) { + field.type(sema.factTypes().readDescriptor(descriptor, new int[] {0})); + } + applyMemberFlags(field, member); + sema.annotationFacts().libraryAnnotations(field, id, member); + if (truth(member, "enum")) { + field.enumSymbol(true); + } + String constant = text(member, CONSTANT); + if (constant != null) { + field.constantValue(constantOf(field.type(), constant)); + } + sema.symbols.put(id, field); + return field; + } + + private JSymbol newMethod(JTypeSymbol owner, String id, @Nullable String name, @Nullable String descriptor, JsonObject member) { + JMethodSymbol method = new JMethodSymbol(sema, id, name == null ? "" : name); + method.owner(owner); + if (descriptor != null && descriptor.startsWith("(")) { + method.parameterTypes(sema.factTypes().parameterTypesOf(descriptor)); + method.returnTypeSymbol(sema.factTypes().readDescriptor(descriptor, new int[] {descriptor.indexOf(')') + 1}).symbol()); + } + applyMemberFlags(method, member); + if (owner.isInterface() && !truth(member, JSema.ABSTRACT) && !truth(member, JSema.STATIC) && !"private".equals(text(member, "vis"))) { + method.addModifiers(List.of("default")); + } + sema.annotationFacts().libraryAnnotations(method, id, member); + List thrown = strings(member, THROWS); + if (!thrown.isEmpty()) { + method.thrownTypes(thrown.stream().map(sema.factTypes()::typeFromName).toList()); + } + if (member.has(VARARGS) && member.get(VARARGS).isJsonPrimitive()) { + method.varArgs(member.get(VARARGS).getAsBoolean()); + method.varArgsKnown(true); + } + if (member.get("retType") instanceof JsonObject retType) { + applyDeclaredReturn(method, retType); + } + registerAnnotationDefault(id, member); + sema.symbols.put(id, method); + return method; + } + + private void applyDeclaredReturn(JMethodSymbol method, JsonObject retType) { + if (!method.isStatic() && retType.has("args")) { + JType plain = sema.factTypes().typeFromFact(retType, Map.of(), true); + if (!plain.isUnknown() && plain.isParameterized() + && plain.args.stream().noneMatch(argument -> argument.isCapture() || argument.isWildcard())) { + method.returnTypeSymbol(plain.symbol()); + } + } + } + + private void registerAnnotationDefault(String id, JsonObject member) { + if (member.get("default") instanceof JsonObject defaultValue) { + Object value = sema.annotationFacts().readAnnotationElement(defaultValue); + if (value != null) { + sema.declaredMembers.annotationDefaults.put(id, value); + } + } + } + + @Nullable + private String linkedOwnerId(JSymbol symbol, org.sonarsource.semsitter.wire.Symbol dump, @Nullable Fact fact) { + String ownerId = text(dump.getOwner()); + String parent = fact == null ? null : text(fact.getParent()); + boolean methodWithoutOwner = ownerId == null && symbol instanceof JMethodSymbol; + boolean ownerOutsideDump = ownerId != null + && parent != null + && !parent.contains(SemaFacts.SCOPE_SEPARATOR) + && !sema.facts.containsKey(ownerId) + && !sema.dumpSymbols.containsKey(ownerId); + return (methodWithoutOwner || ownerOutsideDump) ? parent : ownerId; + } + + private void linkOwner(JSymbol symbol, String id, @Nullable String ownerId) { + if (ownerId != null) { + symbol.owner(sema.resolve(ownerId)); + } else if (symbol instanceof JTypeSymbol typeSymbol && !typeSymbol.isTypeParameter()) { + symbol.owner(sema.packageSymbol(packageName(erase(id)))); + } + } + + private void applyDeclaredType(JSymbol symbol, org.sonarsource.semsitter.wire.Symbol dump, @Nullable Fact fact) { + TypeRef declaredType = typeFact(dump); + if (symbol.isVariableSymbol() && declaredType != null) { + symbol.type(sema.factTypes().typeFromRef(declaredType)); + } else if (symbol.isVariableSymbol() && fact != null && symbol.type().isUnknown()) { + // A use before the declaration is translated still sees a primitive type. + List declared = fact.getTypeList(); + if (declared.size() == 1 && JSema.PRIMITIVES.contains(declared.get(0))) { + symbol.type(sema.primitiveType(declared.get(0))); + } + } + } + + /** The implicit valueOf and values of an enum come without a return type fact: derive it from the owner. */ + private void implicitEnumMethod(JMethodSymbol method, String id, @Nullable String ownerId, org.sonarsource.semsitter.wire.Symbol dump) { + FactValue implicit = dump.getFactsMap().get("implicit"); + if (implicit == null || implicit.getValueCase() == FactValue.ValueCase.VALUE_NOT_SET || ownerId == null) { + return; + } + MemberId parsed = sema.parseMember(id); + boolean valueOf = "valueOf".equals(parsed.name()) && "java.lang.String".equals(parsed.params()); + boolean values = "values".equals(parsed.name()) && parsed.params() != null && parsed.params().isEmpty(); + if (valueOf || values) { + Type enumType = sema.factTypes().typeFromName(erase(ownerId)); + method.returnTypeSymbol((valueOf ? enumType : JType.array(sema, (JType) enumType)).symbol()); + method.addModifiers(List.of("public", "static")); + } + } + + /** Flags, annotations and thrown types the {@code types} answer gives a library member the dump names. */ + private void applyLibraryMember(JSymbol symbol, String id) { + MemberId parsed = sema.parseMember(id); + if (parsed == null || parsed.arityOnly() || JSema.ARRAY.equals(parsed.owner())) { + return; + } + String ownerName = erase(parsed.owner()); + sema.typeSymbol(ownerName); + JsonObject member = sema.lookup().findMember(ownerName, parsed, new HashSet<>(), MemberLookup.Match.TYPED); + if (member == null || member.has("id")) { + return; + } + applyMemberFlags(symbol, member); + sema.annotationFacts().libraryAnnotations(symbol, id, member); + List thrown = strings(member, THROWS); + if (symbol instanceof JMethodSymbol method && !thrown.isEmpty()) { + method.thrownTypes(thrown.stream().map(sema.factTypes()::typeFromName).toList()); + } + if (symbol instanceof JMethodSymbol method && member.get(VARARGS) instanceof JsonPrimitive varArgs && varArgs.isBoolean()) { + method.varArgs(varArgs.getAsBoolean()); + method.varArgsKnown(true); + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberFactory.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberFactory.java new file mode 100644 index 00000000000..91a84335ea9 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberFactory.java @@ -0,0 +1,371 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Fact; + +import static org.sonar.java.semsitter.SemaFacts.erase; +import static org.sonar.java.semsitter.SemaFacts.flat; +import static org.sonar.java.semsitter.SemaFacts.isTypeFact; +import static org.sonar.java.semsitter.SemaFacts.prop; +import static org.sonar.java.semsitter.SemaFacts.strings; +import static org.sonar.java.semsitter.SemaFacts.text; + +/** Creates method, field, type parameter, array, primitive and local type symbols. */ +final class MemberFactory { + + private static final String PUBLIC = "public"; + private static final String FINAL = "final"; + private static final String ANNOTATION = "annotation"; + private static final String INTERFACE = "interface"; + private static final String SUPER = "super"; + private static final String TYPE_PARAMETERS = "typeParameters"; + private final JSema sema; + private final Set creating = new HashSet<>(); + + MemberFactory(JSema sema) { + this.sema = sema; + } + + Symbol.TypeSymbol arraySymbol(JType element) { + String name = element.fullyQualifiedName() + SemaFacts.ARRAY_SUFFIX; + JTypeSymbol found = sema.typesByName.get(name); + if (found != null) { + return found; + } + JTypeSymbol symbol = new JTypeSymbol(sema, name, element.name() + SemaFacts.ARRAY_SUFFIX, false); + symbol.elementFqn(element.fullyQualifiedName()); + symbol.owner(Symbol.ROOT_PACKAGE); + symbol.type(JType.array(sema, element)); + sema.typesByName.put(name, symbol); + return symbol; + } + + Symbol.TypeSymbol primitiveSymbol(String name) { + JTypeSymbol found = sema.typesByName.get(name); + if (found != null) { + return found; + } + JTypeSymbol symbol = new JTypeSymbol(sema, name, name, false); + symbol.owner(Symbol.ROOT_PACKAGE); + symbol.type(sema.primitiveType(name)); + sema.typesByName.put(name, symbol); + return symbol; + } + + /** The upper bound of the type variable with this id: its first declared bound, or {@code Object}. */ + Type typeVariableBound(@Nullable String id) { + if (id != null && sema.symbols.get(id) instanceof JTypeSymbol parameter && parameter.firstBound() instanceof Type bound && !bound.isUnknown()) { + return bound; + } + return sema.getClassType(SemaFacts.OBJECT_TYPE); + } + + /** Every declared bound of the type variable with this id, or {@code Object} when it has none. */ + List typeVariableBounds(@Nullable String id) { + if (id != null && sema.symbols.get(id) instanceof JTypeSymbol parameter && !parameter.bounds().isEmpty()) { + return parameter.bounds(); + } + return List.of(sema.getClassType(SemaFacts.OBJECT_TYPE)); + } + + JSymbol typeParameter(String id) { + int open = id.lastIndexOf('<'); + String name = open >= 0 && id.endsWith(">") ? id.substring(open + 1, id.length() - 1) : id; + JTypeSymbol symbol = new JTypeSymbol(sema, id, name, true); + symbol.type(JType.typeVar(sema, name, id)); + sema.symbols.put(id, symbol); + return symbol; + } + + JSymbol createMember(String id) { + if (!creating.add(id)) { + return sema.unknownSymbol; + } + try { + return createMemberOnce(id); + } finally { + creating.remove(id); + } + } + + void fillMethod(JMethodSymbol method, @Nullable Fact fact, String id) { + MemberId parsed = sema.parseMember(id); + List returns = fact == null ? List.of() : flat(fact.getReturnsList()); + if (!returns.isEmpty()) { + method.returnTypeSymbol(sema.factTypes().typeFromName(returns.get(0)).symbol()); + } + fillParameterTypes(method, fact, parsed); + if (SemaFacts.CONSTRUCTOR_NAME.equals(method.name())) { + method.returnTypeSymbol(primitiveSymbol("void")); + } + fillVarArgs(method, fact, id); + method.parametrized(id.replace(SemaFacts.CONSTRUCTOR_NAME, "").replace("", "").indexOf('<') >= 0); + } + + void applyFact(JSymbol symbol, Fact fact) { + String kind = fact.getKind(); + if (symbol instanceof JTypeSymbol type) { + applyTypeFact(type, fact, kind); + } + symbol.addModifiers(flat(prop(fact, "modifiers"))); + if (symbol instanceof JTypeSymbol) { + symbol.addModifiers(implicitTypeModifiers(kind, text(fact.getParent()))); + } + for (String annotation : fact.getAnnotationsList()) { + if (SemaFacts.DEPRECATED_ANNOTATION.equals(erase(annotation))) { + symbol.deprecated(true); + } + } + if (symbol.isVariableSymbol() && ("enum".equals(kind) || "enum_member".equals(kind))) { + symbol.enumSymbol(true); + symbol.addModifiers(List.of(PUBLIC, JSema.STATIC, FINAL)); + } + } + + void applyTypeInfo(JTypeSymbol symbol, JsonObject info) { + JsonObject genericSuper = info.get("superType") instanceof JsonObject superType ? superType : null; + String kind = text(info, "kind"); + boolean interfaceKind = INTERFACE.equals(kind) || ANNOTATION.equals(kind); + symbol.interfaceSymbol(interfaceKind); + symbol.annotationSymbol(ANNOTATION.equals(kind)); + symbol.enumSymbol("enum".equals(kind) || "java.lang.Enum".equals(text(info, SUPER))); + if (interfaceKind) { + List extend = strings(info, SUPER); + symbol.interfaceNames(extend.isEmpty() ? strings(info, "interfaces") : extend); + symbol.superName(null); + } else { + symbol.superName(text(info, SUPER)); + symbol.interfaceNames(strings(info, "interfaces")); + } + symbol.genericSupertypes(genericSuper, FactTypes.objects(info, "interfaceTypes")); + symbol.addModifiers(flat(info, "modifiers")); + sema.annotationFacts().libraryAnnotations(symbol, symbol.id == null ? symbol.name() : symbol.id, info); + JsonElement typeParameters = info.get(TYPE_PARAMETERS); + if (typeParameters != null && !typeParameters.isJsonNull()) { + symbol.typeParameterCount(typeParameters.getAsInt()); + } + List members = new ArrayList<>(); + if (info.has(JSema.MEMBERS)) { + for (JsonElement member : info.getAsJsonArray(JSema.MEMBERS)) { + members.add(member.getAsJsonObject()); + } + } + symbol.memberFacts(members); + symbol.unknown(false); + } + + private JSymbol createMemberOnce(String id) { + MemberId parsed = Objects.requireNonNull(sema.parseMember(id)); + if (JSema.ARRAY.equals(parsed.owner()) && "length".equals(parsed.name())) { + return createArrayLength(id); + } + String ownerName = erase(parsed.owner()); + JTypeSymbol owner = sema.typeSymbol(ownerName); + JsonObject member = findLibraryMember(ownerName, parsed); + String memberId = member == null ? null : text(member, "id"); + if (member != null && (memberId == null || !creating.contains(memberId))) { + String declaring = sema.lookup().declaringType(ownerName, member, new HashSet<>()); + JSymbol resolved = sema.libraryMembers().memberFromTypeInfo(declaring == null ? owner : sema.typeSymbol(declaring), member); + sema.symbols.put(id, resolved); + return resolved; + } + if (parsed.params() == null) { + return createFieldLikeMember(id, parsed, owner); + } + return createMethod(id, parsed, owner, member == null); + } + + private JSymbol createArrayLength(String id) { + JVariableSymbol length = new JVariableSymbol(sema, id, "length", "field"); + length.addModifiers(List.of(PUBLIC, FINAL)); + length.type(sema.primitiveType("int")); + length.owner(Symbol.UNKNOWN_SYMBOL); + sema.symbols.put(id, length); + return length; + } + + @Nullable + private JsonObject findLibraryMember(String ownerName, MemberId parsed) { + JsonObject member = null; + if (parsed.params() != null && !parsed.arityOnly()) { + member = sema.lookup().findMember(ownerName, parsed, new HashSet<>(), MemberLookup.Match.TYPED); + } + if (member == null) { + member = sema.lookup().findMember(ownerName, parsed, new HashSet<>(), MemberLookup.Match.ARITY); + } + if (member == null && parsed.params() != null) { + member = sema.lookup().findMember(ownerName, parsed, new HashSet<>(), MemberLookup.Match.VARARGS); + } + return member; + } + + private JSymbol createFieldLikeMember(String id, MemberId parsed, JTypeSymbol owner) { + if (parsed.name().contains("$lambda$")) { + JMethodSymbol lambda = new JMethodSymbol(sema, id, parsed.name()); + lambda.owner(owner); + sema.symbols.put(id, lambda); + return lambda; + } + if (parsed.name().contains(")$")) { + return createTypeInMethodBody(id, parsed); + } + JVariableSymbol field = new JVariableSymbol(sema, id, parsed.name(), "field"); + field.owner(owner); + Fact fieldFact = factOf(id); + List fieldType = fieldFact == null ? List.of() : flat(fieldFact.getTypeList()); + if (fieldFact != null && fieldType.isEmpty() && owner.isEnum()) { + // the facts of an enum constant carry no type: it is of its enum + applyFact(field, fieldFact); + field.type(owner.type()); + field.enumSymbol(true); + } else if (fieldFact == null || fieldType.isEmpty()) { + field.unknown(true); + } else { + applyFact(field, fieldFact); + JsonObject declared = sema.declaredMembers.projectFieldTypes.get(id); + field.type(declared != null ? sema.factTypes().typeFromFact(declared) : sema.factTypes().typeFromName(fieldType.get(0))); + } + markDeprecated(field, id); + sema.symbols.put(id, field); + return field; + } + + private JSymbol createMethod(String id, MemberId parsed, JTypeSymbol owner, boolean noLibraryMember) { + JMethodSymbol method = new JMethodSymbol(sema, id, parsed.name()); + method.owner(parsed.arityOnly() ? Symbol.TypeSymbol.UNKNOWN_TYPE : owner); + method.unknown(parsed.arityOnly()); + fillMethod(method, factOf(id), id); + if (SemaFacts.CONSTRUCTOR_NAME.equals(parsed.name()) && factOf(id) == null && noLibraryMember) { + // The implicit default constructor has the access of its class. + method.addModifiers(List.of(PUBLIC, "protected", "private").stream().filter(owner::hasModifier).toList()); + } + Fact methodFact = factOf(id); + if (methodFact != null && !parsed.arityOnly()) { + applyFact(method, methodFact); + } + markDeprecated(method, id); + sema.symbols.put(id, method); + return method; + } + + /** The facts of a project member: those of this file, else those a {@code types} answer gave with it. */ + @Nullable + private Fact factOf(String id) { + Fact fact = sema.facts.get(id); + return fact != null ? fact : sema.declaredMembers.projectMemberFacts.get(id); + } + + private void markDeprecated(JSymbol symbol, String id) { + if (sema.annotationFacts().declaredAnnotations(id).stream().anyMatch(annotation -> SemaFacts.DEPRECATED_ANNOTATION.equals(annotation.name()))) { + symbol.deprecated(true); + } + } + + private void fillParameterTypes(JMethodSymbol method, @Nullable Fact fact, @Nullable MemberId parsed) { + List factParams = fact == null ? List.of() : flat(fact.getParamsList()); + if (!factParams.isEmpty() && (parsed == null || parsed.arityOnly() || factParams.size() == parsed.arity())) { + method.parameterTypes(typesFromNames(factParams)); + } else if (parsed != null && !parsed.arityOnly() && parsed.params() != null && !parsed.params().isEmpty()) { + method.parameterTypes(typesFromNames(parsed.paramList())); + } + } + + private List typesFromNames(List names) { + List types = new ArrayList<>(); + for (String name : names) { + types.add(sema.factTypes().typeFromName(name)); + } + return types; + } + + private void fillVarArgs(JMethodSymbol method, @Nullable Fact fact, String id) { + List declaredParams = fact == null ? List.of() : flat(prop(fact, "param_types")); + Boolean served = sema.declaredMembers.projectVarArgs.get(id); + if (served != null) { + method.varArgs(served); + method.varArgsKnown(true); + } else if (!declaredParams.isEmpty()) { + method.varArgs(declaredParams.get(declaredParams.size() - 1).endsWith("...")); + method.varArgsKnown(true); + } + } + + private static void applyTypeFact(JTypeSymbol type, Fact fact, String kind) { + boolean interfaceKind = INTERFACE.equals(kind) || ANNOTATION.equals(kind); + type.interfaceSymbol(interfaceKind); + type.annotationSymbol(ANNOTATION.equals(kind)); + List extend = fact.getExtendsList(); + List implement = fact.getImplementsList(); + type.enumSymbol("enum".equals(kind) || extend.stream().map(SemaFacts::erase).anyMatch("java.lang.Enum"::equals)); + if (interfaceKind) { + type.interfaceNames(extend.isEmpty() ? implement : extend); + } else { + type.superName(extend.isEmpty() ? null : extend.get(0)); + type.interfaceNames(implement); + } + } + + /** + * Modifiers Java implies: member interfaces, enums, records and annotations are static; enums and records are + * final (an enum constant with a body is not modelled). + */ + private List implicitTypeModifiers(String kind, @Nullable String parent) { + List implied = new ArrayList<>(); + boolean member = parent != null && !parent.endsWith("::") && sema.facts.get(parent) != null + && isTypeFact(sema.facts.get(parent)); + if (member && (INTERFACE.equals(kind) || "enum".equals(kind) || JSema.RECORD.equals(kind) || ANNOTATION.equals(kind))) { + implied.add(JSema.STATIC); + } + if ("enum".equals(kind) || JSema.RECORD.equals(kind)) { + implied.add(FINAL); + } + return implied; + } + + /** + * Local and anonymous classes are identified as members of their enclosing type, with the declaring + * method embedded in the member name, as in {@code com.acme.Owner#create()$Local$1}. They carry no + * declaration of their own, so the symbol is rebuilt from the identifier and owned by whatever + * declares it, which is the method for a local class and the local class for a nested anonymous one. + */ + private JSymbol createTypeInMethodBody(String id, MemberId parsed) { + int lastSegment = parsed.name().lastIndexOf('$'); + String simpleName = parsed.name().substring(lastSegment + 1); + boolean anonymous = simpleName.chars().allMatch(Character::isDigit); + JTypeSymbol symbol = new JTypeSymbol(sema, id, anonymous ? "" : simpleName, false); + sema.symbols.put(id, symbol); + sema.typesByName.putIfAbsent(id, symbol); + symbol.owner(sema.resolve(parsed.owner() + "#" + parsed.name().substring(0, lastSegment))); + symbol.type(sema.rawNamed(id)); + Fact fact = sema.facts.get(id); + if (fact != null) { + applyFact(symbol, fact); + } + return symbol; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberId.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberId.java new file mode 100644 index 00000000000..00e78b26641 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberId.java @@ -0,0 +1,23 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.List; +import javax.annotation.Nullable; + +record MemberId(String owner, String name, @Nullable String params, boolean arityOnly, int arity, List paramList) { +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberLookup.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberLookup.java new file mode 100644 index 00000000000..31e59d83146 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/MemberLookup.java @@ -0,0 +1,230 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; + +import static org.sonar.java.semsitter.SemaFacts.erase; +import static org.sonar.java.semsitter.SemaFacts.parents; +import static org.sonar.java.semsitter.SemaFacts.text; + +/** Finds declared methods and fields by name and arguments. */ +final class MemberLookup { + + private final JSema sema; + private final Map>> membersByTypeName = new HashMap<>(); + + MemberLookup(JSema sema) { + this.sema = sema; + } + + void invalidate(String typeKey) { + membersByTypeName.remove(typeKey); + } + + List membersNamed(String ownerFqn, String name) { + String key = sema.sourceName(ownerFqn); + JsonObject info = sema.typeInfos.get(key); + if (info == null) { + return List.of(); + } + return membersByTypeName.computeIfAbsent(key, k -> indexMembers(info)).getOrDefault(name, List.of()); + } + + @Nullable + Symbol.VariableSymbol enumConstant(@Nullable String typeName, @Nullable String constName) { + if (constName == null) { + return null; + } + String ownerName = typeName == null || typeName.isBlank() ? "" : erase(typeName); + String id = (ownerName.isEmpty() ? "enum" : ownerName) + "#" + constName; + if (sema.symbols.get(id) instanceof Symbol.VariableSymbol variable) { + return variable; + } + JTypeSymbol type = ownerName.isEmpty() ? null : sema.typeSymbol(ownerName); + JVariableSymbol created = new JVariableSymbol(sema, id, constName, "enum_member"); + if (type != null) { + created.owner(type); + created.type(type.type()); + } + created.addModifiers(List.of("public", "static", "final")); + sema.symbols.put(id, created); + return created; + } + + /** The type, among {@code ownerFqn} and its supertypes, whose members include {@code member}, or null when none does. */ + @Nullable + String declaringType(String ownerFqn, JsonObject member, Set seen) { + JsonObject info = seen.add(ownerFqn) ? sema.typeInfos.get(sema.sourceName(ownerFqn)) : null; + if (info == null) { + return null; + } + JsonArray members = info.getAsJsonArray(JSema.MEMBERS); + if (members != null && members.asList().stream().anyMatch(candidate -> candidate == member)) { + return ownerFqn; + } + for (String parent : parents(info)) { + String found = declaringType(erase(parent), member, seen); + if (found != null) { + return found; + } + } + return null; + } + + @Nullable + JsonObject findMember(String ownerFqn, MemberId parsed, Set seen, Match match) { + if (!seen.add(ownerFqn)) { + return null; + } + String name = plainName(parsed.name()); + JsonObject found = matchMembers(membersNamed(ownerFqn, name), parsed, match); + if (found != null) { + return found; + } + JsonObject info = sema.typeInfos.get(sema.sourceName(ownerFqn)); + if (info == null || SemaFacts.CONSTRUCTOR_NAME.equals(name)) { + return null; + } + for (String parent : parents(info)) { + found = findMember(erase(parent), parsed, seen, match); + if (found != null) { + return found; + } + } + return null; + } + + private Map> indexMembers(JsonObject info) { + JsonArray members = info.getAsJsonArray(JSema.MEMBERS); + if (members == null) { + return Map.of(); + } + Map> index = new HashMap<>(); + for (JsonElement element : members) { + JsonObject member = element.getAsJsonObject(); + String memberName = memberNameOf(member); + if (memberName != null) { + index.computeIfAbsent(memberName, k -> new ArrayList<>()).add(member); + } + } + return index; + } + + @Nullable + private String memberNameOf(JsonObject member) { + String written = text(member, "name"); + if (written != null) { + return plainName(written); + } + String id = text(member, "id"); + if (id != null) { + MemberId parsed = sema.parseMember(id); + return parsed == null ? null : plainName(parsed.name()); + } + return null; + } + + @Nullable + private JsonObject matchMembers(List members, MemberId parsed, Match match) { + for (JsonObject member : members) { + if (matches(member, parsed, match)) { + return member; + } + } + return null; + } + + private boolean matches(JsonObject member, MemberId parsed, Match match) { + String parsedName = plainName(parsed.name()); + String id = text(member, "id"); + if (id != null) { + MemberId other = sema.parseMember(id); + return other != null && parsedName.equals(plainName(other.name())) && parsed.arity() == other.arity() + && (parsed.arityOnly() || other.arityOnly() || Objects.equals(parsed.params(), other.params())); + } + if (!parsedName.equals(text(member, "name"))) { + return false; + } + boolean method = parsed.params() != null; + if (method != "m".equals(text(member, "k"))) { + return false; + } + if (!method) { + return true; + } + String descriptor = text(member, "desc"); + if (descriptor == null) { + return false; + } + List declaredParams = sema.factTypes().parameterTypesOf(descriptor); + int declaredCount = declaredParams.size(); + return switch (match) { + case TYPED -> declaredCount == parsed.arity() && sameErasures(declaredParams, parsed.paramList()); + case ARITY -> declaredCount == parsed.arity(); + case VARARGS -> declaredCount > 0 && parsed.arity() >= declaredCount - 1 && declaredParams.get(declaredCount - 1).isArray(); + }; + } + + private static boolean sameErasures(List declared, List names) { + for (int i = 0; i < declared.size(); i++) { + String expected = declared.get(i).erasure().fullyQualifiedName().replace('$', '.'); + if (!expected.equals(erasedName(names.get(i)))) { + return false; + } + } + return true; + } + + private static String erasedName(String name) { + StringBuilder out = new StringBuilder(name.length()); + int depth = 0; + for (char current : erase(name).toCharArray()) { + if (current == '<') { + depth++; + } else if (current == '>') { + depth--; + } else if (depth == 0) { + out.append(current == '$' ? '.' : current); + } + } + return out.toString().replace("...", SemaFacts.ARRAY_SUFFIX).trim(); + } + + private static String plainName(String name) { + if (name.startsWith(SemaFacts.CONSTRUCTOR_NAME)) { + return SemaFacts.CONSTRUCTOR_NAME; + } + int angle = name.indexOf('<'); + return angle > 0 ? name.substring(0, angle) : name; + } + + enum Match { + TYPED, ARITY, VARARGS + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/OverriddenMethods.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/OverriddenMethods.java new file mode 100644 index 00000000000..8ef15c2af39 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/OverriddenMethods.java @@ -0,0 +1,99 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol; +import org.sonar.plugins.java.api.semantic.Type; + +/** Finds the methods a method overrides, walking the supertypes of its class. */ +final class OverriddenMethods { + + private final JMethodSymbol symbol; + private final JSema sema; + + OverriddenMethods(JMethodSymbol symbol) { + this.symbol = symbol; + this.sema = symbol.sema; + } + + List find() { + if (!(symbol.owner() instanceof JTypeSymbol typeSymbol) || symbol.isUnknown() || symbol.isStatic() || symbol.isPrivate()) { + return List.of(); + } + List found = new ArrayList<>(); + Set visited = new HashSet<>(); + if (typeSymbol.isInterface()) { + match(found, sema.typeSymbol(SemaFacts.OBJECT_TYPE), null); + visited.add(SemaFacts.OBJECT_TYPE); + } + walk(found, visited, typeSymbol.superClass()); + for (Type iface : typeSymbol.interfaces()) { + walk(found, visited, iface); + } + return found; + } + + private void walk(List found, Set visited, @Nullable Type type) { + if (type == null || type.isUnknown() || !visited.add(type.fullyQualifiedName())) { + return; + } + if (type.symbol() instanceof JTypeSymbol parent) { + match(found, parent, type); + walk(found, visited, parent.superClass()); + for (Type iface : parent.interfaces()) { + walk(found, visited, iface); + } + } + } + + private void match(List found, JTypeSymbol parent, @Nullable Type declaring) { + for (Symbol member : parent.membersNamed(symbol.name())) { + if (member instanceof JMethodSymbol method && !method.isStatic() && !method.isPrivate() && sameSignature(method, declaring)) { + found.add(method); + return; + } + } + } + + private boolean viaClassVariable(JMethodSymbol library, int index, Type declaring, String mine) { + Type argument = sema.substitution().classVariableArgument(library, index, declaring); + return argument != null && mine.equals(argument.erasure().fullyQualifiedName()); + } + + private boolean sameSignature(JMethodSymbol other, @Nullable Type declaring) { + List theirs = other.parameterTypes(); + if (symbol.parameterTypes().size() != theirs.size()) { + return false; + } + for (int i = 0; i < symbol.parameterTypes().size(); i++) { + String mine = symbol.parameterTypes().get(i).erasure().fullyQualifiedName(); + boolean same = mine.equals(theirs.get(i).erasure().fullyQualifiedName()) + || (declaring != null && (mine.equals(sema.substitution().asMemberOf(theirs.get(i), declaring).erasure().fullyQualifiedName()) + || viaClassVariable(other, i, declaring, mine))); + if (!same) { + return false; + } + } + return true; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemaAnnotations.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemaAnnotations.java new file mode 100644 index 00000000000..58774e7643d --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemaAnnotations.java @@ -0,0 +1,184 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import javax.annotation.Nullable; +import org.sonar.java.model.AnnotationValueImpl; +import org.sonar.plugins.java.api.semantic.SymbolMetadata; +import org.sonarsource.semsitter.wire.Fact; + +import static org.sonar.java.semsitter.SemaFacts.erase; +import static org.sonar.java.semsitter.SemaFacts.parameterKey; +import static org.sonar.java.semsitter.SemaFacts.text; + +/** Annotations declared on project and library symbols, and their values. */ +final class SemaAnnotations { + + private final JSema sema; + + SemaAnnotations(JSema sema) { + this.sema = sema; + } + + List declaredAnnotations(@Nullable String id) { + List typed = sema.declaredMembers.libraryAnnotations.get(id); + if (typed != null) { + return typed; + } + Fact fact = sema.facts.get(id); + return fact == null ? List.of() : fact.getAnnotationsList().stream().map(name -> new DeclaredAnnotation(erase(name), List.of())).toList(); + } + + /** Annotations written on the parameters of a library or project method. */ + void registerParameterAnnotations(String methodId, JsonObject info) { + if (info.get("parameterAnnotations") instanceof JsonArray parameters) { + for (int i = 0; i < parameters.size(); i++) { + List onParameter = readAnnotationList(parameters.get(i)); + if (!onParameter.isEmpty()) { + sema.declaredMembers.libraryAnnotations.putIfAbsent(parameterKey(methodId, i), onParameter); + } + } + } + } + + /** Annotations and deprecation a {@code types} answer gives a library type or member. */ + void libraryAnnotations(JSymbol symbol, String id, JsonObject info) { + registerParameterAnnotations(id, info); + List annotations = readAnnotations(info); + if (annotations.isEmpty()) { + return; + } + sema.declaredMembers.libraryAnnotations.put(id, annotations); + if (annotations.stream().anyMatch(annotation -> SemaFacts.DEPRECATED_ANNOTATION.equals(annotation.name()))) { + symbol.deprecated(true); + } + } + + /** Annotations written on the outermost type of a field or return type are annotations of the member. */ + List readAnnotations(JsonObject info) { + List annotations = new ArrayList<>(readAnnotationList(info.get(JSema.ANNOTATIONS))); + if (info.get("typeAnnotations") instanceof JsonArray typed) { + addOutermostTypeAnnotations(annotations, typed); + } + return annotations; + } + + @Nullable + Object readAnnotationElement(JsonObject value) { + Objects.requireNonNull(value); + String kind = text(value, "kind"); + JsonElement raw = value.get("value"); + if (kind == null) { + return null; + } + return switch (kind) { + case "boolean" -> Boolean.valueOf(raw instanceof JsonPrimitive primitive && primitive.getAsBoolean()); + case "enum" -> sema.lookup().enumConstant(text(value, "type"), text(value, "const")); + case "array" -> readAnnotationArray(raw); + case "annotation" -> raw instanceof JsonObject annotation ? text(annotation, "name") : null; + default -> raw instanceof JsonPrimitive primitive ? readPrimitive(kind, primitive) : null; + }; + } + + /** The default of an annotation element read from a class file. */ + @Nullable + Object annotationDefault(JMethodSymbol method) { + return sema.declaredMembers.annotationDefaults.get(method.id); + } + + private void addOutermostTypeAnnotations(List annotations, JsonArray typed) { + for (JsonElement element : typed) { + if (element instanceof JsonObject entry && "type".equals(text(entry, "on")) && entry.get("path") instanceof JsonArray path && path.isEmpty()) { + JsonArray one = new JsonArray(); + one.add(entry); + for (DeclaredAnnotation annotation : readAnnotationList(one)) { + if (annotations.stream().noneMatch(known -> known.name().equals(annotation.name()))) { + annotations.add(annotation); + } + } + } + } + } + + private List readAnnotationList(@Nullable JsonElement list) { + if (!(list instanceof JsonArray array)) { + return List.of(); + } + List annotations = new ArrayList<>(); + for (JsonElement element : array) { + if (element.isJsonPrimitive()) { + annotations.add(new DeclaredAnnotation(element.getAsString(), List.of())); + } else if (element.isJsonObject()) { + JsonObject annotation = element.getAsJsonObject(); + String name = text(annotation, "name"); + if (name != null) { + annotations.add(new DeclaredAnnotation(name, readAnnotationValues(annotation.get("values")))); + } + } + } + return annotations; + } + + private List readAnnotationValues(@Nullable JsonElement element) { + if (!(element instanceof JsonArray array)) { + return List.of(); + } + List values = new ArrayList<>(); + for (JsonElement item : array) { + if (item.isJsonObject()) { + JsonObject value = item.getAsJsonObject(); + String name = text(value, "name"); + values.add(new AnnotationValueImpl(name == null ? "value" : name, readAnnotationElement(value))); + } + } + return values; + } + + @Nullable + private Object readPrimitive(String kind, JsonPrimitive raw) { + return switch (kind) { + case "byte" -> Byte.valueOf(raw.getAsByte()); + case "short" -> Short.valueOf(raw.getAsShort()); + case "int" -> Integer.valueOf(raw.getAsInt()); + case "long" -> Long.valueOf(raw.getAsLong()); + case "float" -> Float.valueOf(raw.getAsFloat()); + case "double" -> Double.valueOf(raw.getAsDouble()); + case "char" -> Character.valueOf((char) raw.getAsInt()); + case "string" -> raw.getAsString(); + case "class" -> sema.typeSymbol(erase(raw.getAsString())); + default -> null; + }; + } + + private Object[] readAnnotationArray(@Nullable JsonElement element) { + if (!(element instanceof JsonArray array)) { + return new Object[0]; + } + List values = new ArrayList<>(); + for (JsonElement item : array) { + values.add(item.isJsonObject() ? readAnnotationElement(item.getAsJsonObject()) : null); + } + return values.toArray(); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemaFacts.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemaFacts.java new file mode 100644 index 00000000000..5469b711dd9 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemaFacts.java @@ -0,0 +1,320 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactValue; +import org.sonarsource.semsitter.wire.Prop; +import org.sonarsource.semsitter.wire.TypeRef; + +/** Stateless readers of the facts and member ids served by SemSitter. */ +final class SemaFacts { + + static final String ARRAY_SUFFIX = "[]"; + static final String SCOPE_SEPARATOR = "::"; + static final String CONSTRUCTOR_NAME = ""; + static final String NULL_TYPE_NAME = ""; + static final String UNKNOWN_TYPE_NAME = "!Unknown!"; + static final String OBJECT_TYPE = "java.lang.Object"; + static final String DEPRECATED_ANNOTATION = "java.lang.Deprecated"; + + private SemaFacts() { + } + + /** The name a member symbol created from {@code id} gets, or null when the id names no member. */ + @Nullable + static String memberName(String id) { + MemberId parsed = parseMember(id); + return parsed == null ? null : parsed.name(); + } + + /** The declared type a document gives a symbol, or null when it gives none. */ + @Nullable + static TypeRef typeFact(org.sonarsource.semsitter.wire.Symbol symbol) { + FactValue value = symbol.getFactsMap().get("type"); + return value != null && value.hasType() ? value.getType() : null; + } + + static void addTypeName(Set names, @Nullable String id) { + if (id == null || id.isEmpty()) { + return; + } + int hash = id.indexOf('#'); + String owner = hash < 0 ? id : id.substring(0, hash); + if (owner.indexOf('%') >= 0 || owner.indexOf('(') >= 0 || (owner.indexOf('<') >= 0 && hash < 0)) { + return; + } + String erased = erase(owner); + if (!erased.isEmpty() && !JSema.PRIMITIVES.contains(erased) && erased.indexOf(' ') < 0) { + names.add(erased); + } + } + + static void collectFactNames(Set names, TypeRef type) { + addTypeName(names, type.getId()); + for (TypeRef argument : type.getArgumentsList()) { + collectFactNames(names, argument); + } + if (type.hasElement()) { + collectFactNames(names, type.getElement()); + } + } + + static boolean isWellKnown(String fqn) { + return OBJECT_TYPE.equals(fqn) || "java.lang.Cloneable".equals(fqn) || "java.io.Serializable".equals(fqn); + } + + /** Whether {@code fqn} is a plain class name rather than a primitive, type parameter, array or synthetic scope name. */ + static boolean isPlainTypeName(String fqn) { + return !JSema.PRIMITIVES.contains(fqn) && fqn.indexOf('<') < 0 && !fqn.endsWith(ARRAY_SUFFIX) && !fqn.contains(SCOPE_SEPARATOR); + } + + /** The graph fact a {@code types} answer gives a project member, in the shape a document gives it. */ + static Fact fact(JsonObject json) { + Objects.requireNonNull(json); + Fact.Builder fact = Fact.newBuilder() + .setKind(Objects.requireNonNullElse(text(json, "kind"), "")) + .setParent(Objects.requireNonNullElse(text(json, "parent"), "")) + .addAllExtends(strings(json, JSema.EXTENDS)) + .addAllImplements(strings(json, "implements")) + .addAllReturns(strings(json, "returns")) + .addAllType(strings(json, "type")) + .addAllParams(strings(json, "params")) + .addAllAnnotations(strings(json, JSema.ANNOTATIONS)); + if (json.get("props") instanceof JsonObject props) { + for (String name : props.keySet()) { + fact.addProps(Prop.newBuilder().setName(name).addAllValues(strings(props, name))); + } + } + return fact.build(); + } + + static String parameterKey(String methodId, int index) { + return methodId + "@param" + index; + } + + /** A constant spelled as text, as the boxed value of the field's primitive type. */ + static Object constantOf(@Nullable Type type, String text) { + String name = type == null ? "" : type.fullyQualifiedName(); + try { + return switch (name) { + case "int" -> Integer.valueOf(text); + case "long" -> Long.valueOf(text); + case "short" -> Short.valueOf(text); + case "byte" -> Byte.valueOf(text); + case "float" -> Float.valueOf(text); + case "double" -> Double.valueOf(text); + case "boolean" -> Boolean.valueOf(text); + case "char" -> text.length() == 1 ? Integer.valueOf(text.charAt(0)) : text; + default -> text; + }; + } catch (NumberFormatException e) { + return text; + } + } + + static boolean isTypeFact(Fact fact) { + String kind = fact.getKind(); + return "class".equals(kind) || "interface".equals(kind) || "enum".equals(kind) || JSema.RECORD.equals(kind) + || "annotation".equals(kind) || "exception".equals(kind); + } + + static void applyMemberFlags(JSymbol symbol, JsonObject member) { + List modifiers = new ArrayList<>(); + if (truth(member, JSema.STATIC)) { + modifiers.add(JSema.STATIC); + } + if (truth(member, "final")) { + modifiers.add("final"); + } + if (truth(member, "synchronized")) { + modifiers.add("synchronized"); + } + if (truth(member, JSema.ABSTRACT)) { + modifiers.add(JSema.ABSTRACT); + } + String visibility = text(member, "vis"); + if (visibility != null && !"package".equals(visibility)) { + modifiers.add(visibility); + } + symbol.addModifiers(modifiers); + } + + static List parents(JsonObject info) { + List parents = new ArrayList<>(); + String superName = text(info, "super"); + if (superName != null) { + parents.add(superName); + } + parents.addAll(strings(info, "interfaces")); + parents.addAll(strings(info, "super")); + return parents; + } + + @Nullable + static MemberId parseMember(String id) { + int hash = id.indexOf('#'); + if (hash < 0) { + return null; + } + String owner = id.substring(0, hash); + String rest = id.substring(hash + 1); + int paren = rest.endsWith(")") ? rest.lastIndexOf('(') : -1; + if (paren < 0) { + return new MemberId(owner, rest, null, false, -1, List.of()); + } + String name = rest.substring(0, paren); + String params = rest.substring(paren + 1, rest.length() - 1); + boolean arityOnly = !params.isEmpty() && params.chars().allMatch(Character::isDigit); + List paramList = splitParams(params); + int arity = arityOnly ? Integer.parseInt(params) : paramList.size(); + return new MemberId(owner, name, params, arityOnly, arity, paramList); + } + + static String erase(String id) { + if (id.indexOf('`') < 0) { + return id; + } + StringBuilder out = new StringBuilder(id.length()); + int i = 0; + while (i < id.length()) { + char current = id.charAt(i); + i++; + if (current == '`') { + while (i < id.length() && Character.isDigit(id.charAt(i))) { + i++; + } + } else { + out.append(current); + } + } + return out.toString(); + } + + static String simpleName(String fqn) { + int boundary = Math.max(fqn.lastIndexOf('.'), fqn.lastIndexOf('$')); + String name = boundary < 0 ? fqn : fqn.substring(boundary + 1); + return isAnonymousName(name) ? "" : name; + } + + /** An anonymous class is named by its ordinal, which a source name never is. */ + static boolean isAnonymousName(String name) { + return !name.isEmpty() && name.chars().allMatch(Character::isDigit); + } + + static String packageName(String fqn) { + String top = fqn; + int nested = top.indexOf('$'); + if (nested >= 0) { + top = top.substring(0, nested); + } + int dot = top.lastIndexOf('.'); + return dot < 0 ? "" : top.substring(0, dot); + } + + @Nullable + static String text(@Nullable JsonObject object, String key) { + JsonElement element = object == null ? null : object.get(key); + return element != null && element.isJsonPrimitive() ? element.getAsString() : null; + } + + @Nullable + static String text(String value) { + return value.isEmpty() ? null : value; + } + + /** The values of the last property named {@code name}, as a later key of a JSON object replaces an earlier one. */ + static List prop(Fact fact, String name) { + List values = List.of(); + for (Prop prop : fact.getPropsList()) { + if (name.equals(prop.getName())) { + values = prop.getValuesList(); + } + } + return values; + } + + static boolean truth(JsonObject object, String key) { + return object.has(key) && object.get(key).isJsonPrimitive() && object.get(key).getAsBoolean(); + } + + static List strings(JsonObject object, String key) { + if (object == null || !object.has(key) || object.get(key).isJsonNull()) { + return List.of(); + } + JsonElement element = object.get(key); + if (element.isJsonPrimitive()) { + return List.of(element.getAsString()); + } + if (!element.isJsonArray()) { + return List.of(); + } + List values = new ArrayList<>(); + for (JsonElement item : element.getAsJsonArray()) { + if (item.isJsonPrimitive()) { + values.add(item.getAsString()); + } + } + return values; + } + + static List flat(JsonObject object, String key) { + return flat(strings(object, key)); + } + + static List flat(List strings) { + List values = new ArrayList<>(); + for (String value : strings) { + for (String part : value.split(",")) { + if (!part.isBlank()) { + values.add(part.trim()); + } + } + } + return values; + } + + private static List splitParams(String params) { + if (params.isEmpty()) { + return List.of(); + } + List result = new ArrayList<>(); + int depth = 0; + int start = 0; + for (int i = 0; i < params.length(); i++) { + char current = params.charAt(i); + if (current == '<') { + depth++; + } else if (current == '>') { + depth--; + } else if (current == ',' && depth == 0) { + result.add(params.substring(start, i)); + start = i + 1; + } + } + result.add(params.substring(start)); + return result; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/Substitution.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/Substitution.java new file mode 100644 index 00000000000..ce1d4f5a263 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/Substitution.java @@ -0,0 +1,122 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import org.sonar.plugins.java.api.semantic.Type; + +import static org.sonar.java.semsitter.SemaFacts.strings; +import static org.sonar.java.semsitter.SemaFacts.text; + +/** Type variable substitution: members seen from a parameterized type and supertypes. */ +final class Substitution { + + private static final String TYPE_VARS = "typeVars"; + private static final String PARAM_VARS = "paramVars"; + private final JSema sema; + + Substitution(JSema sema) { + this.sema = sema; + } + + /** {@code declared}, written in terms of the type variables of {@code declaring}'s class, as it reads for that parameterization. */ + Type asMemberOf(Type declared, Type declaring) { + if (!(declared instanceof JType type) || !(declaring instanceof JType owner) || !owner.isParameterized()) { + return declared; + } + return type.substitute(typeArgumentsOf(owner)); + } + + /** Applies {@code from}'s type arguments to a supertype written with those type variables. */ + Type instantiateSupertype(Type from, Type supertype) { + if (!from.isParameterized() || !(from instanceof JType fromType) || !(supertype instanceof JType superType)) { + return supertype; + } + return superType.substitute(typeArgumentsOf(fromType)); + } + + List declaredParameters(JMethodSymbol method) { + List cached = method.declaredParameters(); + if (cached == null) { + JsonObject member = lookupGenericMember(method); + cached = member == null ? List.of() : FactTypes.objects(member, "paramTypes"); + method.declaredParameters(cached); + } + return cached; + } + + /** The type {@code declaring} gives the class type variable that the parameter {@code index} of the library {@code method} is declared as. */ + @Nullable + Type classVariableArgument(JMethodSymbol method, int index, Type declaring) { + List parameters = declaredParameters(method); + if (index >= parameters.size() || !"typevar".equals(text(parameters.get(index), "kind")) || !declaring.isParameterized()) { + return null; + } + JsonObject info = sema.typeInfos.get(sema.sourceName(declaring.erasure().fullyQualifiedName())); + int position = info == null ? -1 : strings(info, TYPE_VARS).indexOf(text(parameters.get(index), "id")); + return position < 0 || position >= declaring.typeArguments().size() ? null : declaring.typeArguments().get(position); + } + + /** The loaded declaration of {@code method}, when its declaring type is known and carries a generic signature. */ + @Nullable + JsonObject lookupGenericMember(JMethodSymbol method) { + String ownerFqn = method.owner().type().erasure().fullyQualifiedName(); + if (!sema.declaresType(ownerFqn)) { + return null; + } + List parameters = method.parameterTypes(); + for (JsonObject member : sema.lookup().membersNamed(ownerFqn, method.name())) { + String descriptor = text(member, "desc"); + if (descriptor != null && member.has(PARAM_VARS) && member.get(PARAM_VARS).isJsonArray() + && sameParameters(parameters, sema.factTypes().parameterTypesOf(descriptor))) { + return member; + } + } + return null; + } + + private Map typeArgumentsOf(JType type) { + JsonObject info = sema.typeInfos.get(sema.sourceName(type.erasure().fullyQualifiedName())); + List names = info == null ? List.of() : strings(info, TYPE_VARS); + List arguments = type.typeArguments(); + Map substitution = new HashMap<>(); + for (int i = 0; i < names.size() && i < arguments.size(); i++) { + substitution.put(names.get(i), arguments.get(i)); + } + return substitution; + } + + /** Whether the parameters match the descriptor's erasures; a type variable, which the symbol cannot name, stands for what the descriptor erases it to. */ + private static boolean sameParameters(List parameters, List descriptor) { + if (parameters.size() != descriptor.size()) { + return false; + } + for (int i = 0; i < parameters.size(); i++) { + Type parameter = parameters.get(i); + String name = parameter.erasure().fullyQualifiedName(); + boolean variable = parameter.isUnknown() || parameter.isTypeVar() || name.contains(SemaFacts.SCOPE_SEPARATOR); + if (!variable && !name.equals(descriptor.get(i).erasure().fullyQualifiedName())) { + return false; + } + } + return true; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/Subtyping.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/Subtyping.java new file mode 100644 index 00000000000..7913a8f6df5 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/Subtyping.java @@ -0,0 +1,153 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.List; +import java.util.Objects; +import java.util.Set; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; + +/** Subtyping between {@link JType}s, with type argument containment (JLS 4.5.1) and primitive widening. */ +final class Subtyping { + + private static final String FLOAT = "float"; + private static final String DOUBLE = "double"; + + private Subtyping() { + } + + static boolean isSubtype(JType type, Type superType, Set visited) { + if (type.kind == JType.Kind.CAPTURE || type.kind == JType.Kind.WILDCARD) { + return isSubtype(type.element, superType, visited); + } + if (superType == null || superType.isUnknown() || type.isUnknown()) { + return false; + } + if (type.isNullType()) { + return !superType.isPrimitive(); + } + if (!visited.add(type.fullyQualifiedName() + ">" + superType.fullyQualifiedName())) { + return false; + } + if (superType.isTypeVar() && !type.isTypeVar()) { + return false; + } + if (superType.isTypeVar() && sameTypeVariable(type, superType)) { + return true; + } + return isSubtypeByStructure(type, superType, visited); + } + + private static boolean sameTypeVariable(JType type, Type superType) { + return type.isTypeVar() && superType instanceof JType other && Objects.equals(type.typeVarId, other.typeVarId); + } + + private static boolean isSubtypeByStructure(JType type, Type superType, Set visited) { + if (!type.isArray() && sameErasure(type, superType) && argumentsMatch(type, superType)) { + return true; + } + if (type.isPrimitive() && superType.isPrimitive()) { + return widensTo(type.fullyQualifiedName(), superType.fullyQualifiedName()); + } + if (type.kind == JType.Kind.INTERSECTION) { + return type.intersectionBounds.stream().anyMatch(bound -> isSubtype(bound, superType, visited)); + } + if (type.isArray()) { + return isArraySubtype(type, superType); + } + if (type.isTypeVar()) { + return hasSubtypeBound(type, superType, visited); + } + if (type.isPrimitive() || superType.isPrimitive()) { + return false; + } + return inheritsFrom(type, superType, visited); + } + + private static boolean isArraySubtype(JType type, Type superType) { + if (superType.isArray()) { + return type.elementType().isSubtypeOf(((Type.ArrayType) superType).elementType()); + } + return superType.is(SemaFacts.OBJECT_TYPE) || superType.is("java.lang.Cloneable") || superType.is("java.io.Serializable"); + } + + private static boolean hasSubtypeBound(JType type, Type superType, Set visited) { + return type.sema.memberFactory().typeVariableBounds(type.typeVarId).stream() + .anyMatch(bound -> bound instanceof JType upper && !upper.isUnknown() && upper != type && isSubtype(upper, superType, visited)); + } + + private static boolean inheritsFrom(JType type, Type superType, Set visited) { + Symbol.TypeSymbol owner = type.declaredSymbol(); + // Supertypes are walked erased: their arguments name the owner's type variables, not this type's arguments. + Type superClass = owner.superClass(); + if (superClass != null && superClass.erasure() instanceof JType erasedSuper && isSubtype(erasedSuper, superType, visited)) { + return true; + } + for (Type iface : owner.interfaces()) { + if (iface.erasure() instanceof JType erasedIface && isSubtype(erasedIface, superType, visited)) { + return true; + } + } + return false; + } + + private static boolean sameErasure(JType type, Type superType) { + return type.fullyQualifiedName().equals(superType.erasure().fullyQualifiedName()); + } + + private static boolean argumentsMatch(JType type, Type superType) { + List theirs = superType.typeArguments(); + if (type.args.isEmpty() || theirs.isEmpty()) { + return true; + } + if (type.args.size() != theirs.size()) { + return false; + } + for (int i = 0; i < type.args.size(); i++) { + if (!contains(theirs.get(i), type.args.get(i))) { + return false; + } + } + return true; + } + + /** Whether the type argument {@code mine} is contained by {@code theirs} (JLS 4.5.1). */ + private static boolean contains(Type theirs, JType mine) { + if (theirs instanceof JType wanted && wanted.isWildcard()) { + if (wanted.lower != null) { + return mine.isWildcard() ? (mine.lower != null && wanted.lower.isSubtypeOf(mine.lower)) : wanted.lower.isSubtypeOf(mine); + } + if (wanted.element.is(SemaFacts.OBJECT_TYPE)) { + return true; + } + return mine.isSubtypeOf(wanted.element); + } + return !mine.isWildcard() && mine.is(theirs.fullyQualifiedName()); + } + + private static boolean widensTo(String from, String to) { + return switch (from) { + case "byte" -> Set.of("short", "int", "long", FLOAT, DOUBLE).contains(to); + case "short", "char" -> Set.of("int", "long", FLOAT, DOUBLE).contains(to); + case "int" -> Set.of("long", FLOAT, DOUBLE).contains(to); + case "long" -> Set.of(FLOAT, DOUBLE).contains(to); + case FLOAT -> DOUBLE.equals(to); + default -> false; + }; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/TreeAnnotation.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/TreeAnnotation.java new file mode 100644 index 00000000000..6a9b624fb56 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/TreeAnnotation.java @@ -0,0 +1,157 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; +import org.sonar.java.model.AnnotationValueImpl; +import org.sonar.java.model.LiteralUtils; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.AnnotationInstance; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.AnnotationValue; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.AnnotationTree; +import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; +import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.LiteralTree; +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; +import org.sonar.plugins.java.api.tree.NewArrayTree; +import org.sonar.plugins.java.api.tree.Tree; + +final class TreeAnnotation implements AnnotationInstance { + + private final JSema sema; + private final AnnotationTree tree; + + TreeAnnotation(JSema sema, AnnotationTree tree) { + this.sema = sema; + this.tree = tree; + } + + @Override + public Symbol.TypeSymbol symbol() { + Type type = tree.annotationType().symbolType(); + if (type.isUnknown() && tree.symbolType().isUnknown() && !SemaFacts.UNKNOWN_TYPE_NAME.equals(tree.symbolType().fullyQualifiedName())) { + // an unresolved annotation still carries its written name + type = tree.symbolType(); + } + return type.symbol(); + } + + @Override + public List values() { + List values = new ArrayList<>(); + if (symbol().isUnknown()) { + // the members of an annotation nothing declares cannot be told apart from other expressions + return values; + } + for (ExpressionTree argument : tree.arguments()) { + if (argument instanceof AssignmentExpressionTree assignment) { + String name = assignment.variable().toString(); + values.add(new AnnotationValueImpl(name, value(name, assignment.expression()))); + } else { + values.add(new AnnotationValueImpl("value", value("value", argument))); + } + } + return values; + } + + static Object literal(JSema sema, ExpressionTree expression) { + if (expression instanceof LiteralTree literal) { + return constantValue(literal); + } + if (expression instanceof AnnotationTree annotation) { + return new TreeAnnotation(sema, annotation); + } + if (expression instanceof NewArrayTree array) { + return array.initializers().stream().map(initializer -> literal(sema, initializer)).toArray(); + } + if (expression instanceof MemberSelectExpressionTree select && "class".equals(select.identifier().name())) { + return select.expression().symbolType().symbol(); + } + Symbol symbol = symbolOf(expression); + if (symbol instanceof Symbol.VariableSymbol variable && !variable.isUnknown()) { + return variable.constantValue().orElse(variable.isEnum() ? variable : null); + } + if (symbol != null && symbol.isUnknown()) { + return null; + } + return expression.asConstant().orElse(null); + } + + /** + * The value of the member {@code name}, wrapped in an array when the member is array typed, as the value of an + * array typed member is always an array no matter how many elements the annotation spells out. + */ + private Object value(String name, ExpressionTree expression) { + Object value = literal(expression); + return value instanceof Object[] || !isArrayTyped(name) ? value : new Object[] {value}; + } + + private boolean isArrayTyped(String name) { + return symbol().lookupSymbols(name).stream() + .anyMatch(member -> member instanceof Symbol.MethodSymbol method && method.returnType().type().isArray()); + } + + private Object literal(ExpressionTree expression) { + return literal(sema, expression); + } + + /** + * The compile time value of {@code literal}, typed as the literal is: a {@link String} for text, a {@link Boolean} + * for booleans and an {@link Integer} for an int that fits. Anything else keeps its source spelling. + */ + private static Object constantValue(LiteralTree literal) { + String value = literal.value(); + return switch (literal.kind()) { + case STRING_LITERAL, TEXT_BLOCK -> LiteralUtils.trimQuotes(value); + case BOOLEAN_LITERAL -> Boolean.valueOf(value); + case INT_LITERAL -> { + Integer integer = LiteralUtils.intLiteralValue(literal); + yield integer == null ? value : integer; + } + case LONG_LITERAL -> { + Long number = LiteralUtils.longLiteralValue(literal); + yield number == null ? value : number; + } + case CHAR_LITERAL -> (char) LiteralUtils.charLiteralValue(literal); + case FLOAT_LITERAL, DOUBLE_LITERAL -> floatingValue(value, literal.is(Tree.Kind.FLOAT_LITERAL)); + default -> value; + }; + } + + private static Object floatingValue(String value, boolean isFloat) { + String digits = value.replace("_", ""); + if (isFloat) { + return Float.valueOf(digits); + } + return Double.valueOf(digits); + } + + @Nullable + private static Symbol symbolOf(ExpressionTree expression) { + if (expression instanceof MemberSelectExpressionTree select) { + return select.identifier().symbol(); + } + if (expression instanceof IdentifierTree identifier) { + return identifier.symbol(); + } + return null; + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FactTypesTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FactTypesTest.java new file mode 100644 index 00000000000..3738ab411d9 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FactTypesTest.java @@ -0,0 +1,182 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.TypeRef; + +import static org.assertj.core.api.Assertions.assertThat; + +class FactTypesTest { + + private static final String TYPES = """ + { + "p.Bounded": {"kind": "class", "typeVarBounds": [[{"kind": "class", "id": "java.lang.Number"}], [{"kind": "class", "id": "java.lang.Object"}], + [], ["text"], "flat", [{"kind": "unknown"}]]}, + "p.Plain": {"kind": "class"}, + "java.lang.Number": {"kind": "class"} + } + """; + + private final JSema sema = new JSema(); + private final FactTypes types = sema.factTypes(); + + @Test + void facts_without_a_class_id_are_unknown() { + assertThat(types.typeFromFact(json("{\"kind\": \"unknown\", \"id\": \"p.A\"}")).isUnknown()).isTrue(); + assertThat(types.typeFromFact(json("{\"kind\": \"class\"}")).isUnknown()).isTrue(); + assertThat(types.typeFromFact(json("{\"kind\": \"array\"}")).isUnknown()).isTrue(); + assertThat(types.typeFromFact(json("{\"kind\": \"primitive\", \"id\": \"int\"}")).fullyQualifiedName()).isEqualTo("int"); + } + + @Test + void type_arguments_that_are_no_facts_are_skipped() { + JType type = types.typeFromFact(json("{\"kind\": \"class\", \"id\": \"java.util.Map\", \"args\": [\"K\", {\"kind\": \"class\", \"id\": \"java.lang.String\"}]}")); + + assertThat(type.typeArguments()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.String"); + } + + @Test + void type_variables_are_substituted_or_named_after_their_id() { + Type string = sema.getClassType("java.lang.String"); + + assertThat(types.typeFromFact(json("{\"kind\": \"typevar\", \"id\": \"p.A\"}"), Map.of("p.A", string))).isSameAs(string); + assertThat(types.typeFromFact(json("{\"kind\": \"typevar\", \"id\": \"p.A\"}")).name()).isEqualTo("T"); + assertThat(types.typeFromFact(json("{\"kind\": \"typevar\", \"id\": \"T\"}")).name()).isEqualTo("T"); + assertThat(types.typeFromFact(json("{\"kind\": \"typevar\", \"id\": \"p.Ax\"}")).name()).isEqualTo("Ax"); + assertThat(types.typeFromFact(json("{\"kind\": \"typevar\"}"), new HashMap<>()).name()).isEmpty(); + } + + @Test + void wildcards_are_bounded_or_captured() { + JType lower = types.typeFromFact(json("{\"kind\": \"wildcard\", \"super\": {\"kind\": \"class\", \"id\": \"java.lang.Integer\"}}")); + JType captured = types.typeFromFact(json("{\"kind\": \"wildcard\", \"extends\": {\"kind\": \"unknown\"}}"), Map.of(), true); + + assertThat(lower.isWildcard()).isTrue(); + assertThat(captured.isCapture()).isTrue(); + assertThat(captured.element.fullyQualifiedName()).isEqualTo("java.lang.Object"); + } + + @Test + void captured_unbounded_wildcards_take_the_declared_class_bound() { + sema.ingestTypes(json(TYPES)); + String wildcard = "{\"kind\": \"wildcard\"}"; + JType bounded = types.typeFromFact(json("{\"kind\": \"class\", \"id\": \"p.Bounded\", \"args\": [" + String.join(",", List.of(wildcard, wildcard, wildcard, wildcard, + wildcard, wildcard, wildcard)) + "]}"), Map.of(), true); + JType plain = types.typeFromFact(json("{\"kind\": \"class\", \"id\": \"p.Plain\", \"args\": [" + wildcard + "]}"), Map.of(), true); + JType undeclared = types.typeFromFact(json("{\"kind\": \"class\", \"id\": \"p.Undeclared\", \"args\": [" + wildcard + "]}"), Map.of(), true); + JType typed = types.typeFromFact(json("{\"kind\": \"class\", \"id\": \"p.Bounded\", \"args\": [{\"kind\": \"class\", \"id\": \"java.lang.Long\"}]}"), Map.of(), true); + + assertThat(bounded.typeArguments()).extracting(argument -> ((JType) argument).element.fullyQualifiedName()) + .containsExactly("java.lang.Number", "java.lang.Object", "java.lang.Object", "java.lang.Object", "java.lang.Object", "java.lang.Object", "java.lang.Object"); + assertThat(((JType) plain.typeArguments().get(0)).element.fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(((JType) undeclared.typeArguments().get(0)).element.fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(typed.typeArguments()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.Long"); + } + + @Test + void document_type_refs_build_arrays_wildcards_variables_and_parameterized_types() { + TypeRef list = TypeRef.newBuilder().setKind("class").setId("java.util.List").addArguments(TypeRef.newBuilder().setKind("wildcard")).build(); + + assertThat(types.typeFromRef(TypeRef.newBuilder().setKind("array").setElement(list).build()).isArray()).isTrue(); + assertThat(types.typeFromRef(TypeRef.newBuilder().setKind("array").build()).isUnknown()).isTrue(); + assertThat(types.typeFromRef(TypeRef.newBuilder().setKind("class").build()).isUnknown()).isTrue(); + assertThat(types.typeFromRef(TypeRef.newBuilder().setKind("typevar").setId("p.A").build()).name()).isEqualTo("T"); + assertThat(types.typeFromRef(list).typeArguments()).hasSize(1); + } + + @Test + void supertype_facts_keep_their_type_arguments() { + Type raw = types.supertypeFromFact(json("{\"id\": \"java.util.List\", \"args\": []}")); + Type parameterized = types.supertypeFromFact(json("{\"id\": \"java.util.List\", \"args\": [1, {\"kind\": \"class\", \"id\": \"java.lang.String\"}]}")); + Type unknown = types.supertypeFromFact(json("{\"id\": \"\", \"args\": [{\"kind\": \"class\", \"id\": \"java.lang.String\"}]}")); + + assertThat(raw.isParameterized()).isFalse(); + assertThat(parameterized.typeArguments()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.String"); + assertThat(unknown).isSameAs(Type.UNKNOWN); + assertThat(FactTypes.objects(json("{\"a\": [1, {}], \"b\": {}}"), "a")).hasSize(1); + assertThat(FactTypes.objects(json("{\"b\": {}}"), "b")).isEmpty(); + assertThat(FactTypes.objects(json("{}"), "a")).isEmpty(); + } + + @Test + void descriptors_give_primitive_class_and_array_types() { + List parameters = types.parameterTypesOf("(BCDFIJSZ[[Ljava/lang/String;)V"); + + assertThat(parameters).extracting(Type::fullyQualifiedName) + .containsExactly("byte", "char", "double", "float", "int", "long", "short", "boolean", "java.lang.String[][]"); + assertThat(types.readDescriptor("V", new int[] {0}).fullyQualifiedName()).isEqualTo("void"); + assertThat(types.parameterTypesOf("(I")).extracting(Type::fullyQualifiedName).containsExactly("int"); + } + + @Test + void type_parameter_items_name_the_variables_of_classes_and_callables_by_position() { + sema.ingestDocument(Document.newBuilder() + .addSymbols(symbol("p.A", "type", "A")) + .addSymbols(symbol("p.A", "type", "T")) + .addSymbols(symbol("p.A$B", "type", "B")) + .addSymbols(symbol("p.A$B", "type", "U")) + .addSymbols(symbol("p.A$B>", "type", "V")) + .addSymbols(symbol("p.A$B<>", "type", "")) + .addSymbols(symbol("p.A$B#f", "field", "f")) + .addSymbols(symbol("p.A$B", "field", "Y")) + .addSymbols(symbol("p.G", "type", "E")) + .addSymbols(symbol("p.A#m()", "method", "m")) + .addSymbols(symbol("p.A#m()", "type", "M")) + .build()); + + assertThat(types.typeFromName("p.A::`0").name()).isEqualTo("T"); + assertThat(types.typeFromName("p.A$B::`1").name()).isEqualTo("U"); + assertThat(types.typeFromName("p.G`1::`0").name()).isEqualTo("E"); + assertThat(types.typeFromName("p.A#m()::``0").name()).isEqualTo("M"); + assertThat(types.typeFromName("p.A$B::`2").isTypeVar()).isFalse(); + assertThat(types.typeFromName("::`0").isTypeVar()).isFalse(); + assertThat(types.typeFromName("p.A::`").isTypeVar()).isFalse(); + assertThat(types.typeFromName("p.A::`x").isTypeVar()).isFalse(); + assertThat(types.typeFromName("int[]").fullyQualifiedName()).isEqualTo("int[]"); + } + + @Test + void parameter_placeholders_are_shared_per_method_and_position_unless_annotated() { + JMethodSymbol method = new JMethodSymbol(sema, "p.A#m(int)", "m"); + JMethodSymbol annotated = new JMethodSymbol(sema, "p.A#a(int)", "a"); + sema.declaredMembers.libraryAnnotations.put(SemaFacts.parameterKey("p.A#a(int)", 0), List.of()); + JMethodSymbol anonymous = new JMethodSymbol(sema, null, "n"); + Type type = sema.primitiveType("int"); + + assertThat(types.parameterPlaceholder(method, 0, type)).isSameAs(types.parameterPlaceholder(method, 0, type)); + assertThat(types.parameterPlaceholder(annotated, 0, type)).isInstanceOf(JVariableSymbol.class).isSameAs(types.parameterPlaceholder(annotated, 0, type)); + assertThat(((Symbol.VariableSymbol) types.parameterPlaceholder(annotated, 0, type)).isParameter()).isTrue(); + assertThat(types.parameterPlaceholder(anonymous, 0, type)).isNotSameAs(types.parameterPlaceholder(anonymous, 0, type)); + } + + private static org.sonarsource.semsitter.wire.Symbol.Builder symbol(String id, String kind, String name) { + return org.sonarsource.semsitter.wire.Symbol.newBuilder().setId(id).setKind(kind).setName(name); + } + + private static JsonObject json(String text) { + return JsonParser.parseString(text).getAsJsonObject(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JMethodSymbolTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JMethodSymbolTest.java new file mode 100644 index 00000000000..a9db0d7b61b --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JMethodSymbolTest.java @@ -0,0 +1,193 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; +import org.sonar.plugins.java.api.tree.MethodTree; + +import static org.assertj.core.api.Assertions.assertThat; + +class JMethodSymbolTest { + + private static final String SOURCE = """ + @interface Ann { + int value() default 1; + String[] names() default "x"; + String[] all() default {"a", "b"}; + int none(); + } + class M { + void generic(T t) { + } + void plain() { + } + void varargs(String... args) { + } + void array(String[] args) { + } + } + """; + + @TempDir + Path baseDir; + + private final JSema sema = new JSema(); + private CompilationUnitTree unit; + private JTypeSymbol owner; + + @BeforeEach + void setUp() throws Exception { + unit = (CompilationUnitTree) Replays.parseWithEcj(baseDir, "Ann", SOURCE).get(); + owner = sema.typeSymbol("p.A"); + owner.owner(sema.packageSymbol("p")); + } + + @Test + void signature_is_the_descriptor_of_erased_types() { + JMethodSymbol method = method("p.A#m(byte,char,double,float,int,long,short,boolean,java.lang.String[],X)"); + method.parameterTypes(List.of(primitive("byte"), primitive("char"), primitive("double"), primitive("float"), primitive("int"), primitive("long"), + primitive("short"), primitive("boolean"), JType.array(sema, (JType) sema.getClassType("java.lang.String")), JType.unknown(sema))); + method.returnTypeSymbol(sema.memberFactory().primitiveSymbol("void")); + + assertThat(method.signature()).isEqualTo("p.A#m(BCDFIJSZ[Ljava/lang/String;Ljava/lang/Object;)V"); + } + + @Test + void constructors_of_enums_and_inner_classes_take_hidden_parameters() { + owner.enumSymbol(true); + JTypeSymbol inner = sema.typeSymbol("p.O$I"); + inner.owner(sema.typeSymbol("p.O")); + JMethodSymbol innerConstructor = new JMethodSymbol(sema, "p.O$I#()", ""); + innerConstructor.owner(inner); + JTypeSymbol nested = sema.typeSymbol("p.O$N"); + nested.owner(sema.typeSymbol("p.O")); + nested.addModifiers(List.of("static")); + JMethodSymbol nestedConstructor = new JMethodSymbol(sema, "p.O$N#()", ""); + nestedConstructor.owner(nested); + + assertThat(method("p.A#()").signature()).isEqualTo("p.A#(Ljava/lang/String;I)V"); + assertThat(innerConstructor.signature()).isEqualTo("p.O$I#(Lp/O;)V"); + assertThat(nestedConstructor.signature()).isEqualTo("p.O$N#()V"); + } + + @Test + void signature_of_an_unknown_method_or_one_owned_by_no_type_is_its_id() { + JMethodSymbol unknown = method("p.A#u`1()"); + unknown.unknown(true); + JMethodSymbol inMethod = new JMethodSymbol(sema, "p.A#m()#n()", "n"); + inMethod.owner(sema.packageSymbol("p")); + + assertThat(unknown.signature()).isEqualTo("p.A#u()"); + assertThat(inMethod.signature()).isEqualTo("p.A#m()#n()"); + } + + @Test + void unknown_methods_have_no_flags() { + JMethodSymbol unknown = method("p.A#m()", "default", "synchronized", "native"); + unknown.parametrized(true); + unknown.varArgs(true); + unknown.unknown(true); + + assertThat(unknown.isOverridable()).isFalse(); + assertThat(unknown.isParametrizedMethod()).isFalse(); + assertThat(unknown.isDefaultMethod()).isFalse(); + assertThat(unknown.isSynchronizedMethod()).isFalse(); + assertThat(unknown.isNativeMethod()).isFalse(); + assertThat(unknown.isVarArgsMethod()).isFalse(); + } + + @Test + void methods_of_final_classes_are_not_overridable() { + owner.addModifiers(List.of("final")); + + assertThat(method("p.A#m()").isOverridable()).isFalse(); + assertThat(method("p.A#m()").isNativeMethod()).isFalse(); + } + + @Test + void declared_methods_are_generic_and_variable_arity_as_written() { + assertThat(declared("generic").isParametrizedMethod()).isTrue(); + assertThat(declared("plain").isParametrizedMethod()).isFalse(); + assertThat(declared("plain").isVarArgsMethod()).isFalse(); + assertThat(declared("varargs").isVarArgsMethod()).isTrue(); + assertThat(declared("array").isVarArgsMethod()).isFalse(); + } + + @Test + void variable_arity_without_declaration_comes_from_the_answer_or_the_last_parameter() { + JMethodSymbol known = method("p.A#k(java.lang.String[])"); + known.parameterTypes(List.of(JType.array(sema, (JType) sema.getClassType("java.lang.String")))); + known.varArgsKnown(true); + JMethodSymbol guessed = method("p.A#g(java.lang.String[])"); + guessed.parameterTypes(known.parameterTypes()); + + assertThat(known.isVarArgsMethod()).isFalse(); + assertThat(guessed.isVarArgsMethod()).isTrue(); + assertThat(method("p.A#n()").isVarArgsMethod()).isFalse(); + } + + @Test + void annotation_element_defaults_come_from_the_declaration_or_the_answer() { + JMethodSymbol names = declared("names"); + names.returnTypeSymbol(sema.getClassType("java.lang.String[]").symbol()); + JMethodSymbol all = declared("all"); + all.returnTypeSymbol(sema.getClassType("java.lang.String[]").symbol()); + JMethodSymbol served = method("p.A#s()"); + sema.declaredMembers.annotationDefaults.put("p.A#s()", 3); + + assertThat(declared("value").annotationElementDefaultValue()).isEqualTo(1); + assertThat(declared("none").annotationElementDefaultValue()).isNull(); + assertThat((Object[]) names.annotationElementDefaultValue()).containsExactly("x"); + assertThat((Object[]) all.annotationElementDefaultValue()).containsExactly("a", "b"); + assertThat(served.annotationElementDefaultValue()).isEqualTo(3); + assertThat(new JMethodSymbol(sema, null, "x").annotationElementDefaultValue()).isNull(); + } + + private Type primitive(String name) { + return sema.primitiveType(name); + } + + private JMethodSymbol method(String id, String... modifiers) { + JMethodSymbol method = new JMethodSymbol(sema, id, SemaFacts.memberName(id)); + method.owner(owner); + method.addModifiers(List.of(modifiers)); + return method; + } + + private JMethodSymbol declared(String name) { + List found = new ArrayList<>(); + unit.accept(new BaseTreeVisitor() { + @Override + public void visitMethod(MethodTree tree) { + if (name.equals(tree.simpleName().name())) { + found.add(tree); + } + } + }); + JMethodSymbol method = method("p.A#" + name + "()"); + sema.declare(method.id, found.get(0)); + return method; + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaEdgesTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaEdgesTest.java new file mode 100644 index 00000000000..08c8fdb4157 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaEdgesTest.java @@ -0,0 +1,107 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Document; + +import static org.assertj.core.api.Assertions.assertThat; + +class JSemaEdgesTest { + + private final JSema sema = new JSema(); + + @Test + void local_classes_are_numbered_per_enclosing_class() { + Document document = Document.newBuilder() + .addSymbols(type("p.C#f()$Local")) + .addSymbols(type("p.C#g()$Local")) + .addSymbols(type("p.C#f()$Local$Inner")) + .addSymbols(type("p.C#f()$")) + .addSymbols(type("p.C#h")) + .addSymbols(org.sonarsource.semsitter.wire.Symbol.newBuilder().setKind("type").setName("empty")) + .build(); + sema.ingestDocument(document); + sema.ingestDocument(document); + + assertThat(sema.sourceName("p.C$1Local")).isIn("p.C#f()$Local", "p.C#g()$Local"); + assertThat(sema.sourceName("p.C$2Local")).isIn("p.C#f()$Local", "p.C#g()$Local").isNotEqualTo(sema.sourceName("p.C$1Local")); + assertThat(sema.sourceName("p.C#f()$")).isEqualTo("p.C#f()$"); + assertThat(sema.sourceName("p.C#h")).isEqualTo("p.C#h"); + assertThat(sema.symbols).doesNotContainKey(""); + } + + @Test + void local_classes_in_lambdas_do_not_collide_with_enclosing_method_locals() { + BinaryNames names = new BinaryNames(); + + String inMethod = names.binaryName("p.C#f()$Local"); + String inLambda = names.binaryName("p.C#f()$lambda$1:2()$Local"); + String nestedInLambda = names.binaryName("p.C#f()$lambda$1:2()$Local$Inner"); + + assertThat(inMethod).isEqualTo("p.C$1Local"); + assertThat(inLambda).isEqualTo("p.C$2Local"); + assertThat(nestedInLambda).isEqualTo("p.C$2Local$Inner"); + assertThat(names.sourceName("p.C$1Local")).isEqualTo("p.C#f()$Local"); + assertThat(names.sourceName("p.C$2Local")).isEqualTo("p.C#f()$lambda$1:2()$Local"); + assertThat(names.sourceName("p.C$2Local$Inner")).isEqualTo("p.C#f()$lambda$1:2()$Local$Inner"); + } + + @Test + void class_types_by_special_names() { + assertThat(sema.getClassType("").isNullType()).isTrue(); + assertThat(sema.getClassType("!Unknown![]").fullyQualifiedName()).endsWith("[]"); + assertThat(sema.getClassType("int[]").isArray()).isTrue(); + assertThat(sema.asJType(Type.UNKNOWN).isUnknown()).isTrue(); + } + + @Test + void empty_ids_and_labels_resolve_to_the_unknown_symbol() { + sema.ingestDocument(Document.newBuilder() + .addSymbols(org.sonarsource.semsitter.wire.Symbol.newBuilder().setId("p.A#m()#label").setKind("label").setName("label")) + .build()); + + assertThat(sema.resolve(null)).isSameAs(sema.unknownSymbol); + assertThat(sema.resolve("")).isSameAs(sema.unknownSymbol); + assertThat(sema.resolve("p.A#m()#label")).isSameAs(sema.unknownSymbol); + } + + @Test + void types_the_loader_cannot_answer_stay_known() { + sema.loadTypes(names -> new JsonObject()); + sema.typeLoader = names -> null; + + assertThat(sema.typeSymbol("p.Late").isUnknown()).isFalse(); + assertThat(sema.typeSymbol("p.Late")).isSameAs(sema.typeSymbol("p.Late")); + } + + @Test + void parsed_member_ids_are_cached_per_sema() { + MemberId first = sema.parseMember("p.A#m(int)"); + + assertThat(sema.parseMember("p.A#m(int)")).isSameAs(first); + assertThat(sema.memberName("p.A#m(int)")).isEqualTo("m"); + assertThat(sema.parseMember("p.A")).isNull(); + assertThat(sema.memberName("p.A")).isNull(); + } + + private static org.sonarsource.semsitter.wire.Symbol.Builder type(String id) { + return org.sonarsource.semsitter.wire.Symbol.newBuilder().setId(id).setKind("type").setName("T"); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaTest.java new file mode 100644 index 00000000000..9ed53daaac3 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaTest.java @@ -0,0 +1,169 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.sonar.java.model.InternalSyntaxToken; +import org.sonar.java.model.expression.IdentifierTreeImpl; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactEntry; +import org.sonarsource.semsitter.wire.FactValue; +import org.sonarsource.semsitter.wire.Prop; +import org.sonarsource.semsitter.wire.TypeRef; + +import static org.assertj.core.api.Assertions.assertThat; + +class JSemaTest { + + @Test + void graph_facts_give_kind_supertypes_modifiers_and_annotations() { + JSema sema = sema(Document.newBuilder() + .addFacts(fact("p.A", Fact.newBuilder().setKind("class").setParent("p::") + .addProps(Prop.newBuilder().setName("modifiers").addValues("public,final")) + .addProps(Prop.newBuilder().setName("modifiers").addValues("abstract")) + .addAnnotations("java.lang.Deprecated").addExtends("java.lang.Object").addImplements("java.io.Serializable"))) + .addSymbols(symbol("p.A", "type", "A", "")) + .build()); + + Symbol.TypeSymbol type = (Symbol.TypeSymbol) sema.resolve("p.A"); + assertThat(type.isAbstract()).isTrue(); + assertThat(type.isFinal()).isFalse(); + assertThat(type.isDeprecated()).isTrue(); + assertThat(type.superClass().fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(type.interfaces()).extracting(Type::fullyQualifiedName).containsExactly("java.io.Serializable"); + } + + @Test + void declared_types_of_symbols_are_read_from_type_refs() { + JSema sema = sema(Document.newBuilder() + .addSymbols(symbol("p.A", "type", "A", "")) + .addSymbols(symbol("p.A", "type", "T", "p.A")) + .addSymbols(field("p.A#list", TypeRef.newBuilder().setKind("class").setId("java.util.List").addArguments(TypeRef.newBuilder().setKind("wildcard")))) + .addSymbols(field("p.A#array", TypeRef.newBuilder().setKind("array").setElement(TypeRef.newBuilder().setKind("primitive").setId("int")))) + .addSymbols(field("p.A#variable", TypeRef.newBuilder().setKind("typevar").setId("p.A"))) + .addSymbols(field("p.A#unknown", TypeRef.newBuilder().setKind("unknown"))) + .build()); + + assertThat(sema.referencedTypeNames()).contains("java.util.List", "p.A"); + assertThat(sema.resolve("p.A#list").type().fullyQualifiedName()).isEqualTo("java.util.List"); + assertThat(sema.resolve("p.A#array").type().fullyQualifiedName()).isEqualTo("int[]"); + assertThat(sema.resolve("p.A#variable").type().name()).isEqualTo("T"); + assertThat(sema.resolve("p.A#unknown").type().isUnknown()).isTrue(); + } + + @Test + void only_an_implicit_enum_method_gets_its_return_type_from_the_owner() { + JSema sema = sema(Document.newBuilder() + .addSymbols(symbol("p.E", "type", "E", "")) + .addSymbols(symbol("p.E#values()", "method", "values", "p.E").putFacts("implicit", FactValue.newBuilder().setFlag(true).build())) + .addSymbols(symbol("p.E#valueOf(java.lang.String)", "method", "valueOf", "p.E").putFacts("implicit", FactValue.getDefaultInstance())) + .build()); + + Symbol.MethodSymbol values = (Symbol.MethodSymbol) sema.resolve("p.E#values()"); + assertThat(values.returnType().type().fullyQualifiedName()).isEqualTo("p.E[]"); + assertThat(values.isStatic()).isTrue(); + assertThat(((Symbol.MethodSymbol) sema.resolve("p.E#valueOf(java.lang.String)")).returnType().type().isUnknown()).isTrue(); + } + + @Test + void member_facts_of_a_types_answer_read_like_document_facts() { + JSema sema = sema(Document.getDefaultInstance()); + JsonObject answer = JsonParser.parseString(""" + {"q.B": {"origin":"project","kind":"class","members":[ + {"id":"q.B#k(int)","facts":{"kind":"method","returns":"int","params":["int"],"props":{"modifiers":"static","param_types":["int..."]}}}, + {"id":"q.B#c","facts":{"kind":"field","type":["long"],"props":{"modifiers":["private,final"]}}}, + {"id":"q.B#d","facts":{"kind":"field","type":"java.lang.String","annotations":["java.lang.Deprecated"]}} + ]}} + """).getAsJsonObject(); + sema.loadTypes(names -> answer); + + Symbol.MethodSymbol method = (Symbol.MethodSymbol) sema.resolve("q.B#k(int)"); + assertThat(method.isStatic()).isTrue(); + assertThat(method.isVarArgsMethod()).isTrue(); + assertThat(method.returnType().type().fullyQualifiedName()).isEqualTo("int"); + Symbol constant = sema.resolve("q.B#c"); + assertThat(constant.isPrivate()).isTrue(); + assertThat(constant.isFinal()).isTrue(); + assertThat(constant.type().fullyQualifiedName()).isEqualTo("long"); + Symbol deprecated = sema.resolve("q.B#d"); + assertThat(deprecated.isDeprecated()).isTrue(); + assertThat(deprecated.type().fullyQualifiedName()).isEqualTo("java.lang.String"); + } + + @Test + void generic_project_methods_are_indexed_by_simple_name_and_handle_reentrant_member_resolution() { + JSema sema = sema(Document.getDefaultInstance()); + JsonObject answer = JsonParser.parseString(""" + {"q.G": {"origin":"project","kind":"class","members":[ + {"id":"q.G`1#max<``0:java.lang.Comparable<``0>>(``0,``0)","name":"max","desc":"(Ljava/lang/Comparable;Ljava/lang/Comparable;)Ljava/lang/Comparable;", + "paramVars":["m0","m0"],"facts":{"kind":"method","returns":["java.lang.Comparable"],"params":["java.lang.Comparable","java.lang.Comparable"], + "props":{"member_name":["max"],"simple_name":["max"],"modifiers":["static"]}}}, + {"id":"q.G`1#other(q.G)","name":"other","facts":{"kind":"method","returns":["void"],"params":["q.G"],"props":{"member_name":["other"],"simple_name":["other"]}}} + ]}, + "q.H": {"origin":"project","kind":"class","super":"q.G","members":[]}} + """).getAsJsonObject(); + sema.loadTypes(names -> answer); + + assertThat(sema.lookup().membersNamed("q.G", "max")).hasSize(1); + assertThat(sema.resolve("q.H#max<``0:java.lang.Comparable<``0>>(``0,``0)").owner().type().fullyQualifiedName()).isEqualTo("q.G"); + assertThat(sema.resolve("q.H#max(``0,``0)").owner().type().fullyQualifiedName()).isEqualTo("q.G"); + JTypeSymbol type = sema.typeSymbol("q.G"); + assertThat(type.membersNamed("other")).extracting(Symbol::name).containsExactly("other"); + assertThat(type.membersNamed("other")).extracting(Symbol::name).containsExactly("other"); + } + + @Test + void updating_type_parameter_bounds_invalidates_nested_subtype_cache() { + JSema sema = sema(Document.getDefaultInstance()); + JType typeVar = JType.typeVar(sema, "T", "p.Box::T"); + JType arrayOfT = JType.array(sema, typeVar); + JType number = sema.rawNamed("java.lang.Number"); + JType arrayOfNumber = JType.array(sema, number); + assertThat(arrayOfT.isSubtypeOf(arrayOfNumber)).isFalse(); + + JTypeSymbol param = (JTypeSymbol) sema.memberFactory().typeParameter("p.Box::T"); + IdentifierTreeImpl boundTree = new IdentifierTreeImpl(new InternalSyntaxToken(1, 0, "Number", List.of(), false)); + boundTree.setSymbolType(number); + param.boundTrees(List.of(boundTree)); + + assertThat(arrayOfT.isSubtypeOf(arrayOfNumber)).isTrue(); + } + + private static JSema sema(Document document) { + JSema sema = new JSema(); + sema.ingestDocument(document); + return sema; + } + + private static FactEntry fact(String key, Fact.Builder fact) { + return FactEntry.newBuilder().setKey(key).setValue(fact).build(); + } + + private static org.sonarsource.semsitter.wire.Symbol.Builder symbol(String id, String kind, String name, String owner) { + return org.sonarsource.semsitter.wire.Symbol.newBuilder().setId(id).setKind(kind).setName(name).setOwner(owner); + } + + private static org.sonarsource.semsitter.wire.Symbol.Builder field(String id, TypeRef.Builder type) { + return symbol(id, "field", id.substring(id.indexOf('#') + 1), "p.A").putFacts("type", FactValue.newBuilder().setType(type).build()); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSymbolTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSymbolTest.java new file mode 100644 index 00000000000..dfb4917adc4 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSymbolTest.java @@ -0,0 +1,245 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.CatchTree; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; + +import static org.assertj.core.api.Assertions.assertThat; + +class JSymbolTest { + + private static final String SOURCE = """ + record R(int a) { + } + class T { + void m() { + try { + m(); + } catch (IllegalStateException | IllegalArgumentException e) { + m(); + } + } + } + """; + + @TempDir + Path baseDir; + + private final JSema sema = new JSema(); + + @Test + void symbols_are_equal_by_id_else_by_name_and_owner() { + JTypeSymbol owner = sema.typeSymbol("p.A"); + JMethodSymbol first = new JMethodSymbol(sema, null, "m"); + first.owner(owner); + JMethodSymbol second = new JMethodSymbol(sema, null, "m"); + second.owner(owner); + JMethodSymbol elsewhere = new JMethodSymbol(sema, null, "m"); + JMethodSymbol identified = new JMethodSymbol(sema, "p.A#m()", "m"); + identified.owner(owner); + + assertThat(first).isEqualTo(first).isEqualTo(second).hasSameHashCodeAs(second).isNotEqualTo(elsewhere).isNotEqualTo("m"); + assertThat(identified).isEqualTo(new JMethodSymbol(sema, "p.A#m()", "other")).isNotEqualTo(new JVariableSymbol(sema, "p.A#m()", "m", "field")) + .isEqualTo(first) + .hasToString("p.A#m()"); + assertThat(first).hasToString("m"); + } + + @Test + void members_of_interfaces_get_implicit_modifiers() { + JTypeSymbol owner = type("p.I", sema.packageSymbol("p")); + owner.interfaceSymbol(true); + JVariableSymbol constant = new JVariableSymbol(sema, "p.I#C", "C", "field"); + constant.owner(owner); + JMethodSymbol method = method("p.I#m()", owner); + JMethodSymbol defaultMethod = method("p.I#d()", owner, "default"); + JMethodSymbol staticMethod = method("p.I#s()", owner, "static"); + JMethodSymbol privateMethod = method("p.I#p()", owner, "private"); + JTypeSymbol parameter = new JTypeSymbol(sema, "p.I", "T", true); + parameter.owner(owner); + + assertThat(constant.isStatic()).isTrue(); + assertThat(constant.isFinal()).isTrue(); + assertThat(constant.isPublic()).isTrue(); + assertThat(owner.isAbstract()).isFalse(); + assertThat(method.isAbstract()).isTrue(); + assertThat(defaultMethod.isAbstract()).isFalse(); + assertThat(staticMethod.isAbstract()).isFalse(); + assertThat(privateMethod.isAbstract()).isFalse(); + assertThat(privateMethod.isPublic()).isFalse(); + assertThat(parameter.isStatic()).isFalse(); + assertThat(parameter.isPublic()).isFalse(); + } + + @Test + void nested_interfaces_enums_and_records_are_static_but_not_top_level_or_inner_classes() { + JTypeSymbol outer = type("p.O", sema.packageSymbol("p")); + JTypeSymbol nestedInterface = type("p.O$I", outer); + nestedInterface.interfaceSymbol(true); + JTypeSymbol nestedEnum = type("p.O$E", outer); + nestedEnum.enumSymbol(true); + JTypeSymbol nestedRecord = type("p.O$R", outer); + sema.declare("p.O$R", unit().types().get(0)); + JTypeSymbol inner = type("p.O$C", outer); + sema.declare("p.O$C", unit().types().get(1)); + JTypeSymbol topLevelEnum = type("p.E", sema.packageSymbol("p")); + topLevelEnum.enumSymbol(true); + + assertThat(nestedInterface.isStatic()).isTrue(); + assertThat(nestedEnum.isStatic()).isTrue(); + assertThat(nestedRecord.isStatic()).isTrue(); + assertThat(inner.isStatic()).isFalse(); + assertThat(type("p.O$D", outer).isStatic()).isFalse(); + assertThat(topLevelEnum.isStatic()).isFalse(); + } + + @Test + void enum_constants_are_public_static_final_and_enum_constructors_private() { + JTypeSymbol owner = type("p.E", sema.packageSymbol("p")); + owner.enumSymbol(true); + JVariableSymbol constant = new JVariableSymbol(sema, "p.E#A", "A", "enum_member"); + constant.owner(owner); + JMethodSymbol constructor = method("p.E#()", owner); + JMethodSymbol plain = new JMethodSymbol(sema, "p.C#()", ""); + + assertThat(constant.isStatic()).isTrue(); + assertThat(constant.isFinal()).isTrue(); + assertThat(constant.isPublic()).isTrue(); + assertThat(new JMethodSymbol(sema, "p.E#()", "").isPrivate()).isFalse(); + assertThat(constructor.isPrivate()).isTrue(); + assertThat(method("p.E#values()", owner).isPrivate()).isFalse(); + assertThat(plain.isPrivate()).isFalse(); + } + + @Test + void accessors_of_record_components_are_public_and_receivers_have_no_visibility() { + JTypeSymbol recordType = type("p.R", sema.packageSymbol("p")); + sema.declare("p.R", unit().types().get(0)); + JTypeSymbol plain = type("p.C", sema.packageSymbol("p")); + sema.declare("p.C", unit().types().get(1)); + JVariableSymbol receiver = new JVariableSymbol(sema, "p.C#this", "this", "field"); + receiver.receiver(true); + + assertThat(method("p.R#a()", recordType).isPublic()).isTrue(); + assertThat(method("p.R#b()", recordType).isPublic()).isFalse(); + assertThat(method("p.C#a()", plain).isPublic()).isFalse(); + assertThat(method("p.D#a()", type("p.D", sema.packageSymbol("p"))).isPublic()).isFalse(); + JMethodSymbol declared = method("p.R#x()", recordType); + sema.declare("p.R#x()", ((ClassTree) unit().types().get(1)).members().get(0)); + assertThat(declared.isPublic()).isFalse(); + assertThat(receiver.isPackageVisibility()).isFalse(); + assertThat(new JVariableSymbol(sema, "p.C#f", "f", "field").isPackageVisibility()).isTrue(); + } + + @Test + void a_multi_catch_parameter_is_final() { + List catches = new ArrayList<>(); + unit().accept(new BaseTreeVisitor() { + @Override + public void visitCatch(CatchTree tree) { + catches.add(tree); + } + }); + JVariableSymbol parameter = new JVariableSymbol(sema, "e", "e", "local"); + sema.declare("e", catches.get(0).parameter()); + JVariableSymbol undeclared = new JVariableSymbol(sema, "f", "f", "local"); + + assertThat(parameter.isFinal()).isTrue(); + assertThat(undeclared.isFinal()).isFalse(); + } + + @Test + void enclosing_class_walks_up_to_the_first_type() { + JTypeSymbol top = type("p.A", sema.packageSymbol("p")); + JMethodSymbol method = method("p.A#m()", top); + JTypeSymbol local = type("p.A#m()$L", method); + JTypeSymbol nested = type("p.A$N", top); + JTypeSymbol methodParameter = new JTypeSymbol(sema, "p.A#m()", "T", true); + methodParameter.owner(method); + JTypeSymbol classParameter = new JTypeSymbol(sema, "p.A", "T", true); + classParameter.owner(top); + JVariableSymbol orphan = new JVariableSymbol(sema, "x", "x", "local"); + JVariableSymbol inPackage = new JVariableSymbol(sema, "y", "y", "local"); + inPackage.owner(sema.packageSymbol("p")); + JVariableSymbol inMethod = new JVariableSymbol(sema, "z", "z", "local"); + inMethod.owner(method); + + assertThat(top.enclosingClass()).isSameAs(top); + assertThat(local.enclosingClass()).isSameAs(top); + assertThat(nested.enclosingClass()).isSameAs(top); + assertThat(methodParameter.enclosingClass()).isNull(); + assertThat(classParameter.enclosingClass()).isSameAs(top); + assertThat(orphan.enclosingClass()).isNull(); + assertThat(inPackage.enclosingClass()).isNull(); + assertThat(inMethod.enclosingClass()).isSameAs(top); + } + + @Test + void usages_and_declaration_need_an_id() { + JVariableSymbol anonymous = new JVariableSymbol(sema, null, "x", "local"); + JVariableSymbol used = new JVariableSymbol(sema, "p.A#f", "f", "field"); + IdentifierTree use = identifier(); + sema.use("p.A#f", use); + + assertThat(anonymous.usages()).isEmpty(); + assertThat(anonymous.declaration()).isNull(); + assertThat(new JVariableSymbol(sema, "p.A#g", "g", "field").usages()).isEmpty(); + assertThat(used.usages()).containsExactly(use); + } + + private JTypeSymbol type(String id, Symbol owner) { + JTypeSymbol type = new JTypeSymbol(sema, id, id.substring(id.lastIndexOf('.') + 1), false); + type.owner(owner); + return type; + } + + private JMethodSymbol method(String id, Symbol owner, String... modifiers) { + JMethodSymbol method = new JMethodSymbol(sema, id, SemaFacts.memberName(id)); + method.owner(owner); + method.addModifiers(List.of(modifiers)); + return method; + } + + private IdentifierTree identifier() { + List found = new ArrayList<>(); + unit().accept(new BaseTreeVisitor() { + @Override + public void visitIdentifier(IdentifierTree tree) { + found.add(tree); + } + }); + return found.get(0); + } + + private CompilationUnitTree unit() { + try { + return (CompilationUnitTree) Replays.parseWithEcj(baseDir, "R", SOURCE).get(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeFixtures.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeFixtures.java new file mode 100644 index 00000000000..15c081c111e --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeFixtures.java @@ -0,0 +1,134 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Arrays; +import java.util.List; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; + +/** + * A semantic model holding the JDK types the replay recorded, plus types written as JSON by a test, with shortcuts to + * build types and find library methods. + */ +final class JTypeFixtures { + + private static final JsonObject JDK = loadJdk(); + + final JSema sema; + + JTypeFixtures(String... types) { + sema = new JSema(); + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(JDK.deepCopy()); + for (String json : types) { + sema.ingestTypes(json(json)); + } + } + + static JsonObject json(String json) { + return JsonParser.parseString(json).getAsJsonObject(); + } + + /** + * The type information of a classpath class {@code name}, as {@code {"name": {...}}}: a public class extending + * {@code Object} with no type parameters, unless {@code fields} (the inside of a JSON object) says otherwise. + */ + static String library(String name, String fields, String... members) { + JsonObject info = json(""" + {"origin": "classpath", "kind": "class", "modifiers": ["public"], "super": "java.lang.Object", "superType": {"id": "java.lang.Object", "args": []}, + "interfaces": [], "interfaceTypes": [], "typeParameters": 0, "typeVars": [], "typeVarBounds": []} + """); + json("{" + fields + "}").entrySet().forEach(entry -> info.add(entry.getKey(), entry.getValue())); + JsonArray array = new JsonArray(); + Arrays.stream(members).map(JTypeFixtures::json).forEach(array::add); + info.add("members", array); + JsonObject type = new JsonObject(); + type.add(name, info); + return type.toString(); + } + + /** A public instance method of a library class, with no parameters nor type variables unless {@code fields} says otherwise. */ + static String member(String name, String descriptor, String fields) { + JsonObject member = json(""" + {"k": "m", "vis": "public", "abstract": false, "final": false, "static": false, "synchronized": false, "varargs": false, "retSelf": false, + "throws": [], "paramTypes": [], "paramVars": [], "typeVars": []} + """); + member.addProperty("name", name); + member.addProperty("desc", descriptor); + json("{" + fields + "}").entrySet().forEach(entry -> member.add(entry.getKey(), entry.getValue())); + return member.toString(); + } + + /** The raw type {@code fqn}, or its parameterization with {@code arguments}. */ + JType type(String fqn, JType... arguments) { + return arguments.length == 0 ? (JType) sema.getClassType(fqn) : JType.named(sema, fqn, List.of(arguments)); + } + + /** The type a symbol fact such as {@code {"id": "java.util.List", "args": [...]}} describes. */ + JType fact(String json) { + return sema.factTypes().typeFromFact(json(json)); + } + + JType string() { + return type("java.lang.String"); + } + + JType object() { + return type("java.lang.Object"); + } + + JType integer() { + return type("java.lang.Integer"); + } + + JType primitive(String name) { + return sema.primitiveType(name); + } + + JType extending(JType bound) { + return JType.wildcard(sema, bound); + } + + JType capture(JType bound) { + return JType.capture(sema, bound); + } + + /** The method {@code name} of {@code owner} whose parameters erase to {@code parameters}. */ + JMethodSymbol method(String owner, String name, String... parameters) { + for (Symbol member : sema.getClassType(owner).symbol().lookupSymbols(name)) { + List erased = ((Symbol.MethodSymbol) member).parameterTypes().stream().map(Type::erasure).map(Type::fullyQualifiedName).toList(); + if (member instanceof JMethodSymbol method && erased.equals(Arrays.asList(parameters))) { + return method; + } + } + throw new IllegalArgumentException(owner + "#" + name + Arrays.toString(parameters)); + } + + private static JsonObject loadJdk() { + try { + return Replays.readJson(Replays.TYPES); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeSymbolTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeSymbolTest.java new file mode 100644 index 00000000000..f17c4c823e5 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeSymbolTest.java @@ -0,0 +1,204 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; + +import static org.assertj.core.api.Assertions.assertThat; + +class JTypeSymbolTest { + + private static final String TYPES = """ + { + "p.Base": {"kind": "class", "super": "java.lang.Object", "interfaces": []}, + "p.Iface": {"kind": "interface", "interfaces": []}, + "p.Anon": {"kind": "class", "super": "p.Iface", "interfaces": []}, + "p.AnonBoth": {"kind": "class", "super": "p.Iface", "interfaces": ["p.Iface"]}, + "p.Ann": {"kind": "annotation"}, + "p.CycA": {"kind": "class", "super": "p.CycB"}, + "p.CycB": {"kind": "class", "super": "p.CycA"}, + "p.Loop": {"kind": "class", "super": "p.CycA"}, + "p.Rec": {"kind": "class", "super": "p.Nowhere"}, + "p.En": {"kind": "enum"}, + "p.EnumSuper": {"kind": "enum", "super": "java.lang.Enum"}, + "p.Facts": {"kind": "class", "super": "java.lang.Object", "interfaces": ["java.io.Serializable", "java.lang.Cloneable"], + "interfaceTypes": [{"kind": "class"}, {"kind": "class", "id": {}}]}, + "p.Members": {"kind": "class", "super": "java.lang.Object", "members": [ + {"id": "p.Members#()"}, + {"id": "p.Members#a-b"}, + {"id": "p.Members#1x"}, + {"id": "p.Members#"}, + {"id": "p.Members#size"}, + {"name": "size", "k": "m", "desc": "()I"}, + {"name": "other", "k": "f", "desc": "I"}, + {"k": "m", "desc": "()V"}, + {"id": "p.Members", "facts": {"kind": "typeparameter"}} + ]} + } + """; + + @TempDir + Path baseDir; + + private JSema sema; + + @BeforeEach + void setUp() { + sema = new JSema(); + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(JsonParser.parseString(TYPES).getAsJsonObject()); + } + + @Test + void an_anonymous_class_recorded_with_an_interface_as_superclass_extends_object() { + Symbol.TypeSymbol anonymous = sema.typeSymbol("p.Anon"); + Symbol.TypeSymbol both = sema.typeSymbol("p.AnonBoth"); + + assertThat(anonymous.superClass().fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(anonymous.interfaces()).extracting(Type::fullyQualifiedName).containsExactly("p.Iface"); + assertThat(both.interfaces()).extracting(Type::fullyQualifiedName).containsExactly("p.Iface"); + } + + @Test + void enums_extend_enum_of_themselves() { + assertThat(describe(sema.typeSymbol("p.En").superClass())).isEqualTo("java.lang.Enum"); + assertThat(describe(sema.typeSymbol("p.EnumSuper").superClass())).isEqualTo("java.lang.Enum"); + } + + private static String describe(Type type) { + return type.fullyQualifiedName() + type.typeArguments().stream().map(Type::fullyQualifiedName).toList().toString().replace('[', '<').replace(']', '>'); + } + + @Test + void a_cyclic_hierarchy_falls_back_to_object() { + assertThat(sema.typeSymbol("p.CycA").superClass().fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(sema.typeSymbol("p.Loop").superClass().fullyQualifiedName()).isEqualTo("p.CycA"); + } + + @Test + void annotations_implement_annotation_and_facts_without_a_class_id_are_ignored() { + assertThat(sema.typeSymbol("p.Ann").interfaces()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.annotation.Annotation"); + assertThat(sema.typeSymbol("p.Ann").superClass().fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(sema.typeSymbol("p.Facts").interfaces()).extracting(Type::fullyQualifiedName).containsExactly("java.io.Serializable", "java.lang.Cloneable"); + } + + @Test + void a_diamond_on_the_named_supertype_parameterizes_it() { + JTypeSymbol anonymous = sema.typeSymbol("p.Base"); + JTypeSymbol child = new JTypeSymbol(sema, "p.Child", "Child", false); + child.superName("p.Base"); + JType parameterized = JType.named(sema, "p.Base", List.of((JType) sema.getClassType("java.lang.String"))); + child.declaredSupertype(parameterized); + JTypeSymbol implementer = new JTypeSymbol(sema, "p.Impl", "Impl", false); + implementer.interfaceNames(List.of("p.Iface")); + JType iface = JType.named(sema, "p.Iface", List.of((JType) sema.getClassType("java.lang.String"))); + implementer.declaredSupertype(iface); + + assertThat(anonymous.superClass().fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(child.superClass()).isSameAs(parameterized); + assertThat(implementer.interfaces()).containsExactly(iface); + } + + @Test + void undeclared_supertypes_are_kept_when_named_and_dropped_when_unknown() { + JTypeSymbol type = new JTypeSymbol(sema, "p.Partial", "Partial", false); + type.type(sema.rawNamed("p.Partial")); + type.declaredSupertypes(null, List.of(JType.unknown(sema), JType.unknown(sema))); + + assertThat(type.interfaces()).extracting(Type::fullyQualifiedName).containsExactly("!Unknown!"); + assertThat(type.superTypes()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.Object"); + assertThat(sema.typeSymbol("p.Rec").superTypes()).extracting(Type::fullyQualifiedName).containsExactly("p.Nowhere"); + assertThat(sema.typeSymbol("p.Missing").superTypes()).isEmpty(); + } + + @Test + void members_named_skip_type_parameters_and_facts_naming_another_member() { + JTypeSymbol members = sema.typeSymbol("p.Members"); + + assertThat(members.lookupSymbols("size")).extracting(Symbol::name).containsOnly("size"); + assertThat(members.lookupSymbols("size")).hasSize(2); + assertThat(members.lookupSymbols("other")).extracting(Symbol::isVariableSymbol).containsExactly(true); + assertThat(members.lookupSymbols("T")).isEmpty(); + assertThat(members.memberSymbols()).hasSize(8); + } + + @Test + void a_parameterized_view_shares_the_members_of_its_generic_type() { + JTypeSymbol members = sema.typeSymbol("p.Members"); + JTypeSymbol view = members.parameterizedAs(JType.named(sema, "p.Members", List.of((JType) sema.getClassType("java.lang.String")))); + + assertThat(view.memberSymbols()).isSameAs(members.memberSymbols()); + assertThat(view.lookupSymbols("other")).isEqualTo(members.lookupSymbols("other")); + assertThat(view.interfaces()).isEmpty(); + } + + @Test + void an_enum_of_this_file_has_a_default_constructor_values_and_value_of() throws Exception { + CompilationUnitTree unit = (CompilationUnitTree) Replays.parseWithEcj(baseDir, "En", "enum En { A }").get(); + sema.declare("p.En", unit.types().get(0)); + + List members = List.copyOf(sema.typeSymbol("p.En").memberSymbols()); + + assertThat(members).extracting(Symbol::name).containsExactly("", "values", "valueOf"); + assertThat(((Symbol.MethodSymbol) members.get(1)).returnType().type().fullyQualifiedName()).isEqualTo("p.En[]"); + assertThat(((Symbol.MethodSymbol) members.get(2)).parameterTypes()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.String"); + } + + @Test + void a_type_without_owner_is_its_own_outermost_class() { + JTypeSymbol orphan = new JTypeSymbol(sema, "x", "x", false); + + assertThat(orphan.outermostClass()).isSameAs(orphan); + assertThat(sema.typeSymbol("p.Base").outermostClass()).isSameAs(sema.typeSymbol("p.Base")); + } + + @Test + void type_hierarchy_caches_reuse_results_and_invalidate_on_late_ingestion() { + JType late = (JType) sema.getClassType("p.LateChild"); + JType base = (JType) sema.getClassType("p.Base"); + JType parameterized = JType.named(sema, "p.LateChild", List.of((JType) sema.getClassType("java.lang.String"))); + + assertThat(late.isUnknown()).isTrue(); + assertThat(late.isSubtypeOf(base)).isFalse(); + assertThat(parameterized.symbol()).isSameAs(parameterized.symbol()); + + sema.ingestTypes(JsonParser.parseString(""" + {"p.LateChild": {"kind": "class", "super": "p.Base", "interfaces": ["p.Iface"], "members": [ + {"k": "m", "name": "work", "desc": "()V"} + ]}} + """).getAsJsonObject()); + + JTypeSymbol symbol = sema.typeSymbol("p.LateChild"); + assertThat(late.isUnknown()).isFalse(); + assertThat(late.isSubtypeOf(base)).isTrue(); + assertThat(symbol.superClass()).isSameAs(symbol.superClass()); + assertThat(symbol.interfaces()).isSameAs(symbol.interfaces()); + assertThat(symbol.superTypes()).isSameAs(symbol.superTypes()); + assertThat(symbol.superTypes()).extracting(Type::fullyQualifiedName).contains("p.Base", "p.Iface"); + assertThat(parameterized.symbol().isUnknown()).isFalse(); + assertThat(sema.lookup().membersNamed("p.LateChild", "work")).hasSize(1); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeTest.java new file mode 100644 index 00000000000..ca6a0484cd8 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JTypeTest.java @@ -0,0 +1,153 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Type; + +import static org.assertj.core.api.Assertions.assertThat; + +class JTypeTest { + + private static final String LIST = "java.util.List"; + private static final String LIST_VARIABLE = "java.util.List`1"; + + private final JTypeFixtures fixtures = new JTypeFixtures(); + private final JSema sema = fixtures.sema; + private final JType variable = JType.typeVar(sema, "E", LIST_VARIABLE); + + @Test + void substitutes_inside_captures_wildcards_and_arrays() { + Map substitution = Map.of(LIST_VARIABLE, fixtures.string()); + + assertThat(fixtures.capture(variable).substitute(substitution).isCapture()).isTrue(); + assertThat(fixtures.capture(variable).substitute(substitution).erasure()).isEqualTo(fixtures.string()); + assertThat(JType.superWildcard(sema, variable).substitute(substitution).name()).isEqualTo("? super String"); + assertThat(fixtures.extending(variable).substitute(substitution).name()).isEqualTo("? extends String"); + assertThat(JType.array(sema, variable).substitute(substitution).name()).isEqualTo("String[]"); + } + + @Test + void substitution_naming_no_variable_keeps_the_same_instance() { + Map substitution = Map.of("other", fixtures.string()); + JType capture = fixtures.capture(variable); + JType lower = JType.superWildcard(sema, variable); + JType upper = fixtures.extending(variable); + JType array = JType.array(sema, variable); + JType list = fixtures.type(LIST, variable); + + assertThat(capture.substitute(substitution)).isSameAs(capture); + assertThat(lower.substitute(substitution)).isSameAs(lower); + assertThat(upper.substitute(substitution)).isSameAs(upper); + assertThat(array.substitute(substitution)).isSameAs(array); + assertThat(list.substitute(substitution)).isSameAs(list); + } + + @Test + void type_variable_without_id_is_substituted_by_name() { + JType anonymous = JType.typeVar(sema, "T", null); + + assertThat(anonymous.substitute(Map.of("T", fixtures.integer()))).isSameAs(fixtures.integer()); + assertThat(anonymous.erasure()).isSameAs(anonymous); + assertThat(fixtures.type(LIST, anonymous).isParameterized()).isTrue(); + } + + @Test + void wildcard_of_unknown_bound_is_unknown() { + JType unknown = JType.unknown(sema); + + assertThat(JType.wildcard(sema, unknown)).isSameAs(unknown); + } + + @Test + void wrapper_of_a_class_is_null() { + assertThat(fixtures.string().primitiveWrapperType()).isNull(); + assertThat(fixtures.primitive("int").primitiveWrapperType()).isEqualTo(fixtures.integer()); + assertThat(fixtures.integer().primitiveType()).isEqualTo(fixtures.primitive("int")); + } + + @Test + void declaring_type_of_a_raw_generic_type_names_its_parameters() { + Type declaring = fixtures.type(LIST).declaringType(); + + assertThat(declaring.typeArguments()).hasSize(1); + assertThat(declaring.typeArguments().get(0).isTypeVar()).isTrue(); + assertThat(fixtures.type(LIST, fixtures.string()).declaringType()).isEqualTo(fixtures.type(LIST)); + assertThat(fixtures.string().declaringType()).isEqualTo(fixtures.string()); + assertThat(JType.array(sema, fixtures.string()).declaringType().isArray()).isTrue(); + assertThat(JType.unknown(sema).declaringType().isUnknown()).isTrue(); + } + + @Test + void names_follow_the_source_spelling() { + assertThat(fixtures.extending(fixtures.object()).name()).isEqualTo("?"); + assertThat(fixtures.type("java.util.Map$Entry")).hasToString("Entry"); + assertThat(JType.named(sema, "Enums$1", List.of()).name()).isEmpty(); + assertThat(JType.nullType(sema).name()).isEqualTo(""); + } + + @Test + void intersection_lists_its_bounds() { + JType intersection = JType.intersection(sema, List.of(fixtures.type("java.lang.Number"), fixtures.type("java.lang.Comparable"))); + + assertThat(intersection.isIntersectionType()).isTrue(); + assertThat(intersection.getIntersectionTypes()).containsExactly(fixtures.type("java.lang.Number"), fixtures.type("java.lang.Comparable")); + assertThat(fixtures.string().isIntersectionType()).isFalse(); + assertThat(fixtures.string().getIntersectionTypes()).containsExactly(fixtures.string()); + } + + @Test + void captures_are_equal_only_to_themselves() { + JType capture = fixtures.capture(fixtures.string()); + + assertThat(capture).isEqualTo(capture).isNotEqualTo(fixtures.capture(fixtures.string())); + assertThat(fixtures.string()).isNotEqualTo("java.lang.String"); + } + + @Test + void wildcards_are_equal_when_their_bounds_are() { + JType upper = fixtures.extending(fixtures.string()); + + assertThat(upper).isEqualTo(fixtures.extending(fixtures.string())) + .isNotEqualTo(fixtures.extending(fixtures.integer())) + .isNotEqualTo(JType.superWildcard(sema, fixtures.string())) + .isNotEqualTo(fixtures.string()); + assertThat(fixtures.extending(fixtures.object())).isNotEqualTo(JType.superWildcard(sema, fixtures.string())); + } + + @Test + void arrays_and_parameterizations_are_equal_when_their_parts_are() { + assertThat(JType.array(sema, fixtures.string())).isEqualTo(JType.array(sema, fixtures.string())); + assertThat(JType.array(sema, fixtures.type(LIST, fixtures.string()))).isNotEqualTo(JType.array(sema, fixtures.type(LIST, fixtures.integer()))); + assertThat(fixtures.type(LIST, fixtures.string())).isEqualTo(fixtures.type(LIST, fixtures.string())) + .isNotEqualTo(fixtures.type(LIST, fixtures.integer())) + .isNotEqualTo(fixtures.type(LIST)); + assertThat(fixtures.primitive("int")).isNotEqualTo(fixtures.integer()); + } + + @Test + void type_variable_named_simply_is_the_one_its_declaration_spells_in_full() { + JType simple = JType.typeVar(sema, "E", "E"); + JType other = JType.typeVar(sema, "E", "java.util.Set`1"); + + assertThat(simple).isEqualTo(variable); + assertThat(variable).isEqualTo(simple).isNotEqualTo(other).isNotEqualTo(JType.typeVar(sema, "E", null)); + assertThat(JType.typeVar(sema, "E", null)).isNotEqualTo(variable); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JVariableSymbolTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JVariableSymbolTest.java new file mode 100644 index 00000000000..631d431bf60 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JVariableSymbolTest.java @@ -0,0 +1,146 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.SymbolMetadata; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; +import org.sonar.plugins.java.api.tree.VariableTree; + +import static org.assertj.core.api.Assertions.assertThat; + +class JVariableSymbolTest { + + private static final String SOURCE = """ + class C { + static final long L = 1_000L; + static final float F = 1.5f; + static final double D = 2.5; + static final int I = 1 + 2; + static final long WIDE = 5; + static final double DOUBLE = 1; + static final float FLOAT = 2; + static final Integer BOXED = 3; + static final String S = "s"; + static final int NONE; + final int instance = 4; + static int mutable = 6; + } + """; + + @TempDir + Path baseDir; + + @Test + void constants_of_declared_fields_are_typed_as_their_declaration() throws Exception { + JSema sema = new JSema(); + List fields = fields(); + + assertThat(constant(sema, fields, "L", "static", "final")).contains(1000L); + assertThat(constant(sema, fields, "F", "static", "final")).contains(1.5f); + assertThat(constant(sema, fields, "D", "static", "final")).contains(2.5); + assertThat(constant(sema, fields, "I", "static", "final")).contains(3); + assertThat(constant(sema, fields, "WIDE", "static", "final")).contains(5L); + assertThat(constant(sema, fields, "DOUBLE", "static", "final")).contains(1.0); + assertThat(constant(sema, fields, "FLOAT", "static", "final")).contains(2.0f); + assertThat(constant(sema, fields, "S", "static", "final")).contains("s"); + } + + @Test + void boxed_uninitialized_instance_and_mutable_fields_are_not_constants() throws Exception { + JSema sema = new JSema(); + List fields = fields(); + + assertThat(constant(sema, fields, "BOXED", "static", "final")).isEmpty(); + assertThat(constant(sema, fields, "NONE", "static", "final")).isEmpty(); + assertThat(constant(sema, fields, "instance", "final")).isEmpty(); + assertThat(constant(sema, fields, "mutable", "static")).isEmpty(); + assertThat(new JVariableSymbol(sema, null, "x", "field").constantValue()).isEmpty(); + } + + @Test + void a_given_constant_value_is_kept() { + JVariableSymbol field = new JVariableSymbol(new JSema(), "C#X", "X", "field"); + field.constantValue(7); + + assertThat(field.constantValue()).contains(7); + } + + @Test + void variables_owned_by_a_method_are_local() { + JSema sema = new JSema(); + JVariableSymbol variable = new JVariableSymbol(sema, "C#m()#v", "v", "field"); + variable.owner(new JMethodSymbol(sema, "C#m()", "m")); + JVariableSymbol parameter = new JVariableSymbol(sema, "C#m()#p", "p", "param"); + + assertThat(variable.isLocalVariable()).isTrue(); + assertThat(variable.isParameter()).isFalse(); + assertThat(parameter.isParameter()).isTrue(); + assertThat(new JVariableSymbol(sema, "C#f", "f", "field").isLocalVariable()).isFalse(); + } + + @Test + void parameter_placeholder_of_an_undeclared_method_carries_nothing_but_its_type() { + JSema sema = new JSema(); + JTypeSymbol owner = sema.typeSymbol("p.C"); + JMethodSymbol method = new JMethodSymbol(sema, null, "m"); + method.owner(owner); + Symbol.VariableSymbol placeholder = (Symbol.VariableSymbol) sema.factTypes().parameterPlaceholder(method, 0, sema.primitiveType("int")); + + assertThat(placeholder.name()).isEqualTo("arg0"); + assertThat(placeholder.owner()).isSameAs(method); + assertThat(placeholder.type().fullyQualifiedName()).isEqualTo("int"); + assertThat(placeholder.isUnknown()).isFalse(); + assertThat(placeholder.enclosingClass()).isEqualTo(owner); + assertThat(placeholder.usages()).isEmpty(); + assertThat(placeholder.declaration()).isNull(); + assertThat(placeholder.isEffectivelyFinal()).isFalse(); + assertThat(placeholder.constantValue()).isEmpty(); + assertThat(placeholder.isLocalVariable()).isFalse(); + assertThat(placeholder.isParameter()).isTrue(); + assertThat(placeholder.isVariableSymbol()).isTrue(); + assertThat(placeholder.isFinal()).isFalse(); + + SymbolMetadata metadata = placeholder.metadata(); + assertThat(metadata.isAnnotatedWith("java.lang.Deprecated")).isFalse(); + assertThat(metadata.valuesForAnnotation("java.lang.Deprecated")).isNull(); + assertThat(metadata.annotations()).isEmpty(); + assertThat(metadata.symbolAnnotations()).isEmpty(); + assertThat(metadata.nullabilityData().isNonNull(SymbolMetadata.NullabilityLevel.PACKAGE, false, false)).isFalse(); + assertThat(metadata.nullabilityData(SymbolMetadata.NullabilityTarget.PARAMETER).isNullable(SymbolMetadata.NullabilityLevel.PACKAGE, false, false)).isFalse(); + assertThat(metadata.findAnnotationTree(null)).isNull(); + assertThat(metadata.parametersMetadata()).isEmpty(); + } + + private Optional constant(JSema sema, List fields, String name, String... modifiers) { + JVariableSymbol field = new JVariableSymbol(sema, "C#" + name, name, "field"); + field.addModifiers(List.of(modifiers)); + sema.declare("C#" + name, fields.stream().filter(tree -> tree.simpleName().name().equals(name)).findFirst().orElseThrow()); + return field.constantValue(); + } + + private List fields() throws Exception { + CompilationUnitTree unit = (CompilationUnitTree) Replays.parseWithEcj(baseDir, "C", SOURCE).get(); + return ((ClassTree) unit.types().get(0)).members().stream().map(VariableTree.class::cast).toList(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/LibraryMembersTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/LibraryMembersTest.java new file mode 100644 index 00000000000..8400516e096 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/LibraryMembersTest.java @@ -0,0 +1,229 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactEntry; +import org.sonarsource.semsitter.wire.FactValue; + +import static org.assertj.core.api.Assertions.assertThat; + +class LibraryMembersTest { + + private final JSema sema = new JSema(); + private final LibraryMembers members = sema.libraryMembers(); + + @Test + void thrown_types_are_only_known_for_answered_project_members() { + served(""" + {"q.B": {"origin": "project", "kind": "class", "members": [ + {"id": null}, {"name": "noId"}, + {"id": "q.B#t()", "throws": ["java.io.IOException"], "varargs": "yes", "facts": {"kind": "method"}}, + {"id": "q.B#g", "declaredType": {"kind": "typevar", "id": "q.B"}, "facts": {"kind": "field", "type": ["T"]}} + ]}, + "q.L": {"origin": "library", "kind": "class", "members": [{"id": "q.L#t()", "throws": ["java.lang.Exception"]}]}, + "q.N": {"origin": "project", "kind": "class"}} + """); + + assertThat(members.projectThrown(null)).isNull(); + assertThat(members.projectThrown("q.B#none()")).isNull(); + assertThat(members.projectThrown("q.L#t()")).isNull(); + assertThat(members.projectThrown("q.B#t()")).extracting(Type::fullyQualifiedName).containsExactly("java.io.IOException"); + assertThat(sema.declaredMembers.projectVarArgs).doesNotContainKey("q.B#t()"); + assertThat(sema.declaredMembers.projectFieldTypes).containsKey("q.B#g"); + } + + @Test + void project_members_get_their_served_constant_only_when_undeclared() { + served(""" + {"q.C": {"origin": "project", "kind": "class", "members": [ + {"id": "q.C#K", "constant": "42", "facts": {"kind": "field", "type": ["int"]}}, + {"id": "q.C#m()", "constant": "1", "facts": {"kind": "method"}}, + {"id": "q.C#N", "facts": {"kind": "field", "type": ["int"]}} + ]}} + """); + JTypeSymbol owner = sema.typeSymbol("q.C"); + + assertThat(((JVariableSymbol) members.memberFromTypeInfo(owner, json("{\"id\": \"q.C#K\", \"constant\": \"42\"}"))).constantValue()).contains(42); + assertThat(members.memberFromTypeInfo(owner, json("{\"id\": \"q.C#m()\", \"constant\": \"1\"}")).isMethodSymbol()).isTrue(); + assertThat(((JVariableSymbol) members.memberFromTypeInfo(owner, json("{\"id\": \"q.C#N\"}"))).constantValue()).isEmpty(); + assertThat(members.servedConstant((JVariableSymbol) sema.resolve("q.C#K"))).isEqualTo(42); + assertThat(members.servedConstant((JVariableSymbol) sema.resolve("q.C#N"))).isNull(); + assertThat(members.servedConstant(new JVariableSymbol(sema, null, "x", "field"))).isNull(); + assertThat(members.servedConstant(new JVariableSymbol(sema, "local", "x", "local"))).isNull(); + assertThat(members.servedConstant(new JVariableSymbol(sema, "q.Undeclared#x", "x", "field"))).isNull(); + } + + @Test + void served_constant_needs_a_member_list() { + served("{\"q.E\": {\"origin\": \"project\", \"kind\": \"class\"}}"); + + assertThat(members.servedConstant(new JVariableSymbol(sema, "q.E#x", "x", "field"))).isNull(); + } + + @Test + void classpath_members_read_descriptors_flags_and_return_types() { + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(json("{\"lib.I\": {\"kind\": \"interface\"}}")); + JTypeSymbol iface = sema.typeSymbol("lib.I"); + JTypeSymbol anonymous = new JTypeSymbol(sema, null, "Anon", false); + + JVariableSymbol untyped = (JVariableSymbol) members.memberFromTypeInfo(anonymous, json("{\"k\": \"f\"}")); + assertThat(untyped.id).isEqualTo("Anon#null"); + assertThat(untyped.name()).isEmpty(); + assertThat(members.memberFromTypeInfo(anonymous, json("{\"k\": \"f\"}"))).isSameAs(untyped); + + JMethodSymbol nameless = (JMethodSymbol) members.memberFromTypeInfo(iface, json("{\"desc\": \"V\", \"vis\": \"private\", \"retParam\": null, \"default\": {}}")); + assertThat(nameless.name()).isEmpty(); + assertThat(nameless.hasModifier("default")).isFalse(); + assertThat(nameless.parameterTypes()).isEmpty(); + + JMethodSymbol defaulted = (JMethodSymbol) members.memberFromTypeInfo(iface, json(""" + {"name": "d", "desc": "()Ljava/util/List;", "varargs": [], + "retType": {"kind": "class", "id": "java.util.List", "args": [{"kind": "wildcard"}]}} + """)); + assertThat(defaulted.hasModifier("default")).isTrue(); + assertThat(defaulted.isVarArgsMethod()).isFalse(); + assertThat(defaulted.returnType().type().isParameterized()).isFalse(); + + JMethodSymbol unknownReturn = (JMethodSymbol) members.memberFromTypeInfo(iface, json(""" + {"name": "u", "desc": "()Ljava/lang/Object;", "abstract": true, + "retType": {"kind": "class", "id": "lib.Missing", "args": [{"kind": "class", "id": "java.lang.String"}]}} + """)); + assertThat(unknownReturn.returnType().type().fullyQualifiedName()).isEqualTo("java.lang.Object"); + + JMethodSymbol staticReturn = (JMethodSymbol) members.memberFromTypeInfo(iface, json(""" + {"name": "s", "desc": "()Ljava/util/List;", "static": true, + "retType": {"kind": "class", "id": "java.util.List", "args": [{"kind": "class", "id": "java.lang.String"}]}} + """)); + assertThat(staticReturn.hasModifier("default")).isFalse(); + assertThat(staticReturn.returnType().type().isParameterized()).isFalse(); + + JMethodSymbol plainReturn = (JMethodSymbol) members.memberFromTypeInfo(iface, json(""" + {"name": "p", "desc": "()Ljava/util/List;", "abstract": true, "retType": {"kind": "class", "id": "java.util.List"}} + """)); + assertThat(plainReturn.returnType().type().isParameterized()).isFalse(); + } + + @Test + void dump_symbols_already_created_are_kept() { + sema.symbols.put("p.A#f", new JVariableSymbol(sema, "p.A#f", "kept", "field")); + sema.ingestDocument(Document.newBuilder() + .addSymbols(symbol("p.A#f", "field", "f", "p.A")) + .addSymbols(symbol("p.A#l", "label", "l", "p.A")) + .build()); + + assertThat(sema.symbols.get("p.A#f").name()).isEqualTo("kept"); + assertThat(sema.symbols).doesNotContainKey("p.A#l"); + } + + @Test + void dump_members_without_owner_fall_back_to_their_fact_parent() { + sema.ingestDocument(Document.newBuilder() + .addFacts(fact("p.A#m()", Fact.newBuilder().setKind("method").setParent("p.A"))) + .addFacts(fact("p.A#f", Fact.newBuilder().setKind("field").setParent("p.Outer").setTier("IN_PROJECT").addType("long"))) + .addFacts(fact("p.A#g", Fact.newBuilder().setKind("field").addType("java.lang.String"))) + .addFacts(fact("p.A#h", Fact.newBuilder().setKind("field").addType("int").addType("long"))) + .addSymbols(symbol("p.A", "type", "A", "")) + .addSymbols(org.sonarsource.semsitter.wire.Symbol.newBuilder().setId("p.A#m()").setKind("method").setName("m")) + .addSymbols(symbol("p.A#f", "field", "f", "p.Missing")) + .addSymbols(symbol("p.A#g", "field", "g", "p.A")) + .addSymbols(symbol("p.A#h", "field", "h", "p.A")) + .addSymbols(symbol("m", "method", "m", "p.A")) + .build()); + + assertThat(sema.resolve("p.A#m()").owner().name()).isEqualTo("A"); + assertThat(sema.resolve("p.A#f").owner().name()).isEqualTo("Outer"); + assertThat(sema.resolve("p.A#f").type().fullyQualifiedName()).isEqualTo("long"); + assertThat(sema.resolve("p.A#g").type().isUnknown()).isTrue(); + assertThat(sema.resolve("p.A#h").type().isUnknown()).isTrue(); + } + + @Test + void implicit_enum_methods_need_an_owner_and_the_right_signature() { + FactValue implicit = FactValue.newBuilder().setFlag(true).build(); + sema.ingestDocument(Document.newBuilder() + .addSymbols(symbol("p.E", "type", "E", "")) + .addSymbols(org.sonarsource.semsitter.wire.Symbol.newBuilder().setId("p.E#values()").setKind("method").setName("values").putFacts("implicit", implicit)) + .addSymbols(symbol("p.E#values(int)", "method", "values", "p.E").putFacts("implicit", implicit)) + .addSymbols(symbol("p.E#valueOf(int)", "method", "valueOf", "p.E").putFacts("implicit", implicit)) + .addSymbols(symbol("p.E#other()", "method", "other", "p.E").putFacts("implicit", implicit)) + .addSymbols(symbol("p.E#valueOf(java.lang.String)", "method", "valueOf", "p.E").putFacts("implicit", implicit)) + .build()); + + assertThat(((Symbol.MethodSymbol) sema.resolve("p.E#values()")).isStatic()).isFalse(); + assertThat(((Symbol.MethodSymbol) sema.resolve("p.E#values(int)")).isStatic()).isFalse(); + assertThat(((Symbol.MethodSymbol) sema.resolve("p.E#valueOf(int)")).isStatic()).isFalse(); + assertThat(((Symbol.MethodSymbol) sema.resolve("p.E#other()")).isStatic()).isFalse(); + Symbol.MethodSymbol valueOf = (Symbol.MethodSymbol) sema.resolve("p.E#valueOf(java.lang.String)"); + assertThat(valueOf.isStatic()).isTrue(); + assertThat(valueOf.returnType().type().fullyQualifiedName()).isEqualTo("p.E"); + } + + @Test + void library_members_named_by_the_dump_take_served_flags() { + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(json(""" + {"lib.L": {"kind": "class", "members": [ + {"k": "m", "name": "m", "desc": "(I)V", "static": true, "throws": ["java.io.IOException"], "varargs": true}, + {"k": "m", "name": "n", "desc": "(I)V", "varargs": "maybe"}, + {"k": "f", "name": "f", "desc": "I", "static": true, "throws": ["java.io.IOException"]}, + {"id": "lib.L#p(int)", "facts": {"kind": "method"}} + ]}} + """)); + sema.ingestDocument(Document.newBuilder() + .addSymbols(symbol("lib.L#m(int)", "method", "m", "lib.L")) + .addSymbols(symbol("lib.L#n(int)", "method", "n", "lib.L")) + .addSymbols(symbol("lib.L#f", "field", "f", "lib.L")) + .addSymbols(symbol("lib.L#p(int)", "method", "p", "lib.L")) + .addSymbols(symbol("lib.L#q(1)", "method", "q", "lib.L")) + .addSymbols(symbol("array#clone()", "method", "clone", "array")) + .build()); + + Symbol.MethodSymbol m = (Symbol.MethodSymbol) sema.resolve("lib.L#m(int)"); + assertThat(m.isStatic()).isTrue(); + assertThat(m.isVarArgsMethod()).isTrue(); + assertThat(m.thrownTypes()).extracting(Type::fullyQualifiedName).containsExactly("java.io.IOException"); + assertThat(((Symbol.MethodSymbol) sema.resolve("lib.L#n(int)")).thrownTypes()).isEmpty(); + assertThat(sema.resolve("lib.L#f").isStatic()).isTrue(); + assertThat(sema.resolve("lib.L#p(int)").isStatic()).isFalse(); + assertThat(sema.resolve("lib.L#q(1)").isStatic()).isFalse(); + } + + private void served(String answer) { + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(json(answer)); + } + + private static org.sonarsource.semsitter.wire.Symbol.Builder symbol(String id, String kind, String name, String owner) { + return org.sonarsource.semsitter.wire.Symbol.newBuilder().setId(id).setKind(kind).setName(name).setOwner(owner); + } + + private static FactEntry fact(String key, Fact.Builder fact) { + return FactEntry.newBuilder().setKey(key).setValue(fact).build(); + } + + private static JsonObject json(String text) { + return JsonParser.parseString(text).getAsJsonObject(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/MemberFactoryTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/MemberFactoryTest.java new file mode 100644 index 00000000000..0cd5f598dc0 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/MemberFactoryTest.java @@ -0,0 +1,203 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; +import org.sonar.plugins.java.api.tree.TypeParameterTree; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactEntry; +import org.sonarsource.semsitter.wire.Prop; + +import static org.assertj.core.api.Assertions.assertThat; + +class MemberFactoryTest { + + @TempDir + Path baseDir; + + private final JSema sema = new JSema(); + private final MemberFactory factory = sema.memberFactory(); + + @Test + void type_variable_bounds_are_the_declared_ones_or_object() throws Exception { + CompilationUnitTree unit = (CompilationUnitTree) Replays.parseWithEcj(baseDir, "G", "class G, U extends Missing, V> {}").get(); + List parameters = ((ClassTree) unit.types().get(0)).typeParameters(); + bounded("p.G", parameters.get(0)); + bounded("p.G", parameters.get(1)); + bounded("p.G", parameters.get(2)); + + assertThat(factory.typeVariableBound("p.G").fullyQualifiedName()).isEqualTo("java.lang.Number"); + assertThat(factory.typeVariableBounds("p.G")).extracting(Type::fullyQualifiedName).containsExactly("java.lang.Number", "java.lang.Comparable"); + assertThat(factory.typeVariableBound("p.G").fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(factory.typeVariableBound("p.G").fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(factory.typeVariableBounds("p.G")).extracting(Type::fullyQualifiedName).containsExactly("java.lang.Object"); + assertThat(factory.typeVariableBound(null).fullyQualifiedName()).isEqualTo("java.lang.Object"); + assertThat(factory.typeVariableBounds(null)).extracting(Type::fullyQualifiedName).containsExactly("java.lang.Object"); + assertThat(factory.typeVariableBound("p.G#f").fullyQualifiedName()).isEqualTo("java.lang.Object"); + } + + @Test + void type_parameters_are_named_after_their_id() { + assertThat(sema.resolve("p.A").name()).isEqualTo("T"); + assertThat(factory.typeParameter("p.A { + if (names.contains("p.A")) { + reentrant[0] = sema.resolve("p.A#m()"); + } + return new JsonObject(); + }); + + sema.resolve("p.A#m()"); + + assertThat(reentrant[0]).isSameAs(sema.unknownSymbol); + assertThat(sema.resolve("array#clone()").isMethodSymbol()).isTrue(); + } + + @Test + void local_and_anonymous_classes_are_owned_by_their_method() { + JSema withFacts = sema(Document.newBuilder() + .addFacts(fact("p.C#f()$Local", Fact.newBuilder().setKind("class").addProps(Prop.newBuilder().setName("modifiers").addValues("final")))) + .build()); + + Symbol.TypeSymbol local = (Symbol.TypeSymbol) withFacts.resolve("p.C#f()$Local"); + Symbol.TypeSymbol anonymous = (Symbol.TypeSymbol) withFacts.resolve("p.C#f()$Local$1"); + + assertThat(local.name()).isEqualTo("Local"); + assertThat(local.isFinal()).isTrue(); + assertThat(local.owner().name()).isEqualTo("f"); + assertThat(anonymous.name()).isEmpty(); + assertThat(anonymous.owner()).isSameAs(local); + } + + @Test + void enum_constants_without_a_type_fact_are_of_their_enum() { + JSema withFacts = sema(Document.newBuilder() + .addFacts(fact("p.E", Fact.newBuilder().setKind("enum").setParent("p::"))) + .addFacts(fact("p.E#A", Fact.newBuilder().setKind("enum_member"))) + .addFacts(fact("p.E#B", Fact.newBuilder().setKind("enum"))) + .addSymbols(org.sonarsource.semsitter.wire.Symbol.newBuilder().setId("p.E").setKind("type").setName("E")) + .build()); + + Symbol constant = withFacts.resolve("p.E#A"); + Symbol other = withFacts.resolve("p.E#B"); + + assertThat(constant.type().fullyQualifiedName()).isEqualTo("p.E"); + assertThat(constant.isEnum()).isTrue(); + assertThat(constant.isStatic()).isTrue(); + assertThat(constant.isPublic()).isTrue(); + assertThat(other.isFinal()).isTrue(); + assertThat(withFacts.resolve("p.E#none").isUnknown()).isTrue(); + } + + @Test + void project_members_take_served_declared_types_aliases_and_variable_arity() { + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(json(""" + {"q.B": {"origin": "project", "kind": "class", "members": [ + {"id": "q.B#list", "facts": {"kind": "field", "type": ["java.util.List"]}, + "declaredType": {"kind": "class", "id": "java.util.List", "args": [{"kind": "class", "id": "java.lang.String"}]}}, + {"id": "q.B#old", "useIds": ["q.B#alias"], "facts": {"kind": "field", "type": ["int"]}, "annotations": [{"name": "java.lang.Deprecated"}]}, + {"id": "q.B#v(int[])", "useIds": ["q.B#w(int[])"], "varargs": false, "facts": {"kind": "method", "params": ["int[]"]}}, + {"id": "q.B#p(int,int)", "useIds": ["q.B#r(2)", "q.B#s(long)"], "facts": {"kind": "method", "params": ["int", "int"], + "props": {"param_types": ["int", "int..."]}}} + ]}} + """)); + + assertThat(sema.resolve("q.B#list").type().typeArguments()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.String"); + assertThat(sema.resolve("q.B#alias").isDeprecated()).isTrue(); + assertThat(sema.resolve("q.B#alias").type().fullyQualifiedName()).isEqualTo("int"); + assertThat(((Symbol.MethodSymbol) sema.resolve("q.B#w(int[])")).isVarArgsMethod()).isFalse(); + Symbol.MethodSymbol arity = (Symbol.MethodSymbol) sema.resolve("q.B#r(2)"); + assertThat(arity.isUnknown()).isTrue(); + assertThat(arity.parameterTypes()).hasSize(2); + Symbol.MethodSymbol mismatched = (Symbol.MethodSymbol) sema.resolve("q.B#s(long)"); + assertThat(mismatched.parameterTypes()).extracting(Type::fullyQualifiedName).containsExactly("long"); + assertThat(mismatched.isVarArgsMethod()).isTrue(); + } + + @Test + void type_facts_give_kinds_supertypes_and_implicit_modifiers() { + JSema withFacts = sema(Document.newBuilder() + .addFacts(fact("p.O", Fact.newBuilder().setKind("class").setParent("p::"))) + .addFacts(fact("p.O$I", Fact.newBuilder().setKind("interface").setParent("p.O").addImplements("p.J"))) + .addFacts(fact("p.O$M", Fact.newBuilder().setKind("method").setParent("p.O"))) + .addFacts(fact("p.O$M$R", Fact.newBuilder().setKind("record").setParent("p.O$M"))) + .addFacts(fact("p.O$N", Fact.newBuilder().setKind("enum").setParent("p.Nowhere"))) + .addFacts(fact("p.X", Fact.newBuilder().setKind("class").addExtends("java.lang.Enum`1"))) + .addSymbols(type("p.O")).addSymbols(type("p.O$I")).addSymbols(type("p.O$M$R")).addSymbols(type("p.O$N")).addSymbols(type("p.X")) + .build()); + + Symbol.TypeSymbol nestedInterface = (Symbol.TypeSymbol) withFacts.resolve("p.O$I"); + assertThat(nestedInterface.isStatic()).isTrue(); + assertThat(nestedInterface.interfaces()).extracting(Type::fullyQualifiedName).containsExactly("p.J"); + assertThat(((JTypeSymbol) withFacts.resolve("p.O$M$R")).hasModifier("static")).isFalse(); + assertThat(((JTypeSymbol) withFacts.resolve("p.O$M$R")).hasModifier("final")).isTrue(); + assertThat(((JTypeSymbol) withFacts.resolve("p.O$N")).hasModifier("static")).isFalse(); + assertThat(withFacts.resolve("p.X").isEnum()).isTrue(); + } + + @Test + void type_information_reads_interface_supertypes_and_type_parameter_counts() { + JTypeSymbol anonymous = new JTypeSymbol(sema, null, "Anonymous", false); + factory.applyTypeInfo(anonymous, json("{\"kind\": \"interface\", \"super\": [\"java.lang.Runnable\"], \"typeParameters\": null}")); + JTypeSymbol generic = sema.typeSymbol("p.Gen"); + factory.applyTypeInfo(generic, json("{\"kind\": \"class\", \"super\": \"java.lang.Enum\", \"typeParameters\": 2}")); + + assertThat(anonymous.isInterface()).isTrue(); + assertThat(anonymous.interfaces()).extracting(Type::fullyQualifiedName).containsExactly("java.lang.Runnable"); + assertThat(anonymous.typeParameterCount()).isZero(); + assertThat(generic.isEnum()).isTrue(); + assertThat(generic.typeParameterCount()).isEqualTo(2); + } + + private void bounded(String id, TypeParameterTree tree) { + ((JTypeSymbol) factory.typeParameter(id)).boundTrees(tree.bounds()); + } + + private static JSema sema(Document document) { + JSema sema = new JSema(); + sema.ingestDocument(document); + return sema; + } + + private static org.sonarsource.semsitter.wire.Symbol.Builder type(String id) { + return org.sonarsource.semsitter.wire.Symbol.newBuilder().setId(id).setKind("type").setName(SemaFacts.simpleName(id)); + } + + private static FactEntry fact(String key, Fact.Builder fact) { + return FactEntry.newBuilder().setKey(key).setValue(fact).build(); + } + + private static JsonObject json(String text) { + return JsonParser.parseString(text).getAsJsonObject(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/MemberLookupTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/MemberLookupTest.java new file mode 100644 index 00000000000..972727d19b3 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/MemberLookupTest.java @@ -0,0 +1,115 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.HashSet; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Symbol; + +import static org.assertj.core.api.Assertions.assertThat; + +class MemberLookupTest { + + private static final String TYPES = """ + { + "lib.Calls": {"kind": "class", "super": "lib.Parent", "interfaces": [], "members": [ + {"k": "m", "name": "take", "desc": "(Ljava/lang/String;)V"}, + {"k": "m", "name": "two", "desc": "(I)V"}, + {"k": "m", "name": "two", "desc": "(J)V"}, + {"k": "m", "name": "spread", "desc": "([Ljava/lang/String;)V", "varargs": true}, + {"k": "m", "name": "gen", "desc": "(Ljava/util/List;)V"}, + {"k": "f", "name": "own", "desc": "I"}, + {"k": "m", "name": "nodesc"}, + {"k": "f", "name": "take", "desc": "I"} + ]}, + "lib.Parent": {"kind": "class", "super": "lib.Ghost", "interfaces": [], "members": [ + {"k": "f", "name": "inherited", "desc": "I"}, + {"k": "m", "name": "fromParent", "desc": "()V"} + ]}, + "lib.Proj": {"origin": "project", "kind": "class", "members": [ + {"id": "lib.Proj#count", "facts": {"kind": "field", "type": ["int"]}}, + {"id": "lib.Proj#ghost"}, + {"id": "lib.Proj#run(int)", "facts": {"kind": "method", "params": ["int"]}} + ]}, + "java.lang.String": {"kind": "class", "super": "java.lang.Object"}, + "java.lang.Object": {"kind": "class"} + } + """; + + private JSema sema; + private MemberLookup lookup; + + @BeforeEach + void setUp() { + sema = new JSema(); + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(JsonParser.parseString(TYPES).getAsJsonObject()); + lookup = sema.lookup(); + } + + @Test + void enum_constants_are_created_once_with_their_enum_as_type() { + Symbol.VariableSymbol constant = lookup.enumConstant("lib.E", "A"); + Symbol.VariableSymbol ownerless = lookup.enumConstant(" ", "B"); + + assertThat(lookup.enumConstant("lib.E", null)).isNull(); + assertThat(lookup.enumConstant("lib.E", "A")).isSameAs(constant); + assertThat(constant.type().fullyQualifiedName()).isEqualTo("lib.E"); + assertThat(constant.isStatic()).isTrue(); + assertThat(ownerless.owner()).isSameAs(Symbol.UNKNOWN_SYMBOL); + assertThat(lookup.enumConstant(null, "B")).isSameAs(ownerless); + } + + @Test + void members_match_by_kind_descriptor_and_erased_parameter_types() { + assertThat(find("lib.Calls", "lib.Calls#take", MemberLookup.Match.ARITY).get("k").getAsString()).isEqualTo("f"); + assertThat(find("lib.Calls", "lib.Calls#nodesc()", MemberLookup.Match.ARITY)).isNull(); + assertThat(find("lib.Calls", "lib.Calls#spread(java.lang.String,java.lang.String)", MemberLookup.Match.TYPED)).isNull(); + assertThat(find("lib.Calls", "lib.Calls#spread(java.lang.String,java.lang.String)", MemberLookup.Match.VARARGS)).isNotNull(); + assertThat(find("lib.Calls", "lib.Calls#take()", MemberLookup.Match.VARARGS)).isNull(); + assertThat(find("lib.Calls", "lib.Calls#gen(java.util.List>)", MemberLookup.Match.TYPED)).isNotNull(); + assertThat(find("lib.Calls", "lib.Calls#take(int)", MemberLookup.Match.TYPED)).isNull(); + assertThat(find("lib.Calls", "lib.Calls#fromParent()", MemberLookup.Match.TYPED)).isNotNull(); + assertThat(find("lib.Calls", "lib.Calls#()", MemberLookup.Match.TYPED)).isNull(); + assertThat(find("lib.Proj", "lib.Proj#run(1)", MemberLookup.Match.ARITY)).isNotNull(); + assertThat(find("lib.Proj", "lib.Proj#run(long)", MemberLookup.Match.TYPED)).isNull(); + assertThat(find("lib.Proj", "lib.Proj#run()", MemberLookup.Match.ARITY)).isNull(); + } + + private JsonObject find(String owner, String id, MemberLookup.Match match) { + return lookup.findMember(owner, SemaFacts.parseMember(id), new HashSet<>(), match); + } + + @Test + void inherited_library_members_are_owned_by_the_type_declaring_them() { + assertThat(sema.resolve("lib.Calls#fromParent()").owner().name()).isEqualTo("Parent"); + assertThat(sema.resolve("lib.Calls#two(int)").owner().name()).isEqualTo("Calls"); + assertThat(lookup.declaringType("lib.Calls", new JsonObject(), new HashSet<>())).isNull(); + } + + @Test + void a_closed_type_loader_leaves_types_undeclared_and_unknown() { + JSema closed = new JSema(); + closed.loadTypes(names -> null); + + assertThat(closed.declaresType("lib.Missing")).isFalse(); + assertThat(closed.typeSymbol("lib.Missing").isTypeSymbol()).isFalse(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/OverriddenMethodsTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/OverriddenMethodsTest.java new file mode 100644 index 00000000000..4d766afec51 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/OverriddenMethodsTest.java @@ -0,0 +1,145 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Symbol; + +import static org.assertj.core.api.Assertions.assertThat; + +class OverriddenMethodsTest { + + private static final String LIBRARY = """ + { + "lib.Converter": { + "origin": "classpath", "kind": "interface", "modifiers": ["public"], "interfaces": [], + "typeParameters": 2, "typeVars": ["A", "B"], + "members": [ + {"k": "m", "name": "convert", "desc": "(Ljava/lang/Object;)Ljava/lang/Object;", "vis": "public", "abstract": true, "static": false, + "paramTypes": [{"id": "A", "kind": "typevar"}], "paramVars": ["a"], "retParam": 1, "retType": {"id": "B", "kind": "typevar"}, "throws": []}, + {"k": "m", "name": "reset", "desc": "()V", "vis": "public", "abstract": true, "static": false, "throws": []}, + {"k": "m", "name": "hashCode", "desc": "()I", "vis": "public", "abstract": true, "static": false, "throws": []} + ] + }, + "lib.Impl": { + "origin": "classpath", "kind": "class", "modifiers": ["public"], "super": "java.lang.Object", + "interfaces": ["lib.Converter"], + "interfaceTypes": [{"id": "lib.Converter", "args": [{"id": "java.lang.String", "args": []}, {"id": "java.lang.Boolean", "args": []}]}], + "typeParameters": 0, "typeVars": [], + "typeAnnotations": [ + {"on": "interface", "index": 0, "path": ["<0>"], "name": "lib.NonNull", "values": []}, + {"on": "interface", "index": 0, "path": ["<1>"], "name": "javax.annotation.Nullable", "values": []} + ], + "members": [ + {"k": "m", "name": "convert", "desc": "(Ljava/lang/String;)Ljava/lang/Boolean;", "vis": "public", "static": false, "throws": []}, + {"k": "m", "name": "reset", "desc": "()V", "vis": "public", "static": false, "throws": []}, + {"k": "m", "name": "helper", "desc": "()V", "vis": "private", "static": false, "throws": []}, + {"k": "m", "name": "create", "desc": "()Llib/Impl;", "vis": "public", "static": true, "throws": []} + ] + }, + "lib.Sub": { + "origin": "classpath", "kind": "class", "modifiers": ["public"], "super": "lib.Impl", "interfaces": [], + "typeParameters": 0, "typeVars": [], + "members": [ + {"k": "m", "name": "convert", "desc": "(Ljava/lang/String;)Ljava/lang/Boolean;", "vis": "public", "static": false, "throws": []}, + {"k": "m", "name": "convert", "desc": "(Ljava/lang/Integer;)Ljava/lang/Boolean;", "vis": "public", "static": false, "throws": []}, + {"k": "m", "name": "helper", "desc": "()V", "vis": "private", "static": false, "throws": []}, + {"k": "m", "name": "create", "desc": "()Llib/Impl;", "vis": "public", "static": true, "throws": []} + ] + }, + "java.lang.Object": { + "origin": "classpath", "kind": "class", "modifiers": ["public"], "interfaces": [], "typeParameters": 0, "typeVars": [], + "members": [ + {"k": "m", "name": "hashCode", "desc": "()I", "vis": "public", "static": false, "throws": []} + ] + }, + "java.lang.String": {"origin": "classpath", "kind": "class", "modifiers": ["public", "final"], "super": "java.lang.Object", "interfaces": [], "typeParameters": 0, "typeVars": [], "members": []}, + "java.lang.Boolean": {"origin": "classpath", "kind": "class", "modifiers": ["public", "final"], "super": "java.lang.Object", "interfaces": [], "typeParameters": 0, "typeVars": [], "members": []}, + "java.lang.Integer": {"origin": "classpath", "kind": "class", "modifiers": ["public", "final"], "super": "java.lang.Object", "interfaces": [], "typeParameters": 0, "typeVars": [], "members": []}, + "javax.annotation.Nullable": {"origin": "classpath", "kind": "annotation", "modifiers": ["public"], "interfaces": [], "typeParameters": 0, "typeVars": [], "members": []}, + "lib.Marker": { + "origin": "classpath", "kind": "interface", "modifiers": ["public"], "interfaces": [], "typeParameters": 0, "typeVars": [], + "members": [ + {"k": "m", "name": "hashCode", "desc": "()I", "vis": "public", "abstract": true, "static": false, "throws": []} + ] + } + } + """; + + private JSema sema; + + @BeforeEach + void setUp() { + sema = new JSema(); + sema.loadTypes(names -> new JsonObject()); + sema.ingestTypes(JsonParser.parseString(LIBRARY).getAsJsonObject()); + } + + @Test + void a_method_overrides_the_method_of_its_parameterized_interface() { + List overridden = method("lib.Impl", "convert").overriddenSymbols(); + + assertThat(overridden).hasSize(1); + assertThat(overridden.get(0).owner().name()).isEqualTo("Converter"); + } + + @Test + void a_method_without_a_type_variable_result_keeps_its_own_metadata() { + List overridden = method("lib.Impl", "reset").overriddenSymbols(); + + assertThat(overridden).containsExactly(method("lib.Converter", "reset")); + } + + @Test + void an_overload_with_other_parameters_overrides_nothing() { + assertThat(method("lib.Sub", "convert", "java.lang.Integer").overriddenSymbols()).isEmpty(); + } + + @Test + void private_and_static_methods_override_nothing() { + assertThat(method("lib.Sub", "helper").overriddenSymbols()).isEmpty(); + assertThat(method("lib.Sub", "create").overriddenSymbols()).isEmpty(); + } + + @Test + void an_interface_method_overrides_the_public_methods_of_object() { + List overridden = method("lib.Marker", "hashCode").overriddenSymbols(); + + assertThat(overridden).extracting(method -> method.owner().type().fullyQualifiedName()).containsExactly("java.lang.Object"); + } + + @Test + void an_unknown_method_overrides_nothing() { + JMethodSymbol unknown = new JMethodSymbol(sema, null, "convert"); + unknown.unknown(true); + + assertThat(unknown.overriddenSymbols()).isEmpty(); + } + + private Symbol.MethodSymbol method(String type, String name, String... parameters) { + return sema.getClassType(type).symbol().lookupSymbols(name).stream() + .filter(Symbol.MethodSymbol.class::isInstance) + .map(Symbol.MethodSymbol.class::cast) + .filter(method -> parameters.length == 0 || method.parameterTypes().get(0).is(parameters[0])) + .findFirst() + .orElseThrow(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/Replays.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/Replays.java new file mode 100644 index 00000000000..ab1f19a3339 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/Replays.java @@ -0,0 +1,82 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.sonarsource.scanner.engine.sensor.test.fixtures.TestInputFileBuilder; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.java.AnalysisProgress; +import org.sonar.java.jdt.JDTParser; +import org.sonar.java.model.JParseResult; +import org.sonar.java.model.JParser; +import org.sonar.java.model.JavaVersionImpl; + +/** + * The JDK type declarations a SemSitter server answered, recorded in {@code replay/types.json.gz}, and ECJ parsing of + * test sources. + */ +final class Replays { + + private static final int JAVA_VERSION = 21; + static final Path DIRECTORY = Path.of("src", "test", "resources", "org", "sonar", "java", "semsitter", "replay"); + static final Path TYPES = DIRECTORY.resolve("types.json.gz"); + + private Replays() { + } + + static String read(Path file) throws IOException { + try (InputStream in = Files.newInputStream(file)) { + return new String(isGzip(file) ? new GZIPInputStream(in).readAllBytes() : in.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static boolean isGzip(Path file) { + return file.getFileName().toString().endsWith(".gz"); + } + + static JsonObject readJson(Path file) throws IOException { + if (!Files.exists(file)) { + return new JsonObject(); + } + return JsonParser.parseString(read(file)).getAsJsonObject(); + } + + static InputFile inputFile(Path baseDir, String relativePath, String source) { + return new TestInputFileBuilder("module", relativePath) + .setModuleBaseDir(baseDir) + .setCharset(StandardCharsets.UTF_8) + .setLanguage("java") + .setContents(source) + .build(); + } + + static JParseResult parseWithEcj(Path baseDir, String sample, String source) { + List results = new ArrayList<>(); + JDTParser.create(JParser.Mode.BATCH, new JavaVersionImpl(JAVA_VERSION), List.of(), false, true) + .parse(List.of(inputFile(baseDir, sample + ".java", source)), () -> false, new AnalysisProgress(1), (file, result) -> results.add(result)); + return results.get(0); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemaAnnotationsTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemaAnnotationsTest.java new file mode 100644 index 00000000000..a54213fae96 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemaAnnotationsTest.java @@ -0,0 +1,128 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.AnnotationValue; +import org.sonarsource.semsitter.wire.Fact; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +class SemaAnnotationsTest { + + private JSema sema; + private SemaAnnotations annotations; + + @BeforeEach + void setUp() { + sema = new JSema(); + sema.loadTypes(names -> new JsonObject()); + annotations = sema.annotationFacts(); + } + + @Test + void element_values_without_a_value_of_their_kind_are_null() { + assertThat(element("{\"kind\": \"boolean\"}")).isEqualTo(false); + assertThat(element("{\"kind\": \"boolean\", \"value\": true}")).isEqualTo(true); + assertThat(element("{\"kind\": \"int\", \"value\": {}}")).isNull(); + assertThat(element("{\"kind\": \"string\"}")).isNull(); + assertThat(element("{\"kind\": \"string\", \"value\": \"s\"}")).isEqualTo("s"); + assertThat(element("{\"kind\": \"annotation\", \"value\": \"lib.Marker\"}")).isNull(); + assertThat(element("{\"kind\": \"annotation\"}")).isNull(); + assertThat(element("{\"kind\": \"mystery\", \"value\": 1}")).isNull(); + assertThat(element("{\"value\": 1}")).isNull(); + } + + @Test + void class_values_are_type_symbols() { + assertThat(element("{\"kind\": \"class\", \"value\": \"java.util.List`1\"}")) + .isInstanceOfSatisfying(Symbol.TypeSymbol.class, type -> assertThat(type.type().fullyQualifiedName()).isEqualTo("java.util.List")); + } + + @Test + void parameter_annotations_come_from_the_parameter_annotations_of_a_member() { + annotations.registerParameterAnnotations("p.A#m(int)", json(""" + {"parameterAnnotations": [ + [], + [{"name": "lib.Second", "values": [{"name": "value", "kind": "string", "value": "x"}]}] + ]} + """)); + + List registered = sema.declaredMembers.libraryAnnotations.get(SemaFacts.parameterKey("p.A#m(int)", 1)); + assertThat(names(registered)).containsExactly("lib.Second"); + assertThat(registered.get(0).values()).extracting(AnnotationValue::name, AnnotationValue::value).containsExactly(tuple("value", "x")); + assertThat(sema.declaredMembers.libraryAnnotations).hasSize(1); + } + + @Test + void members_without_parameter_annotations_register_nothing() { + annotations.registerParameterAnnotations("p.A#m()", json("{}")); + annotations.registerParameterAnnotations("p.A#m()", json("{\"parameterAnnotations\": \"none\"}")); + + assertThat(sema.declaredMembers.libraryAnnotations).isEmpty(); + } + + @Test + void declared_annotations_of_a_graph_fact_keep_no_values() { + sema.facts.put("p.A", Fact.newBuilder().addAnnotations("lib.Marker`1").build()); + + List declared = annotations.declaredAnnotations("p.A"); + + assertThat(names(declared)).containsExactly("lib.Marker"); + assertThat(declared.get(0).values()).isEmpty(); + assertThat(annotations.declaredAnnotations("p.Other")).isEmpty(); + assertThat(annotations.declaredAnnotations(null)).isEmpty(); + } + + @Test + void outermost_type_annotations_add_to_the_declared_ones_once() { + List read = annotations.readAnnotations(json(""" + {"annotations": [{"name": "lib.A", "values": 1}, {"name": "lib.B", "values": [1, {"kind": "int", "value": 2}]}], + "typeAnnotations": [ + 1, + {"on": "type", "path": [], "name": "lib.A", "values": []}, + {"on": "type", "path": [], "name": "lib.C", "values": []}, + {"on": "type", "path": [{"kind": "array"}], "name": "lib.Deep", "values": []}, + {"on": "type", "name": "lib.NoPath", "values": []}, + {"on": "param", "path": [], "name": "lib.Param", "values": []} + ]} + """)); + + assertThat(names(read)).containsExactly("lib.A", "lib.B", "lib.C"); + assertThat(read.get(0).values()).isEmpty(); + assertThat(read.get(1).values()).extracting(AnnotationValue::name, AnnotationValue::value).containsExactly(tuple("value", 2)); + assertThat(annotations.readAnnotations(json("{\"annotations\": \"lib.A\"}"))).isEmpty(); + } + + private Object element(String value) { + return annotations.readAnnotationElement(json(value)); + } + + private static JsonObject json(String text) { + return JsonParser.parseString(text).getAsJsonObject(); + } + + private static List names(List declared) { + return declared.stream().map(DeclaredAnnotation::name).toList(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemaFactsTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemaFactsTest.java new file mode 100644 index 00000000000..e6313abd73b --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemaFactsTest.java @@ -0,0 +1,136 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.sonarsource.semsitter.wire.Fact; +import org.sonarsource.semsitter.wire.FactValue; +import org.sonarsource.semsitter.wire.Symbol; + +import static org.assertj.core.api.Assertions.assertThat; + +class SemaFactsTest { + + @Test + void type_fact_is_only_read_from_a_type_value() { + Symbol flagged = Symbol.newBuilder().putFacts("type", FactValue.newBuilder().setFlag(true).build()).build(); + + assertThat(SemaFacts.typeFact(flagged)).isNull(); + assertThat(SemaFacts.typeFact(Symbol.getDefaultInstance())).isNull(); + } + + @Test + void type_names_skip_locals_generic_parameters_primitives_and_malformed_owners() { + Set names = new HashSet<>(); + SemaFacts.addTypeName(names, null); + SemaFacts.addTypeName(names, ""); + SemaFacts.addTypeName(names, "p.A%1"); + SemaFacts.addTypeName(names, "p.A#f()$Local"); + SemaFacts.addTypeName(names, "p.A(x)#m"); + SemaFacts.addTypeName(names, "p.A"); + SemaFacts.addTypeName(names, "int"); + SemaFacts.addTypeName(names, "p.A b"); + SemaFacts.addTypeName(names, "p.G`1#m()"); + SemaFacts.addTypeName(names, "p.B#field"); + + assertThat(names).containsExactlyInAnyOrder("p.A", "p.G", "p.B"); + } + + @Test + void well_known_types_are_the_roots_of_every_hierarchy() { + assertThat(SemaFacts.isWellKnown("java.lang.Object")).isTrue(); + assertThat(SemaFacts.isWellKnown("java.lang.Cloneable")).isTrue(); + assertThat(SemaFacts.isWellKnown("java.io.Serializable")).isTrue(); + assertThat(SemaFacts.isWellKnown("java.lang.String")).isFalse(); + } + + @Test + void constants_are_boxed_as_the_primitive_type_of_the_field() { + JSema sema = new JSema(); + + assertThat(SemaFacts.constantOf(sema.primitiveType("int"), "1")).isEqualTo(1); + assertThat(SemaFacts.constantOf(sema.primitiveType("long"), "2")).isEqualTo(2L); + assertThat(SemaFacts.constantOf(sema.primitiveType("short"), "3")).isEqualTo((short) 3); + assertThat(SemaFacts.constantOf(sema.primitiveType("byte"), "4")).isEqualTo((byte) 4); + assertThat(SemaFacts.constantOf(sema.primitiveType("float"), "1.5")).isEqualTo(1.5f); + assertThat(SemaFacts.constantOf(sema.primitiveType("double"), "2.5")).isEqualTo(2.5); + assertThat(SemaFacts.constantOf(sema.primitiveType("boolean"), "true")).isEqualTo(true); + assertThat(SemaFacts.constantOf(sema.primitiveType("char"), "A")).isEqualTo(65); + assertThat(SemaFacts.constantOf(sema.primitiveType("char"), "AB")).isEqualTo("AB"); + assertThat(SemaFacts.constantOf(sema.primitiveType("int"), "x")).isEqualTo("x"); + assertThat(SemaFacts.constantOf(null, "text")).isEqualTo("text"); + } + + @Test + void type_facts_are_the_kinds_of_type_declarations() { + assertThat(List.of("class", "interface", "enum", "record", "annotation", "exception")) + .allMatch(kind -> SemaFacts.isTypeFact(Fact.newBuilder().setKind(kind).build())); + assertThat(SemaFacts.isTypeFact(Fact.newBuilder().setKind("method").build())).isFalse(); + } + + @Test + void member_flags_become_modifiers_and_package_visibility_adds_none() { + JSema sema = new JSema(); + JMethodSymbol method = new JMethodSymbol(sema, "p.A#m()", "m"); + SemaFacts.applyMemberFlags(method, json("{\"static\":true,\"final\":true,\"synchronized\":true,\"abstract\":true,\"vis\":\"package\"}")); + JMethodSymbol hidden = new JMethodSymbol(sema, "p.A#n()", "n"); + SemaFacts.applyMemberFlags(hidden, json("{\"vis\":\"private\"}")); + + assertThat(method.isStatic()).isTrue(); + assertThat(method.isFinal()).isTrue(); + assertThat(method.isSynchronizedMethod()).isTrue(); + assertThat(method.isAbstract()).isTrue(); + assertThat(method.isPackageVisibility()).isTrue(); + assertThat(hidden.isPrivate()).isTrue(); + } + + @Test + void member_ids_split_parameters_outside_type_arguments() { + MemberId parsed = SemaFacts.parseMember("p.A#m(java.util.Map,int)"); + + assertThat(parsed.paramList()).containsExactly("java.util.Map", "int"); + assertThat(parsed.arity()).isEqualTo(2); + assertThat(SemaFacts.parseMember("p.A")).isNull(); + assertThat(SemaFacts.memberName("p.A")).isNull(); + assertThat(SemaFacts.parseMember("p.A#m(2)").arityOnly()).isTrue(); + } + + @Test + void json_readers_ignore_values_of_another_shape() { + JsonObject object = json("{\"o\":{},\"a\":[1,{},\"x\"],\"n\":null,\"p\":\"v\"}"); + + assertThat(SemaFacts.text(null, "p")).isNull(); + assertThat(SemaFacts.text(object, "o")).isNull(); + assertThat(SemaFacts.text(object, "p")).isEqualTo("v"); + assertThat(SemaFacts.truth(object, "o")).isFalse(); + assertThat(SemaFacts.strings(null, "a")).isEmpty(); + assertThat(SemaFacts.strings(object, "n")).isEmpty(); + assertThat(SemaFacts.strings(object, "o")).isEmpty(); + assertThat(SemaFacts.strings(object, "p")).containsExactly("v"); + assertThat(SemaFacts.strings(object, "a")).containsExactly("1", "x"); + assertThat(SemaFacts.flat(List.of("a, b", " ,c"))).containsExactly("a", "b", "c"); + } + + private static JsonObject json(String text) { + return JsonParser.parseString(text).getAsJsonObject(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SubstitutionTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SubstitutionTest.java new file mode 100644 index 00000000000..95647645bae --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SubstitutionTest.java @@ -0,0 +1,111 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Type; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.java.semsitter.JTypeFixtures.library; +import static org.sonar.java.semsitter.JTypeFixtures.member; + +class SubstitutionTest { + + private static final String BOX = "lib.Box"; + private static final String LIST = "java.util.List"; + private static final String ARRAY_LIST = "java.util.ArrayList"; + private static final String OBJECT = "java.lang.Object"; + private static final String T = "{\"id\": \"T\", \"kind\": \"typevar\"}"; + private static final String BOX_VARIABLES = "\"typeParameters\": 1, \"typeVars\": [\"T\"]"; + + private final JTypeFixtures fixtures = new JTypeFixtures( + library(BOX, BOX_VARIABLES, + member("put", "(Ljava/lang/Object;)V", "\"paramVars\": [\"c0\"], \"paramTypes\": [" + T + "]"), + member("named", "(Ljava/util/List;)V", "\"paramVars\": [\"\"], \"paramTypes\": [{\"id\": \"java.util.List\", \"args\": [{\"id\": \"java.lang.String\"}]}]")), + "{\"lib.Bare\": {\"origin\": \"classpath\", \"kind\": \"class\", \"super\": \"java.lang.Object\", \"typeParameters\": 1, \"typeVars\": [\"T\"]}}"); + private final Substitution substitution = fixtures.sema.substitution(); + private final JType variable = JType.typeVar(fixtures.sema, "T", "T"); + + @Test + void member_type_reads_the_declaring_arguments() { + assertThat(substitution.asMemberOf(variable, box(fixtures.string()))).isEqualTo(fixtures.string()); + assertThat(substitution.asMemberOf(variable, fixtures.type(BOX))).isSameAs(variable); + assertThat(substitution.asMemberOf(variable, Type.UNKNOWN)).isSameAs(variable); + assertThat(substitution.asMemberOf(Type.UNKNOWN, box(fixtures.string()))).isSameAs(Type.UNKNOWN); + } + + @Test + void supertype_is_instantiated_with_the_arguments_of_its_subtype() { + JType declared = fixtures.type(LIST, JType.typeVar(fixtures.sema, "E", "E")); + + assertThat(substitution.instantiateSupertype(fixtures.type(ARRAY_LIST, fixtures.string()), declared)).isEqualTo(fixtures.type(LIST, fixtures.string())); + assertThat(substitution.instantiateSupertype(fixtures.type(ARRAY_LIST), declared)).isSameAs(declared); + assertThat(substitution.instantiateSupertype(fixtures.type(ARRAY_LIST, fixtures.string()), Type.UNKNOWN)).isSameAs(Type.UNKNOWN); + assertThat(substitution.instantiateSupertype(fixtures.type("lib.Undeclared", fixtures.string()), declared)).isEqualTo(declared); + } + + @Test + void class_variable_argument_is_read_from_the_declaring_type() { + JMethodSymbol put = method(BOX, "put", OBJECT); + + assertThat(substitution.classVariableArgument(put, 0, box(fixtures.string()))).isEqualTo(fixtures.string()); + assertThat(substitution.classVariableArgument(put, 1, box(fixtures.string()))).isNull(); + assertThat(substitution.classVariableArgument(put, 0, fixtures.type(BOX))).isNull(); + assertThat(substitution.classVariableArgument(method(BOX, "named", LIST), 0, box(fixtures.string()))).isNull(); + assertThat(substitution.classVariableArgument(put, 0, fixtures.type("lib.Undeclared", fixtures.string()))).isNull(); + assertThat(substitution.classVariableArgument(put, 0, fixtures.type(LIST, fixtures.string()))).isNull(); + } + + @Test + void generic_member_needs_a_declaration_with_its_signature() { + JMethodSymbol bare = new JMethodSymbol(fixtures.sema, "lib.Bare#get()", "get"); + bare.owner(fixtures.type("lib.Bare").symbol()); + bare.parameterTypes(List.of()); + + assertThat(substitution.lookupGenericMember(bare)).isNull(); + assertThat(substitution.lookupGenericMember(method(BOX, "put", OBJECT))).isNotNull(); + } + + @Test + void parameters_named_by_a_type_variable_match_any_erasure() { + JMethodSymbol unknown = boxMethod(Type.UNKNOWN); + JMethodSymbol variableParameter = boxMethod(variable); + JMethodSymbol local = boxMethod(fixtures.type("lib.Box::Local")); + JMethodSymbol other = boxMethod(fixtures.string()); + + assertThat(substitution.lookupGenericMember(unknown)).isNotNull(); + assertThat(substitution.lookupGenericMember(variableParameter)).isNotNull(); + assertThat(substitution.lookupGenericMember(local)).isNotNull(); + assertThat(substitution.lookupGenericMember(other)).isNull(); + } + + private JMethodSymbol boxMethod(Type parameter) { + JMethodSymbol method = new JMethodSymbol(fixtures.sema, "lib.Box#put(java.lang.Object)", "put"); + method.owner(fixtures.type(BOX).symbol()); + method.parameterTypes(List.of(parameter)); + return method; + } + + private JType box(JType argument) { + return fixtures.type(BOX, argument); + } + + private JMethodSymbol method(String owner, String name, String... parameters) { + return fixtures.method(owner, name, parameters); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SubtypingTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SubtypingTest.java new file mode 100644 index 00000000000..332dba3d629 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SubtypingTest.java @@ -0,0 +1,126 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.util.HashSet; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Type; + +import static org.assertj.core.api.Assertions.assertThat; + +class SubtypingTest { + + private static final String LIST = "java.util.List"; + private static final String NUMBER = "java.lang.Number"; + + private final JTypeFixtures fixtures = new JTypeFixtures(); + private final JSema sema = fixtures.sema; + + @Test + void nothing_is_a_subtype_of_a_missing_type() { + assertThat(Subtyping.isSubtype(fixtures.string(), null, new HashSet<>())).isFalse(); + assertThat(fixtures.string().isSubtypeOf(Type.UNKNOWN)).isFalse(); + assertThat(JType.unknown(sema).isSubtypeOf(fixtures.object())).isFalse(); + } + + @Test + void capture_and_wildcard_are_subtypes_through_their_bound() { + assertThat(fixtures.capture(fixtures.string()).isSubtypeOf("java.lang.CharSequence")).isTrue(); + assertThat(fixtures.extending(fixtures.integer()).isSubtypeOf(NUMBER)).isTrue(); + assertThat(fixtures.extending(fixtures.integer()).isSubtypeOf(fixtures.string())).isFalse(); + } + + @Test + void type_variable_is_a_subtype_of_itself_and_of_its_bound() { + JType variable = JType.typeVar(sema, "E", "java.util.List`1"); + + assertThat(variable.isSubtypeOf(JType.typeVar(sema, "E", "java.util.List`1"))).isTrue(); + assertThat(variable.isSubtypeOf(JType.typeVar(sema, "T", "java.util.Set`1"))).isFalse(); + assertThat(variable.isSubtypeOf(fixtures.object())).isTrue(); + assertThat(fixtures.string().isSubtypeOf(variable)).isFalse(); + } + + @Test + void null_is_a_subtype_of_every_reference_type() { + JType nullType = JType.nullType(sema); + + assertThat(nullType.isSubtypeOf(fixtures.string())).isTrue(); + assertThat(nullType.isSubtypeOf(fixtures.primitive("int"))).isFalse(); + } + + @Test + void primitives_widen() { + assertThat(fixtures.primitive("byte").isSubtypeOf(fixtures.primitive("short"))).isTrue(); + assertThat(fixtures.primitive("char").isSubtypeOf(fixtures.primitive("int"))).isTrue(); + assertThat(fixtures.primitive("int").isSubtypeOf(fixtures.primitive("long"))).isTrue(); + assertThat(fixtures.primitive("long").isSubtypeOf(fixtures.primitive("float"))).isTrue(); + assertThat(fixtures.primitive("float").isSubtypeOf(fixtures.primitive("double"))).isTrue(); + assertThat(fixtures.primitive("double").isSubtypeOf(fixtures.primitive("float"))).isFalse(); + assertThat(fixtures.primitive("boolean").isSubtypeOf(fixtures.primitive("int"))).isFalse(); + assertThat(fixtures.primitive("int").isSubtypeOf(fixtures.integer())).isFalse(); + } + + @Test + void intersection_is_a_subtype_of_each_bound() { + JType intersection = JType.intersection(sema, List.of(fixtures.type(NUMBER), fixtures.type("java.lang.Comparable"))); + + assertThat(intersection.isSubtypeOf("java.lang.Comparable")).isTrue(); + assertThat(intersection.isSubtypeOf("java.io.Serializable")).isTrue(); + assertThat(intersection.isSubtypeOf(fixtures.string())).isFalse(); + } + + @Test + void arrays_are_cloneable_and_serializable() { + JType strings = JType.array(sema, fixtures.string()); + + assertThat(strings.isSubtypeOf(fixtures.object())).isTrue(); + assertThat(strings.isSubtypeOf("java.lang.Cloneable")).isTrue(); + assertThat(strings.isSubtypeOf("java.io.Serializable")).isTrue(); + assertThat(strings.isSubtypeOf("java.lang.CharSequence")).isFalse(); + assertThat(strings.isSubtypeOf(JType.array(sema, fixtures.object()))).isTrue(); + } + + @Test + void parameterizations_need_as_many_arguments() { + JType malformed = fixtures.type(LIST, fixtures.string(), fixtures.string()); + + assertThat(malformed.isSubtypeOf(fixtures.type(LIST, fixtures.string()))).isFalse(); + } + + @Test + void lower_bounded_wildcard_contains_supertypes_of_its_bound() { + JType consumer = fixtures.type(LIST, JType.superWildcard(sema, fixtures.integer())); + + assertThat(fixtures.type(LIST, fixtures.type(NUMBER)).isSubtypeOf(consumer)).isTrue(); + assertThat(fixtures.type(LIST, fixtures.string()).isSubtypeOf(consumer)).isFalse(); + assertThat(fixtures.type(LIST, JType.superWildcard(sema, fixtures.type(NUMBER))).isSubtypeOf(consumer)).isTrue(); + assertThat(fixtures.type(LIST, JType.superWildcard(sema, fixtures.integer())).isSubtypeOf(fixtures.type(LIST, JType.superWildcard(sema, fixtures.type(NUMBER))))) + .isFalse(); + assertThat(fixtures.type(LIST, fixtures.extending(fixtures.integer())).isSubtypeOf(consumer)).isFalse(); + } + + @Test + void upper_bounded_wildcard_contains_subtypes_of_its_bound() { + JType producer = fixtures.type(LIST, fixtures.extending(fixtures.type(NUMBER))); + + assertThat(fixtures.type(LIST, fixtures.integer()).isSubtypeOf(producer)).isTrue(); + assertThat(fixtures.type(LIST, fixtures.string()).isSubtypeOf(producer)).isFalse(); + assertThat(fixtures.type(LIST, fixtures.string()).isSubtypeOf(fixtures.type(LIST, fixtures.extending(fixtures.object())))).isTrue(); + assertThat(fixtures.type(LIST, fixtures.extending(fixtures.integer())).isSubtypeOf(fixtures.type(LIST, fixtures.integer()))).isFalse(); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/TreeAnnotationTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/TreeAnnotationTest.java new file mode 100644 index 00000000000..70fa45ca082 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/TreeAnnotationTest.java @@ -0,0 +1,180 @@ +/* + * SonarQube Java + * Copyright (C) SonarSource Sàrl + * mailto:info AT sonarsource DOT com + * + * You can redistribute and/or modify this program under the terms of + * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Sonar Source-Available License for more details. + * + * You should have received a copy of the Sonar Source-Available License + * along with this program; if not, see https://sonarsource.com/license/ssal/ + */ +package org.sonar.java.semsitter; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.AnnotationValue; +import org.sonar.plugins.java.api.tree.AnnotationTree; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.MethodTree; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +/** Reads annotation values from trees the ECJ frontend gives, as those of the SemSitter frontend have the same shape. */ +class TreeAnnotationTest { + + private static final String SOURCE = """ + import java.lang.annotation.Retention; + import java.lang.annotation.RetentionPolicy; + + @interface Values { + String[] names() default {}; + int number() default 0; + long big() default 0; + char letter() default 'a'; + Class type() default Object.class; + Deprecated nested() default @Deprecated; + String text() default ""; + int sum() default 0; + boolean flag() default false; + float ratio() default 0; + double scale() default 0; + char escaped() default 'a'; + char unicode() default 'a'; + char octal() default 'a'; + } + + class Holder { + static final int CONSTANT = 7; + static String field = "f"; + + @Values(names = "one", number = 42, big = 3L, letter = 'z', type = String.class, nested = @Deprecated(since = "9"), text = \""" + block\""", sum = 1 + 2, flag = true) + void literals() {} + + @Values(ratio = 1.5f, scale = 2_0.5, escaped = '\\n', unicode = '\\u0041', octal = '\\101') + void numbers() {} + + @Values(names = {"x", "y"}, number = CONSTANT, sum = Holder.CONSTANT) + void constants() {} + + @SuppressWarnings("unchecked") + void single() {} + + @Retention(RetentionPolicy.RUNTIME) + void enumConstant() {} + + @SuppressWarnings(Holder.field) + void notConstant() {} + + @SuppressWarnings(MISSING) + void unknownValue() {} + + @Missing(1) + void unknownAnnotation() {} + } + """; + + @TempDir + Path baseDir; + + private final JSema sema = new JSema(); + private final Map annotations = new HashMap<>(); + + @BeforeEach + void parse() throws Exception { + Replays.parseWithEcj(baseDir, "TreeAnnotationSample", SOURCE).get().accept(new BaseTreeVisitor() { + @Override + public void visitMethod(MethodTree tree) { + if (!tree.modifiers().annotations().isEmpty()) { + annotations.put(tree.simpleName().name(), tree.modifiers().annotations().get(0)); + } + super.visitMethod(tree); + } + }); + } + + @Test + void literal_values_keep_their_java_type() { + Map values = values("literals"); + + assertThat((Object[]) values.get("names")).containsExactly("one"); + assertThat(values) + .containsEntry("number", 42) + .containsEntry("big", 3L) + .containsEntry("letter", 'z') + .containsEntry("sum", 3) + .containsEntry("flag", true); + assertThat(values.get("text")).asString().contains("block"); + assertThat(values.get("type")).isInstanceOfSatisfying(Symbol.TypeSymbol.class, type -> assertThat(type.type().fullyQualifiedName()).isEqualTo("java.lang.String")); + assertThat(values.get("nested")).isInstanceOfSatisfying(TreeAnnotation.class, nested -> { + assertThat(nested.symbol().type().fullyQualifiedName()).isEqualTo("java.lang.Deprecated"); + assertThat(nested.values()).extracting(AnnotationValue::name, AnnotationValue::value).containsExactly(tuple("since", "9")); + }); + } + + @Test + void floating_and_escaped_char_literals_keep_their_java_type() { + assertThat(values("numbers")) + .containsEntry("ratio", 1.5f) + .containsEntry("scale", 20.5) + .containsEntry("escaped", '\n') + .containsEntry("unicode", 'A') + .containsEntry("octal", 'A'); + } + + @Test + void constant_names_give_their_value() { + Map values = values("constants"); + + assertThat((Object[]) values.get("names")).containsExactly("x", "y"); + assertThat(values).containsEntry("number", 7).containsEntry("sum", 7); + } + + @Test + void a_single_value_of_an_array_member_is_an_array() { + assertThat((Object[]) values("single").get("value")).containsExactly("unchecked"); + } + + @Test + void enum_constants_are_their_symbol() { + assertThat(values("enumConstant").get("value")).isInstanceOfSatisfying(Symbol.VariableSymbol.class, constant -> assertThat(constant.name()).isEqualTo("RUNTIME")); + } + + @Test + void a_variable_that_is_not_a_constant_has_no_value() { + assertThat((Object[]) values("notConstant").get("value")).containsOnlyNulls(); + } + + @Test + void an_unknown_name_has_no_value_as_with_ecj() { + assertThat((Object[]) values("unknownValue").get("value")).containsOnlyNulls(); + } + + @Test + void an_unknown_annotation_has_no_values() { + TreeAnnotation annotation = new TreeAnnotation(sema, annotations.get("unknownAnnotation")); + + assertThat(annotation.symbol().isUnknown()).isTrue(); + assertThat(annotation.values()).isEmpty(); + } + + private Map values(String method) { + List values = new TreeAnnotation(sema, annotations.get(method)).values(); + Map byName = new HashMap<>(); + values.forEach(value -> byName.put(value.name(), value.value())); + return byName; + } +} diff --git a/java-frontend-semsitter/src/test/resources/org/sonar/java/semsitter/replay/types.json.gz b/java-frontend-semsitter/src/test/resources/org/sonar/java/semsitter/replay/types.json.gz new file mode 100644 index 00000000000..d1c6bf6826d Binary files /dev/null and b/java-frontend-semsitter/src/test/resources/org/sonar/java/semsitter/replay/types.json.gz differ diff --git a/java-frontend/src/main/java/org/sonar/java/model/AnnotationValueImpl.java b/java-frontend/src/main/java/org/sonar/java/model/AnnotationValueImpl.java index 3e218d99377..8f88783b2c6 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/AnnotationValueImpl.java +++ b/java-frontend/src/main/java/org/sonar/java/model/AnnotationValueImpl.java @@ -16,6 +16,7 @@ */ package org.sonar.java.model; +import javax.annotation.Nullable; import org.sonar.plugins.java.api.semantic.SymbolMetadata; public class AnnotationValueImpl implements SymbolMetadata.AnnotationValue { @@ -23,7 +24,7 @@ public class AnnotationValueImpl implements SymbolMetadata.AnnotationValue { private final String name; private final Object value; - public AnnotationValueImpl(String name, Object value) { + public AnnotationValueImpl(String name, @Nullable Object value) { this.name = name; this.value = value; } diff --git a/java-frontend/src/main/java/org/sonar/java/utils/SpringUtils.java b/java-frontend/src/main/java/org/sonar/java/utils/SpringUtils.java index 714fc59d889..c4f19b228e8 100644 --- a/java-frontend/src/main/java/org/sonar/java/utils/SpringUtils.java +++ b/java-frontend/src/main/java/org/sonar/java/utils/SpringUtils.java @@ -148,7 +148,9 @@ public static String extractBeanNameFromAnnotation(SymbolMetadata meta, String s if (attrs != null) { Optional name = attrs.stream() .filter(v -> VALUE_ATTRIBUTE.equals(v.name()) || "name".equals(v.name())) - .map(v -> (String) v.value()) + .map(SymbolMetadata.AnnotationValue::value) + .filter(String.class::isInstance) + .map(String.class::cast) .filter(s -> !s.isBlank()) .findFirst(); if (name.isPresent()) { @@ -194,7 +196,9 @@ public static String extractQualifierValue(SymbolMetadata metadata) { } return attrs.stream() .filter(v -> VALUE_ATTRIBUTE.equals(v.name())) - .map(v -> (String) v.value()) + .map(SymbolMetadata.AnnotationValue::value) + .filter(String.class::isInstance) + .map(String.class::cast) .filter(s -> !s.isBlank()) .findFirst() .orElse(null); diff --git a/java-frontend/src/test/java/org/sonar/java/utils/SpringUtilsTest.java b/java-frontend/src/test/java/org/sonar/java/utils/SpringUtilsTest.java index a37248c11d1..e93f8200e38 100644 --- a/java-frontend/src/test/java/org/sonar/java/utils/SpringUtilsTest.java +++ b/java-frontend/src/test/java/org/sonar/java/utils/SpringUtilsTest.java @@ -258,6 +258,9 @@ class WithExplicitName {} class WithBlankName {} class NoStereotypeAnnotation {} + + @org.springframework.stereotype.Component(Unresolved.NAME) + class WithUnresolvedName {} """, TestClasspathUtils.DEFAULT_MODULE.getClassPath()); @Test @@ -287,6 +290,13 @@ void falls_back_to_decapitalized_simple_name_when_no_stereotype_annotation() { assertThat(SpringUtils.extractBeanNameFromAnnotation(clazz.symbol().metadata(), clazz.simpleName().name())) .isEqualTo("noStereotypeAnnotation"); } + + @Test + void falls_back_to_decapitalized_simple_name_when_the_explicit_name_is_unresolved() { + var clazz = (ClassTreeImpl) compilationUnit.types().get(4); + assertThat(SpringUtils.extractBeanNameFromAnnotation(clazz.symbol().metadata(), clazz.simpleName().name())) + .isEqualTo("withUnresolvedName"); + } } // ---- extractQualifierValue ------------------------------------------------------ @@ -298,7 +308,8 @@ class A { void m( @org.springframework.beans.factory.annotation.Qualifier("qualifierValue") Object withQualifier, @org.springframework.beans.factory.annotation.Qualifier("") Object withBlankQualifier, - Object withoutQualifier) { + Object withoutQualifier, + @org.springframework.beans.factory.annotation.Qualifier(Unresolved.NAME) Object withUnresolvedQualifier) { } } """, TestClasspathUtils.DEFAULT_MODULE.getClassPath()); @@ -321,6 +332,12 @@ void returns_null_when_no_qualifier_annotation() { var withoutQualifier = method.parameters().get(2); assertThat(SpringUtils.extractQualifierValue(withoutQualifier.symbol().metadata())).isNull(); } + + @Test + void returns_null_when_the_qualifier_value_is_unresolved() { + var withUnresolvedQualifier = method.parameters().get(3); + assertThat(SpringUtils.extractQualifierValue(withUnresolvedQualifier.symbol().metadata())).isNull(); + } } // ---- collectAutowiredDependenciesOnClass -----------------------------------------