diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java new file mode 100644 index 00000000000..b96c33d3c6b --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/CompilerWarnings.java @@ -0,0 +1,738 @@ +/* + * 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.EnumMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.sonar.java.model.ExpressionUtils; +import org.sonar.java.model.JavaTree; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.BinaryExpressionTree; +import org.sonar.plugins.java.api.tree.CatchTree; +import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.ImportClauseTree; +import org.sonar.plugins.java.api.tree.ImportTree; +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; +import org.sonar.plugins.java.api.tree.SyntaxToken; +import org.sonar.plugins.java.api.tree.SyntaxTrivia; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.TryStatementTree; +import org.sonar.plugins.java.api.tree.TypeTree; +import org.sonar.plugins.java.api.tree.UnionTypeTree; + +/** + * The compiler diagnostics the checks read from the compilation unit, derived from the tree and its symbols: + * unused imports and assignments without effect. + */ +final class CompilerWarnings extends BaseTreeVisitor { + + private static final Pattern JAVADOC_REFERENCE = Pattern.compile("\\{@(?:link|linkplain|value)\\s+([^}]*)\\}|@(?:see|throws|exception)\\s+([^\\r\\n]*)"); + private static final Pattern MARKDOWN_LINK = Pattern.compile("\\[([^\\]\\r\\n]*)\\]"); + private static final Pattern JAVA_NAME = Pattern.compile("[\\p{L}_$][\\p{L}\\p{N}_$]*"); + + private static final Map NUMERIC_RANK = Map.of("byte", 0, "short", 1, "char", 1, "int", 2, "long", 3, "float", 4, "double", 5); + + static final Set SUPPORTED_KINDS = Set.of(ProblemKind.UNUSED_IMPORT, ProblemKind.REDUNDANT_CAST, ProblemKind.ASSIGNMENT_HAS_NO_EFFECT, ProblemKind.MASKED_CATCH); + + private final Map> warnings = new EnumMap<>(ProblemKind.class); + private final List identifiers = new ArrayList<>(); + private final Set javadocNames = new HashSet<>(); + private final List tries = new ArrayList<>(); + private final JSema sema; + + private CompilerWarnings(JSema sema) { + this.sema = sema; + } + + static void addTo(JavaTree.CompilationUnitTreeImpl unit) { + CompilerWarnings visitor = new CompilerWarnings((JSema) unit.sema); + visitor.scan(unit.packageDeclaration()); + visitor.scan(unit.types()); + unit.imports().forEach(visitor::scan); + visitor.collectJavadocNames(unit); + visitor.reportUnusedImports(unit); + visitor.reportUnreachableCatches(unit); + unit.addWarnings(visitor.warnings); + } + + private void add(ProblemKind type, String message, Tree tree) { + warnings.computeIfAbsent(type, key -> new LinkedHashSet<>()).add(new JWarning(message, type, tree)); + } + + @Override + public void visitImport(ImportTree tree) { + // names inside an import are not uses + } + + @Override + public void visitIdentifier(IdentifierTree tree) { + identifiers.add(tree); + super.visitIdentifier(tree); + } + + @Override + public void visitArrayType(org.sonar.plugins.java.api.tree.ArrayTypeTree tree) { + scan(tree.annotations()); + super.visitArrayType(tree); + } + + /** Only simple names use an import: the member of a qualified name is not one. */ + @Override + public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { + scan(tree.expression()); + if (tree.identifier() instanceof JavaTree.AnnotatedTypeTree annotated) { + scan(annotated.annotations()); + } + } + + @Override + public void visitTypeCast(org.sonar.plugins.java.api.tree.TypeCastTree tree) { + Type cast = tree.type().symbolType(); + Type operand = tree.expression().symbolType(); + boolean widening = !cast.isUnknown() && !operand.isUnknown() && operand.isSubtypeOf(cast) && sema.preservesArguments(operand, cast) && !changesTypeFor(tree, operand) + && !isResultOfArgumentLambda(tree); + if (widening) { + if (cast.erasure().fullyQualifiedName().equals(operand.erasure().fullyQualifiedName()) && elementType(cast).typeArguments().isEmpty() == elementType(operand).typeArguments().isEmpty()) { + add(ProblemKind.REDUNDANT_CAST, "Unnecessary cast from " + operand.erasure().name() + " to " + cast.erasure().name(), tree); + } + } + if (widening && assignedTo(tree).filter(target -> !target.isUnknown() && operand.isSubtypeOf(target) && cast.isSubtypeOf(target)).isPresent()) { + // the cast widens a value that is assigned to a type accepting it as is + add(ProblemKind.REDUNDANT_CAST, "Unnecessary cast from " + operand.erasure().name() + " to " + cast.erasure().name(), tree); + } + if (widening && cast.isArray() && isIndexedArray(tree)) { + add(ProblemKind.REDUNDANT_CAST, "Unnecessary cast from " + operand.erasure().name() + " to " + cast.erasure().name(), tree); + } + super.visitTypeCast(tree); + scan(tree.bounds()); + } + + /** Whether the cast is the result of a lambda passed as an argument: it can fix the type the call infers. */ + private static boolean isResultOfArgumentLambda(org.sonar.plugins.java.api.tree.TypeCastTree cast) { + Tree parent = cast.parent(); + while (parent instanceof org.sonar.plugins.java.api.tree.ParenthesizedTree || parent instanceof org.sonar.plugins.java.api.tree.ReturnStatementTree) { + parent = parent.parent(); + } + if (parent instanceof org.sonar.plugins.java.api.tree.BlockTree) { + parent = parent.parent(); + } + return parent instanceof org.sonar.plugins.java.api.tree.LambdaExpressionTree lambda && lambda.parent() instanceof org.sonar.plugins.java.api.tree.Arguments; + } + + /** The innermost element type of an array type; the type itself otherwise. */ + private static Type elementType(Type type) { + Type element = type; + while (element.isArray() && element instanceof Type.ArrayType array) { + element = array.elementType(); + } + return element; + } + + /** Whether the cast is the array an element is read from. */ + private static boolean isIndexedArray(org.sonar.plugins.java.api.tree.TypeCastTree cast) { + Tree child = cast; + Tree parent = cast.parent(); + while (parent instanceof org.sonar.plugins.java.api.tree.ParenthesizedTree) { + child = parent; + parent = parent.parent(); + } + return parent instanceof org.sonar.plugins.java.api.tree.ArrayAccessExpressionTree access && access.expression() == child; + } + + /** Whether the cast is the operand of another cast that the operand's own type cannot reach without it. */ + private boolean changesTypeFor(org.sonar.plugins.java.api.tree.TypeCastTree cast, Type operand) { + Tree parent = cast.parent(); + while (parent instanceof org.sonar.plugins.java.api.tree.ParenthesizedTree) { + parent = parent.parent(); + } + if (!(parent instanceof org.sonar.plugins.java.api.tree.TypeCastTree outer)) { + return false; + } + Type target = outer.type().symbolType(); + return target.isParameterized() && operand.isParameterized() && !sema.preservesArguments(operand, target) && !sema.preservesArguments(target, operand); + } + + /** The type of the parameter {@code argument} is passed to, when no other method of the owner could take the call instead. */ + private static java.util.Optional soleParameterType(org.sonar.plugins.java.api.tree.Arguments arguments, Tree argument) { + Symbol.MethodSymbol method = arguments.parent() instanceof org.sonar.plugins.java.api.tree.MethodInvocationTree call ? call.methodSymbol() + : arguments.parent() instanceof org.sonar.plugins.java.api.tree.NewClassTree creation ? creation.methodSymbol() : null; + int index = arguments.indexOf(argument); + if (method == null || method.isUnknown() || index < 0 || index >= method.parameterTypes().size() || method.isVarArgsMethod() || !(method.owner() instanceof Symbol.TypeSymbol owner)) { + return java.util.Optional.empty(); + } + long sameArity = (owner instanceof JTypeSymbol type ? type.membersNamed(method.name()) : owner.memberSymbols()).stream() + .filter(member -> member.isMethodSymbol() && member.name().equals(method.name()) && ((Symbol.MethodSymbol) member).parameterTypes().size() == arguments.size()) + .count(); + return sameArity == 1 ? java.util.Optional.of(method.parameterTypes().get(index)) : java.util.Optional.empty(); + } + + /** The declared return type of the method a return statement belongs to; none inside a lambda. */ + private static java.util.Optional returnedAs(Tree statement) { + Tree enclosing = statement.parent(); + while (enclosing != null && !(enclosing instanceof org.sonar.plugins.java.api.tree.MethodTree) && !(enclosing instanceof org.sonar.plugins.java.api.tree.LambdaExpressionTree) + && !(enclosing instanceof org.sonar.plugins.java.api.tree.ClassTree)) { + enclosing = enclosing.parent(); + } + if (enclosing instanceof org.sonar.plugins.java.api.tree.MethodTree method && method.returnType() != null) { + return java.util.Optional.of(method.returnType().symbolType()); + } + return java.util.Optional.empty(); + } + + /** The declared type of the variable the cast initializes or is assigned to. */ + private static java.util.Optional assignedTo(org.sonar.plugins.java.api.tree.TypeCastTree cast) { + Tree child = cast; + Tree parent = cast.parent(); + while (parent instanceof org.sonar.plugins.java.api.tree.ParenthesizedTree) { + child = parent; + parent = parent.parent(); + } + if (parent instanceof org.sonar.plugins.java.api.tree.VariableTree variable && variable.initializer() == child && !(variable.type() instanceof org.sonar.plugins.java.api.tree.VarTypeTree)) { + return java.util.Optional.of(variable.type().symbolType()); + } + if (parent instanceof AssignmentExpressionTree assignment && assignment.is(Tree.Kind.ASSIGNMENT) && assignment.expression() == child) { + return java.util.Optional.of(assignment.variable().symbolType()); + } + if (parent instanceof org.sonar.plugins.java.api.tree.Arguments arguments) { + return soleParameterType(arguments, child); + } + if (parent instanceof org.sonar.plugins.java.api.tree.ReturnStatementTree) { + return returnedAs(parent); + } + return java.util.Optional.empty(); + } + + /** + * A widening primitive cast on an operand is unnecessary when the operator promotes the operands to the same types without it + * (all casts of the expression are removed together). + */ + @Override + public void visitBinaryExpression(BinaryExpressionTree tree) { + ExpressionTree left = ExpressionUtils.skipParentheses(tree.leftOperand()); + ExpressionTree right = ExpressionUtils.skipParentheses(tree.rightOperand()); + boolean leftCast = isWideningPrimitiveCast(left); + boolean rightCast = isWideningPrimitiveCast(right); + if (leftCast || rightCast) { + String leftType = promotionInput(left, leftCast); + String rightType = promotionInput(right, rightCast); + if (leftType != null && rightType != null && sameOperandTypes(tree.kind(), leftType, rightType, left, right)) { + if (leftCast) { + add(ProblemKind.REDUNDANT_CAST, castMessage(left), left); + } + if (rightCast) { + add(ProblemKind.REDUNDANT_CAST, castMessage(right), right); + } + } + } + super.visitBinaryExpression(tree); + } + + private static String castMessage(ExpressionTree cast) { + return "Unnecessary cast from " + ((org.sonar.plugins.java.api.tree.TypeCastTree) cast).expression().symbolType().name() + " to " + cast.symbolType().name(); + } + + private static boolean isWideningPrimitiveCast(ExpressionTree tree) { + if (!(tree instanceof org.sonar.plugins.java.api.tree.TypeCastTree cast)) { + return false; + } + String from = cast.expression().symbolType().fullyQualifiedName(); + String to = cast.type().symbolType().fullyQualifiedName(); + return NUMERIC_RANK.containsKey(from) && NUMERIC_RANK.containsKey(to) && (from.equals(to) || isWidening(from, to)); + } + + private static boolean isWidening(String from, String to) { + if ("char".equals(to)) { + return false; + } + if ("char".equals(from)) { + return NUMERIC_RANK.get(to) >= NUMERIC_RANK.get("int"); + } + return NUMERIC_RANK.get(from) < NUMERIC_RANK.get(to); + } + + /** The type the operand has once its cast is dropped, or null when the operand is not a numeric primitive. */ + private static String promotionInput(ExpressionTree operand, boolean dropCast) { + Type type = dropCast ? ((org.sonar.plugins.java.api.tree.TypeCastTree) operand).expression().symbolType() : operand.symbolType(); + String name = type.fullyQualifiedName(); + return NUMERIC_RANK.containsKey(name) ? name : null; + } + + private static boolean sameOperandTypes(Tree.Kind kind, String leftWithout, String rightWithout, ExpressionTree left, ExpressionTree right) { + String leftWith = left.symbolType().fullyQualifiedName(); + String rightWith = right.symbolType().fullyQualifiedName(); + if (!NUMERIC_RANK.containsKey(leftWith) || !NUMERIC_RANK.containsKey(rightWith)) { + return false; + } + if (kind == Tree.Kind.LEFT_SHIFT || kind == Tree.Kind.RIGHT_SHIFT || kind == Tree.Kind.UNSIGNED_RIGHT_SHIFT) { + return unaryPromoted(leftWith).equals(unaryPromoted(leftWithout)) && unaryPromoted(rightWith).equals(unaryPromoted(rightWithout)); + } + return binaryPromoted(leftWith, rightWith).equals(binaryPromoted(leftWithout, rightWithout)); + } + + private static String unaryPromoted(String type) { + return NUMERIC_RANK.get(type) < NUMERIC_RANK.get("int") ? "int" : type; + } + + private static String binaryPromoted(String left, String right) { + String a = unaryPromoted(left); + String b = unaryPromoted(right); + return NUMERIC_RANK.get(a) >= NUMERIC_RANK.get(b) ? a : b; + } + + @Override + public void visitTryStatement(TryStatementTree tree) { + List caught = new ArrayList<>(); + for (CatchTree catchTree : tree.catches()) { + TypeTree parameterType = catchTree.parameter().type(); + List alternatives = parameterType instanceof UnionTypeTree union ? union.typeAlternatives() : List.of(parameterType); + for (TypeTree alternative : alternatives) { + Type type = alternative.symbolType(); + Type hiding = type.isUnknown() ? null : caught.stream().filter(type::isSubtypeOf).findFirst().orElse(null); + if (hiding != null) { + add(ProblemKind.MASKED_CATCH, "Unreachable catch block for " + type.name() + ". It is already handled by the catch block for " + hiding.name(), alternative); + } + } + alternatives.stream().map(TypeTree::symbolType).filter(type -> !type.isUnknown()).forEach(caught::add); + } + tries.add(tree); + super.visitTryStatement(tree); + } + + /** Flow analysis is not done for a unit that has unresolved names. */ + private void reportUnreachableCatches(JavaTree.CompilationUnitTreeImpl unit) { + String currentPackage = unit.packageDeclaration() == null ? "" : dotted(unit.packageDeclaration().packageName()); + boolean unresolved = identifiers.stream().anyMatch(identifier -> identifier.symbol().isUnknown()) + || unit.imports().stream().anyMatch(clause -> clause instanceof ImportTree tree && !isResolvable(tree, dotted(tree.qualifiedIdentifier()), currentPackage)); + if (!unresolved) { + tries.forEach(this::reportUnreachableCatches); + } + } + + /** A catch of a checked exception that nothing left over by the previous catches can reach. */ + private void reportUnreachableCatches(TryStatementTree tree) { + ThrownTypes body = new ThrownTypes(); + body.scanTry(tree.resourceList(), tree.block()); + if (body.unknown) { + return; + } + List remaining = new ArrayList<>(body.thrown); + for (CatchTree catchTree : tree.catches()) { + TypeTree parameterType = catchTree.parameter().type(); + List alternatives = parameterType instanceof UnionTypeTree union ? union.typeAlternatives() : List.of(parameterType); + List handled = new ArrayList<>(); + for (TypeTree alternative : alternatives) { + Type type = alternative.symbolType(); + if (type.isUnknown()) { + return; + } + handled.add(type); + if (isCheckedException(type) && remaining.stream().noneMatch(thrown -> thrown.isSubtypeOf(type) || type.isSubtypeOf(thrown))) { + add(ProblemKind.MASKED_CATCH, "Unreachable catch block for " + type.name() + ". Only more specific exceptions are thrown and handled by previous catch block(s)", alternative); + } + } + remaining.removeIf(thrown -> handled.stream().anyMatch(thrown::isSubtypeOf)); + } + } + + /** Neither unchecked nor a supertype of the unchecked ones. */ + private static boolean isCheckedException(Type type) { + return type.isClass() && type.isSubtypeOf("java.lang.Throwable") && !type.isSubtypeOf("java.lang.RuntimeException") && !type.isSubtypeOf("java.lang.Error") + && !type.is("java.lang.Exception") && !type.is("java.lang.Throwable"); + } + + /** The exception types the statements of a try body can throw, not looking inside lambdas and nested classes. */ + private static final class ThrownTypes extends BaseTreeVisitor { + final List thrown = new ArrayList<>(); + boolean unknown; + + void scanTry(List resources, Tree block) { + for (Tree resource : resources) { + scan(resource); + Type type = resource instanceof org.sonar.plugins.java.api.tree.VariableTree variable ? variable.type().symbolType() + : resource instanceof ExpressionTree expression ? expression.symbolType() : null; + addClose(type); + } + scan(block); + } + + private void addClose(Type type) { + if (type == null || type.isUnknown()) { + unknown = true; + return; + } + List candidates = new ArrayList<>(List.of(type)); + type.symbol().superTypes().forEach(candidates::add); + for (Type candidate : candidates) { + for (Symbol member : candidate.symbol().memberSymbols()) { + if (member instanceof Symbol.MethodSymbol method && "close".equals(method.name()) && method.parameterTypes().isEmpty()) { + addAll(method); + return; + } + } + } + unknown = true; + } + + private void addAll(Symbol.MethodSymbol method) { + if (method.isUnknown()) { + unknown = true; + return; + } + method.thrownTypes().forEach(this::add); + } + + private void add(Type type) { + if (type.isUnknown() || !type.isClass()) { + unknown = true; + } else { + thrown.add(type); + } + } + + @Override + public void visitMethodInvocation(org.sonar.plugins.java.api.tree.MethodInvocationTree tree) { + super.visitMethodInvocation(tree); + addAll(tree.methodSymbol()); + } + + @Override + public void visitNewClass(org.sonar.plugins.java.api.tree.NewClassTree tree) { + scan(tree.enclosingExpression()); + scan(tree.arguments()); + addAll(tree.methodSymbol()); + } + + @Override + public void visitThrowStatement(org.sonar.plugins.java.api.tree.ThrowStatementTree tree) { + super.visitThrowStatement(tree); + add(tree.expression().symbolType()); + } + + @Override + public void visitTryStatement(TryStatementTree tree) { + ThrownTypes inner = new ThrownTypes(); + inner.scanTry(tree.resourceList(), tree.block()); + unknown |= inner.unknown; + List caught = new ArrayList<>(); + tree.catches().forEach(catchTree -> { + TypeTree parameterType = catchTree.parameter().type(); + (parameterType instanceof UnionTypeTree union ? union.typeAlternatives() : List.of(parameterType)).forEach(alternative -> caught.add(alternative.symbolType())); + scan(catchTree.block()); + }); + inner.thrown.stream().filter(type -> caught.stream().noneMatch(type::isSubtypeOf)).forEach(thrown::add); + scan(tree.finallyBlock()); + } + + @Override + public void visitLambdaExpression(org.sonar.plugins.java.api.tree.LambdaExpressionTree tree) { + // not thrown by the enclosing statements + } + + @Override + public void visitMethodReference(org.sonar.plugins.java.api.tree.MethodReferenceTree tree) { + scan(tree.expression()); + } + + @Override + public void visitClass(org.sonar.plugins.java.api.tree.ClassTree tree) { + // a nested class has its own callables + } + } + + @Override + public void visitAssignmentExpression(AssignmentExpressionTree tree) { + if (tree.is(Tree.Kind.ASSIGNMENT)) { + Symbol target = assignedVariable(tree.variable()); + if (target != null && target.equals(assignedVariable(tree.expression()))) { + add(ProblemKind.ASSIGNMENT_HAS_NO_EFFECT, "The assignment to variable " + target.name() + " has no effect", tree); + } + } + super.visitAssignmentExpression(tree); + } + + /** The variable a simple name, {@code this.name} or {@code Type.name} designates. */ + private static Symbol assignedVariable(ExpressionTree tree) { + ExpressionTree expression = tree; + while (expression instanceof org.sonar.plugins.java.api.tree.ParenthesizedTree parenthesized) { + expression = parenthesized.expression(); + } + IdentifierTree name = null; + if (expression instanceof IdentifierTree identifier) { + name = identifier; + } else if (expression instanceof MemberSelectExpressionTree select) { + ExpressionTree qualifier = select.expression(); + if (qualifier instanceof IdentifierTree owner && ("this".equals(owner.name()) || owner.symbol().isTypeSymbol())) { + name = select.identifier(); + } + } + if (name == null || !name.symbol().isVariableSymbol() || name.symbol().isUnknown()) { + return null; + } + return name.symbol(); + } + + /** The names a Javadoc reference tag ({@code @link}, {@code @value}, {@code @see}, {@code @throws}) spells, as the compiler reads them. */ + private void collectJavadocNames(Tree tree) { + if (tree instanceof SyntaxToken token) { + for (SyntaxTrivia trivia : token.trivias()) { + if (trivia.comment().startsWith("/**") || trivia.comment().startsWith("///")) { + addJavadocNames(trivia.comment()); + } + } + return; + } + if (tree instanceof JavaTree javaTree && !javaTree.isLeaf()) { + for (Tree child : javaTree.getChildren()) { + if (child != null) { + collectJavadocNames(child); + } + } + } + } + + private void addJavadocNames(String comment) { + Matcher matcher = JAVADOC_REFERENCE.matcher(comment); + while (matcher.find()) { + addReferenceNames(matcher.group(1) != null ? matcher.group(1) : matcher.group(2)); + } + if (comment.startsWith("///")) { + Matcher link = MARKDOWN_LINK.matcher(comment); + while (link.find()) { + addReferenceNames(link.group(1)); + } + } + } + + private void addReferenceNames(String reference) { + Matcher word = JAVA_NAME.matcher(reference); + boolean first = true; + while (word.find()) { + String name = word.group(); + int start = word.start(); + if (first) { + javadocNames.add(name); + first = false; + } else if (reference.substring(0, start).contains("(")) { + javadocNames.add(name); + } + } + } + + private void reportUnusedImports(JavaTree.CompilationUnitTreeImpl unit) { + if (unit.moduleDeclaration() != null) { + // The compiler reports no unused import in a module declaration unit. + return; + } + Set seen = new HashSet<>(); + String currentPackage = unit.packageDeclaration() == null ? "" : dotted(unit.packageDeclaration().packageName()); + // Loads the imported types first, so that an on-demand import of their package is known to exist. + for (ImportClauseTree clause : unit.imports()) { + if (clause instanceof ImportTree importTree && !importTree.isStatic() && !dotted(importTree.qualifiedIdentifier()).endsWith(".*")) { + declaresImported(dotted(importTree.qualifiedIdentifier())); + } + } + for (ImportClauseTree clause : unit.imports()) { + if (!(clause instanceof ImportTree importTree)) { + continue; + } + String name = dotted(importTree.qualifiedIdentifier()); + String key = (importTree.isStatic() ? "static " : "") + name; + boolean duplicate = !seen.add(key); + if (isResolvable(importTree, name, currentPackage) && (duplicate || isOwnPackage(importTree, name, currentPackage) || !isUsed(importTree, name))) { + add(ProblemKind.UNUSED_IMPORT, "The import " + (name.endsWith(".*") ? name.substring(0, name.length() - 2) : name) + " is never used", importTree); + } + } + } + + private void declaresImported(String name) { + binaryName(name); + } + + /** Like the compiler, only an import that resolves can be reported as unused. */ + private boolean isResolvable(ImportTree importTree, String name, String currentPackage) { + if (importTree instanceof JavaTree.ImportTreeImpl impl && impl.isModule()) { + return true; + } + boolean onDemand = name.endsWith(".*"); + String qualifier = onDemand ? name.substring(0, name.length() - 2) : name; + if (onDemand && !importTree.isStatic() && (qualifier.equals(currentPackage) || sema.knowsPackage(qualifier))) { + return true; + } + return resolvesType(importTree.isStatic() && !onDemand ? qualifier.substring(0, Math.max(0, qualifier.lastIndexOf('.'))) : qualifier); + } + + private boolean resolvesType(String dotted) { + return binaryName(dotted) != null; + } + + /** The binary name of the type a dotted name denotes, trying each dot as a nesting boundary. */ + private String binaryName(String dotted) { + String candidate = dotted; + while (!candidate.isEmpty()) { + if (sema.declaresType(candidate)) { + return candidate; + } + int dot = candidate.lastIndexOf('.'); + if (dot < 0) { + return null; + } + candidate = candidate.substring(0, dot) + "$" + candidate.substring(dot + 1); + } + return null; + } + + /** The package's own types are imported implicitly, so such an import is never counted as used. */ + private static boolean isOwnPackage(ImportTree importTree, String name, String currentPackage) { + if (importTree.isStatic() || currentPackage.isEmpty()) { + return false; + } + String qualifier = name.endsWith(".*") ? name.substring(0, name.length() - 2) : name.substring(0, Math.max(0, name.lastIndexOf('.'))); + return (qualifier.equals(currentPackage) && !name.endsWith(".*")) || name.equals(currentPackage + ".*"); + } + + private boolean isUsed(ImportTree importTree, String name) { + if (importTree instanceof JavaTree.ImportTreeImpl impl && impl.isModule()) { + return true; + } + if (!name.endsWith(".*") && javadocNames.contains(name.substring(name.lastIndexOf('.') + 1))) { + return true; + } + boolean onDemand = name.endsWith(".*"); + String qualifier = onDemand ? name.substring(0, name.length() - 2) : name.substring(0, Math.max(0, name.lastIndexOf('.'))); + for (IdentifierTree identifier : identifiers) { + Symbol symbol = identifier.symbol(); + // a symbol found in the scope of the file does not consult the import + boolean inScope = !symbol.isUnknown() && symbol.declaration() != null && isInScope(symbol, identifier); + if (!inScope && uses(importTree, name, qualifier, identifier)) { + return true; + } + } + return false; + } + + /** + * A member of another type of the same file is in scope only through an import, one of an enclosing or inherited type is not. + * The annotations of a class are outside its scope, and a method looked up through an incomplete hierarchy may still come from an import. + */ + private static boolean isInScope(Symbol symbol, IdentifierTree identifier) { + if (!(symbol.owner() instanceof Symbol.TypeSymbol owner) || owner.isUnknown()) { + return true; + } + boolean incompleteHierarchy = false; + boolean inScope = false; + Tree previous = identifier; + for (Tree tree = identifier.parent(); tree != null; previous = tree, tree = tree.parent()) { + if (tree instanceof org.sonar.plugins.java.api.tree.ClassTree declared) { + incompleteHierarchy |= declared.superClass() != null && declared.superClass().symbolType().isUnknown(); + Symbol.TypeSymbol enclosing = declared.symbol(); + if (!isOutsideBody(declared, previous) && (enclosing.equals(owner) || enclosing.type().isSubtypeOf(owner.type().erasure()))) { + inScope = true; + } + } + } + return inScope && !(symbol.isMethodSymbol() && incompleteHierarchy); + } + + /** The annotations, type parameters and supertypes of a class are not part of its body, where its members are in scope. */ + private static boolean isOutsideBody(org.sonar.plugins.java.api.tree.ClassTree declared, Tree child) { + return child == declared.modifiers() || child == declared.typeParameters() || child == declared.superClass() + || child == declared.superInterfaces(); + } + + private boolean uses(ImportTree importTree, String name, String qualifier, IdentifierTree identifier) { + Symbol symbol = identifier.symbol(); + if (name.endsWith(".*")) { + return declaredIn(symbol, qualifier.replace('$', '.'), importTree.isStatic()); + } + if (!identifier.name().equals(name.substring(name.lastIndexOf('.') + 1))) { + return false; + } + if (symbol.isUnknown()) { + return true; + } + // a class named with a dollar sign is a top-level class, as written in the import, not a nested one + String dotted = name.replace('$', '.'); + return importTree.isStatic() ? isMemberOf(symbol, qualifier.replace('$', '.')) || (symbol.isTypeSymbol() && dottedType(symbol).equals(dotted)) : denotesType(symbol, dotted, identifier); + } + + /** A static import also brings in the members the named type inherits. */ + private boolean isMemberOf(Symbol symbol, String qualifier) { + if (!(symbol.owner() instanceof Symbol.TypeSymbol owner)) { + return false; + } + if (dottedType(owner).equals(qualifier)) { + return true; + } + String binary = binaryName(qualifier); + return binary != null && sema.getClassType(binary).isSubtypeOf(owner.type()); + } + + private static boolean denotesType(Symbol symbol, String name, IdentifierTree identifier) { + if (symbol.isTypeSymbol()) { + return dottedType(symbol).equals(name); + } + if (!(symbol.isMethodSymbol() && "".equals(symbol.name()))) { + return false; + } + if (symbol.owner() instanceof Symbol.TypeSymbol owner && dottedType(owner).equals(name)) { + return true; + } + Type written = identifier.symbolType(); + return written != null && !written.isUnknown() && written.erasure().fullyQualifiedName().replace('$', '.').equals(name); + } + + private static boolean declaredIn(Symbol symbol, String qualifier, boolean isStatic) { + if (symbol.isUnknown()) { + return false; + } + if (isStatic) { + if (symbol.isTypeSymbol()) { + String type = dottedType(symbol); + return type.startsWith(qualifier + ".") && type.indexOf('.', qualifier.length() + 1) < 0; + } + return symbol.owner() instanceof Symbol.TypeSymbol owner && dottedType(owner).equals(qualifier); + } + Symbol type = symbol; + if ("".equals(symbol.name())) { + type = symbol.owner(); + } + return type.isTypeSymbol() && !type.isUnknown() && dottedType(type).startsWith(qualifier + "."); + } + + private static String dottedType(Symbol symbol) { + return symbol.type().fullyQualifiedName().replace('$', '.'); + } + + private static String dotted(Tree tree) { + if (tree instanceof MemberSelectExpressionTree select) { + return dotted(select.expression()) + "." + select.identifier().name(); + } + return tree instanceof IdentifierTree identifier ? identifier.name() : ""; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/EffectivelyFinalVariables.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/EffectivelyFinalVariables.java new file mode 100644 index 00000000000..fdfc8c08abd --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/EffectivelyFinalVariables.java @@ -0,0 +1,93 @@ +/* + * 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.IdentityHashMap; +import java.util.List; +import java.util.Map; +import org.sonar.java.model.JavaTree; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.UnaryExpressionTree; +import org.sonar.plugins.java.api.tree.VariableTree; + +/** + * Marks the local variables and parameters that are never reassigned (JLS 4.12.4), as the compiler does. + * A variable declared without a value stays effectively final after one plain assignment. + */ +final class EffectivelyFinalVariables extends BaseTreeVisitor { + + private final Map assignments = new IdentityHashMap<>(); + private final List variables = new ArrayList<>(); + + private EffectivelyFinalVariables() { + } + + static void mark(JavaTree.CompilationUnitTreeImpl unit) { + EffectivelyFinalVariables visitor = new EffectivelyFinalVariables(); + visitor.scan(unit); + for (VariableTree variable : visitor.variables) { + if (variable.symbol() instanceof JVariableSymbol symbol) { + int[] counts = visitor.assignments.getOrDefault(symbol, new int[2]); + boolean unassigned = variable.initializer() == null && isLocalDeclaration(variable); + symbol.effectivelyFinal(counts[1] == 0 && counts[0] <= (unassigned ? 1 : 0)); + } + } + } + + private static boolean isLocalDeclaration(VariableTree variable) { + Tree parent = variable.parent(); + return parent != null && parent.is(Tree.Kind.BLOCK, Tree.Kind.CASE_GROUP, Tree.Kind.STATIC_INITIALIZER, Tree.Kind.INITIALIZER, Tree.Kind.FOR_STATEMENT); + } + + @Override + public void visitVariable(VariableTree tree) { + if (tree.symbol() instanceof JVariableSymbol symbol && (symbol.isLocalVariable() || symbol.isParameter())) { + variables.add(tree); + } + super.visitVariable(tree); + } + + @Override + public void visitAssignmentExpression(AssignmentExpressionTree tree) { + countAssignment(tree.variable(), tree.is(Tree.Kind.ASSIGNMENT) ? 0 : 1); + super.visitAssignmentExpression(tree); + } + + @Override + public void visitUnaryExpression(UnaryExpressionTree tree) { + if (tree.is(Tree.Kind.PREFIX_INCREMENT, Tree.Kind.PREFIX_DECREMENT, Tree.Kind.POSTFIX_INCREMENT, Tree.Kind.POSTFIX_DECREMENT)) { + countAssignment(tree.expression(), 1); + } + super.visitUnaryExpression(tree); + } + + private void countAssignment(ExpressionTree target, int slot) { + ExpressionTree expression = target; + while (expression instanceof org.sonar.plugins.java.api.tree.ParenthesizedTree parenthesized) { + expression = parenthesized.expression(); + } + if (expression instanceof IdentifierTree identifier) { + assignments.computeIfAbsent(identifier.symbol(), key -> new int[2])[slot]++; + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JInitializerBlockSymbol.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JInitializerBlockSymbol.java new file mode 100644 index 00000000000..1575d6452eb --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JInitializerBlockSymbol.java @@ -0,0 +1,216 @@ +/* + * 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 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.IdentifierTree; +import org.sonar.plugins.java.api.tree.MethodTree; + +/** + * Symbol type to represent initializer blocks. It's a type of method symbol and was introduced, so that variables + * defined inside an initializer block can have an owner other than the containing class. This is necessary to properly + * detect them as local variables. + */ +final class JInitializerBlockSymbol implements Symbol.MethodSymbol { + private final TypeSymbol owner; + private final boolean isStatic; + + public JInitializerBlockSymbol(TypeSymbol owner, boolean isStatic) { + this.owner = owner; + this.isStatic = isStatic; + } + + @Override + public MethodTree declaration() { + return null; + } + + @Override + public List parameterTypes() { + return Collections.emptyList(); + } + + @Override + public List declarationParameters() { + return Collections.emptyList(); + } + + @Override + public Symbol.TypeSymbol returnType() { + return TypeSymbol.UNKNOWN_TYPE; + } + + @Override + public List thrownTypes() { + return Collections.emptyList(); + } + + @Override + public List overriddenSymbols() { + return Collections.emptyList(); + } + + @Override + public Symbol owner() { + return owner; + } + + @Override + public Type type() { + return Type.UNKNOWN; + } + + @Override + public boolean isVariableSymbol() { + return false; + } + + @Override + public boolean isTypeSymbol() { + return false; + } + + @Override + public boolean isMethodSymbol() { + return true; + } + + @Override + public boolean isPackageSymbol() { + return false; + } + + @Override + public boolean isStatic() { + return isStatic; + } + + @Override + public boolean isFinal() { + return false; + } + + @Override + public boolean isEnum() { + return false; + } + + @Override + public boolean isInterface() { + return false; + } + + @Override + public boolean isAbstract() { + return false; + } + + @Override + public boolean isPublic() { + return false; + } + + @Override + public boolean isPrivate() { + return false; + } + + @Override + public boolean isProtected() { + return false; + } + + @Override + public boolean isPackageVisibility() { + return false; + } + + @Override + public boolean isDeprecated() { + return false; + } + + @Override + public boolean isVolatile() { + return false; + } + + @Override + public boolean isUnknown() { + return false; + } + + @Override + public SymbolMetadata metadata() { + return Symbols.EMPTY_METADATA; + } + + @Override + public TypeSymbol enclosingClass() { + return owner; + } + + @Override + public List usages() { + return Collections.emptyList(); + } + + @Override + public String name() { + return isStatic ? " (initializer block)" : " (initializer block)"; + } + + @Override + public String signature() { + return owner.name() + "." + name(); + } + + @Override + public boolean isOverridable() { + return false; + } + + @Override + public boolean isParametrizedMethod() { + return false; + } + + @Override + public boolean isDefaultMethod() { + return false; + } + + @Override + public boolean isSynchronizedMethod() { + return false; + } + + @Override + public boolean isVarArgsMethod() { + return false; + } + + @Override + public boolean isNativeMethod() { + return false; + } +} 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..6c7ba05baea --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JMethodSymbol.java @@ -0,0 +1,548 @@ +/* + * 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.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Collections; +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.SymbolMetadata; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.ArrayTypeTree; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.ParameterizedTypeTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +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 List parameterTypes = List.of(); + private TypeSymbol returnTypeSymbol = TypeSymbol.UNKNOWN_TYPE; + private boolean varArgs; + private boolean varArgsKnown; + private boolean lambda; + private boolean parametrized; + private final String signature; + @Nullable + private Integer returnTypeParameter; + private boolean returnsSelf; + @Nullable + private List parameterVariables; + @Nullable + private List declaredParameters; + private boolean declaredReturnLoaded; + @Nullable + private JsonObject declaredReturn; + 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 : JSema.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 lambda(boolean lambda) { + this.lambda = lambda; + } + + boolean isLambda() { + return lambda; + } + + boolean substitutes(List parameters, Type returned) { + return !returned.equals(returnTypeSymbol.type()) || !parameters.equals(parameterTypes); + } + + void parametrized(boolean parametrized) { + this.parametrized = parametrized; + } + + void returnTypeParameter(@Nullable Integer returnTypeParameter) { + this.returnTypeParameter = returnTypeParameter; + } + + @Nullable + Integer returnTypeParameter() { + return returnTypeParameter; + } + + void returnsSelf(boolean returnsSelf) { + this.returnsSelf = returnsSelf; + } + + boolean returnsSelf() { + return returnsSelf; + } + + void parameterVariables(List parameterVariables) { + this.parameterVariables = parameterVariables; + } + + @Nullable + List parameterVariables() { + return parameterVariables; + } + + void declaredParameters(List declaredParameters) { + this.declaredParameters = declaredParameters; + } + + @Nullable + List declaredParameters() { + return declaredParameters; + } + + void declaredReturn(@Nullable JsonObject declaredReturn) { + this.declaredReturnLoaded = true; + this.declaredReturn = declaredReturn; + } + + boolean declaredReturnLoaded() { + return declaredReturnLoaded; + } + + @Nullable + JsonObject declaredReturn() { + return declaredReturn; + } + + /** Whether the declared signature is written with a type variable of this method itself, which makes it a generic method. */ + private boolean declaresTypeVariable() { + if (id == null) { + return false; + } + String prefix = id + "<"; + if (mentionsVariable(returnTypeSymbol == null ? null : returnTypeSymbol.type(), prefix)) { + return true; + } + return parameterTypes.stream().anyMatch(type -> mentionsVariable(type, prefix)); + } + + private static boolean mentionsVariable(@Nullable Type type, String prefix) { + if (type == null) { + return false; + } + if (type.isArray()) { + return mentionsVariable(((Type.ArrayType) type).elementType(), prefix); + } + if (type instanceof JType jType && jType.typeVarId != null && jType.typeVarId.startsWith(prefix)) { + return true; + } + if (type instanceof JType jType && jType.element != null && mentionsVariable(jType.element, prefix)) { + return true; + } + return type.typeArguments().stream().anyMatch(argument -> mentionsVariable(argument, prefix)); + } + + /** + * A per-invocation view with substituted parameter and return types. Equality stays on the SemSitter id, + * so the view still denotes the same method as the declaration. + */ + JMethodSymbol withSignature(List parameterTypes, Type returnType) { + return withSignature(id, parameterTypes, returnType); + } + + /** The view of the functional method a lambda implements, with an identity of its own: two lambdas are never the same symbol. */ + JMethodSymbol lambdaView(String lambdaId) { + JMethodSymbol view = withSignature(lambdaId, parameterTypes, returnTypeSymbol.type()); + view.lambda = true; + return view; + } + + private JMethodSymbol withSignature(@Nullable String viewId, List parameterTypes, Type returnType) { + JMethodSymbol view = new JMethodSymbol(sema, viewId, name()); + view.owner(owner()); + view.addModifiers(modifiersCopy()); + view.parameterTypes = List.copyOf(parameterTypes); + view.parameterVariables = parameterVariables; + view.declaredParameters = declaredParameters; + view.declaredReturnLoaded = declaredReturnLoaded; + view.declaredReturn = declaredReturn; + view.returnTypeSymbol = returnType.symbol(); + view.varArgs = varArgs; + view.varArgsKnown = varArgsKnown; + view.lambda = lambda; + view.parametrized = parametrized || declaresTypeVariable(); + view.returnTypeParameter = returnTypeParameter; + view.returnsSelf = returnsSelf; + view.thrownTypes = thrownTypes; + view.unknown(isUnknown()); + view.deprecated(isDeprecated()); + view.descriptorSignature = signature(); + return view; + } + + private List modifiersCopy() { + List copy = new ArrayList<>(); + if (isPublic()) { + copy.add("public"); + } + if (isPrivate()) { + copy.add("private"); + } + if (isProtected()) { + copy.add("protected"); + } + if (isStatic()) { + copy.add("static"); + } + if (isFinal()) { + copy.add("final"); + } + if (hasModifier("abstract")) { + copy.add("abstract"); + } + if (hasModifier("default")) { + copy.add("default"); + } + if (hasModifier("native")) { + copy.add("native"); + } + if (hasModifier("synchronized")) { + copy.add("synchronized"); + } + return copy; + } + + @Override + public List parameterTypes() { + return parameterTypes; + } + + @Override + public List declarationParameters() { + if (declaration() instanceof MethodTree method && method.closeParenToken() != null) { + return method.parameters().stream().map(parameter -> (Symbol) parameter.symbol()).toList(); + } + List placeholders = new ArrayList<>(); + for (int i = 0; i < parameterTypes.size(); i++) { + placeholders.add(sema.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.projectThrown(id); + return served == null ? Collections.emptyList() : served; + } + return method.throwsClauses().stream().map(TypeTree::symbolType).toList(); + } + + @Override + public List overriddenSymbols() { + if (overridden == null) { + overridden = findOverridden(); + } + return overridden; + } + + private List findOverridden() { + if (!(owner() instanceof JTypeSymbol typeSymbol) || isUnknown() || isStatic() || isPrivate()) { + return List.of(); + } + List found = new ArrayList<>(); + Set visited = new HashSet<>(); + if (typeSymbol.isInterface()) { + match(found, sema.typeSymbol("java.lang.Object"), null); + visited.add("java.lang.Object"); + } + 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, TypeSymbol parent, @Nullable Type declaring) { + for (Symbol member : parent instanceof JTypeSymbol type ? type.membersNamed(name()) : parent.memberSymbols()) { + if (member.isMethodSymbol() && !member.isStatic() && !member.isPrivate() && name().equals(member.name()) && sameSignature((MethodSymbol) member, declaring)) { + found.add(withWrittenTypeArgument((MethodSymbol) member, declaring)); + return; + } + } + } + + /** + * A method returning a class type variable, seen through a supertype written with an annotated type argument + * ({@code Converter}), carries that annotation as the nullability of its result. + */ + private MethodSymbol withWrittenTypeArgument(MethodSymbol overridden, @Nullable Type declaring) { + if (declaring == null || !(overridden instanceof JMethodSymbol library)) { + return overridden; + } + Integer position = returnedClassVariable(library, declaring); + SymbolMetadata metadata = position == null ? null : writtenArgumentMetadata(declaring, position); + if (metadata == null) { + return overridden; + } + return (MethodSymbol) Proxy.newProxyInstance(MethodSymbol.class.getClassLoader(), new Class[] {MethodSymbol.class}, (proxy, method, arguments) -> { + if ("metadata".equals(method.getName()) && method.getParameterCount() == 0) { + return metadata; + } + if ("equals".equals(method.getName()) && method.getParameterCount() == 1) { + return proxy == arguments[0] || library.equals(arguments[0]); + } + try { + return method.invoke(library, arguments); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); + } + + /** The annotations of the type argument at {@code position} of {@code declaring}: as written in this class, or as a supertype states it. */ + @Nullable + private SymbolMetadata writtenArgumentMetadata(Type declaring, int position) { + if (owner() instanceof JTypeSymbol typeSymbol && typeSymbol.declaration() instanceof ClassTree classTree) { + List supertypes = new ArrayList<>(classTree.superInterfaces()); + if (classTree.superClass() != null) { + supertypes.add(classTree.superClass()); + } + for (TypeTree supertype : supertypes) { + if (supertype instanceof ParameterizedTypeTree parameterized && parameterized.symbolType().erasure().fullyQualifiedName().equals(declaring.erasure().fullyQualifiedName()) + && position < parameterized.typeArguments().size() + && parameterized.typeArguments().get(position) instanceof TypeTree argument && JSymbolMetadata.isAnnotatedType(argument)) { + return JSymbolMetadata.ofTypeTree(sema, argument); + } + } + } + if (owner() instanceof JTypeSymbol typeSymbol) { + List declared = sema.supertypeArgumentAnnotations(typeSymbol.type(), declaring, position); + if (!declared.isEmpty()) { + return JSymbolMetadata.ofDeclared(sema, declared); + } + } + return null; + } + + /** The position, among the type variables of its class, of the one the method returns. */ + @Nullable + private Integer returnedClassVariable(JMethodSymbol method, Type declaring) { + if (method.returnTypeParameter() != null) { + return method.returnTypeParameter(); + } + if (method.declaration() == null) { + return sema.returnedClassVariable(method, declaring); + } + if (method.declaration() instanceof MethodTree tree && tree.returnType() instanceof IdentifierTree returned + && method.owner() instanceof JTypeSymbol parent && parent.declaration() instanceof ClassTree parentClass) { + for (int i = 0; i < parentClass.typeParameters().size(); i++) { + if (parentClass.typeParameters().get(i).identifier().name().equals(returned.name())) { + return i; + } + } + } + return null; + } + + private boolean viaClassVariable(JMethodSymbol library, int index, Type declaring, String mine) { + Type argument = sema.classVariableArgument(library, index, declaring); + return argument != null && mine.equals(argument.erasure().fullyQualifiedName()); + } + + private boolean sameSignature(MethodSymbol other, @Nullable Type declaring) { + List theirs = other.parameterTypes(); + if (parameterTypes.size() != theirs.size()) { + return false; + } + for (int i = 0; i < parameterTypes.size(); i++) { + String mine = parameterTypes.get(i).erasure().fullyQualifiedName(); + boolean same = mine.equals(theirs.get(i).erasure().fullyQualifiedName()) + || (declaring != null && mine.equals(sema.asMemberOf(theirs.get(i), declaring).erasure().fullyQualifiedName())) + || (declaring != null && other instanceof JMethodSymbol library && viaClassVariable(library, i, declaring, mine)); + if (!same) { + return false; + } + } + return true; + } + + /** + * 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; + } + + 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('('); + parameterTypes.forEach(parameter -> out.append(descriptor(parameter))); + out.append(')'); + if ("".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('.', '/') + ";"; + }; + } + + @Override + public boolean isOverridable() { + Symbol owner = owner(); + return !isUnknown() && !(isPrivate() || isStatic() || isFinal() || (owner != null && owner.isFinal())); + } + + @Override + public boolean isParametrizedMethod() { + return !isUnknown() && (parametrized || (declaration() != null && !declaration().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.annotationDefault(this); + } + if (method.defaultValue() == null) { + return null; + } + Object value = JSymbolMetadata.TreeAnnotation.literal(sema, method.defaultValue()); + return value instanceof Object[] || !returnType().type().isArray() ? value : new Object[] {value}; + } + + @Override + public boolean isNativeMethod() { + return !isUnknown() && hasModifier("native"); + } +} 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/JProblem.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JProblem.java new file mode 100644 index 00000000000..de54cf62ec8 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JProblem.java @@ -0,0 +1,100 @@ +/* + * 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.Map; +import java.util.Objects; +import java.util.Set; +import org.sonar.plugins.java.api.diagnostics.Problem; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.tree.Tree; + +public class JProblem implements Problem { + + private static final String USE_ENABLE_PREVIEW = " Use --enable-preview to enable"; + private static final Map> KINDS = Map.of( + ProblemKind.UNUSED_IMPORT, Set.of(Tree.Kind.IMPORT), + ProblemKind.REDUNDANT_CAST, Set.of(Tree.Kind.TYPE_CAST, Tree.Kind.PARENTHESIZED_EXPRESSION), + ProblemKind.ASSIGNMENT_HAS_NO_EFFECT, Set.of(Tree.Kind.ASSIGNMENT), + ProblemKind.MASKED_CATCH, Set.of(Tree.Kind.IDENTIFIER, Tree.Kind.MEMBER_SELECT)); + private static final Set COMPILER_OPTIONS = Set.of( + "org.eclipse.jdt.core.compiler.problem.unusedImport", + "org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck", + "org.eclipse.jdt.core.compiler.problem.noEffectAssignment", + "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock"); + + private final String message; + private final ProblemKind type; + + JProblem(String message, ProblemKind type) { + this.type = type; + this.message = type == ProblemKind.PREVIEW_FEATURE_USED ? cleanMessage(message) : message; + } + + static JProblem undefinedType(String fqn) { + return new JProblem(fqn + " cannot be resolved to a type", ProblemKind.UNDEFINED_TYPE); + } + + @Override + public ProblemKind type() { + return type; + } + + static Set kinds(ProblemKind type) { + return KINDS.getOrDefault(type, Set.of()); + } + + public static Set compilerOptions() { + return COMPILER_OPTIONS; + } + + @Override + public String message() { + return message; + } + + @Override + public String toString() { + return message; + } + + private static String cleanMessage(String message) { + if (message.endsWith(USE_ENABLE_PREVIEW)) { + // Using --enable-preview is irrelevant in this context. + return message.substring(0, message.length() - USE_ENABLE_PREVIEW.length()); + } + return message; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof JProblem)) { + return false; + } + JProblem that = (JProblem) o; + return type == that.type && message.equals(that.message); + } + + @Override + public int hashCode() { + return Objects.hash(type, message); + } + +} 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..c54f8f446eb --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSema.java @@ -0,0 +1,2998 @@ +/* + * 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.JsonParseException; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +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.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import org.sonar.java.model.AnnotationValueImpl; +import org.sonar.java.model.Symbols; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.semantic.Sema; +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.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.FactValue; +import org.sonarsource.semsitter.wire.Prop; +import org.sonarsource.semsitter.wire.TypeRef; + +/** + * 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). + */ +public final class JSema implements Sema { + private static final String ANNOTATIONS = "annotations"; + private static final String EXTENDS = "extends"; + private static final String WILDCARD = "wildcard"; + private static final String MEMBERS = "members"; + private static final String THROWS = "throws"; + private static final int MEMBER_IDS_LIMIT = 200_000; + private static final Map MEMBER_IDS = new ConcurrentHashMap<>(); + private static final MemberId NOT_A_MEMBER = new MemberId("", "", null, false, -1, List.of()); + private static final String STATIC = "static"; + private static final String ABSTRACT = "abstract"; + private static final String RECORD = "record"; + private static final String ARRAY = "array"; + + + private static final Set PRIMITIVES = Set.of("byte", "short", "int", "long", "char", "float", "double", "boolean", "void"); + private static final Set OBJECT_METHODS = Set.of("equals/1", "hashCode/0", "toString/0"); + private static final Pattern LAMBDA_SEGMENTS = Pattern.compile("^(\\$lambda\\$[^$()]*\\(\\))+"); + + private final Map facts = new HashMap<>(); + private final Map dumpSymbols = new LinkedHashMap<>(); + private final Map typeInfos = new HashMap<>(); + private final Map> libraryAnnotations = new HashMap<>(); + private final Map> projectThrows = new HashMap<>(); + private final Map projectMemberFacts = new HashMap<>(); + private final Map projectVarArgs = new HashMap<>(); + private final Map> packageAnnotations = new HashMap<>(); + private final Map projectFieldTypes = new HashMap<>(); + private final Map symbols = new HashMap<>(); + private final Map annotationDefaults = new HashMap<>(); + private final Map placeholders = new HashMap<>(); + private final Map typesByName = new HashMap<>(); + private final Map rawTypes = new HashMap<>(); + private final Map binaryNames = new HashMap<>(); + private final Map sourceNames = new HashMap<>(); + final Map declarations = new HashMap<>(); + final Map> usages = new HashMap<>(); + private final Set undefinedTypes = new HashSet<>(); + private final Set creating = new HashSet<>(); + private final Set requestedTypes = new HashSet<>(); + private Function, JsonObject> typeLoader = names -> new JsonObject(); + private Function packageLoader = name -> null; + private boolean typesLoaded; + private final JSymbol unknownSymbol = new JVariableSymbol(this, null, "", "local"); + + public JSema() { + unknownSymbol.unknown(true); + } + + /** + * 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. + */ + public void ingestDocument(Document document) { + 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) { + binaryName(erase(id)); + } + } + } + for (String id : dumpSymbols.keySet()) { + createDumpSymbol(id); + } + for (String id : new ArrayList<>(dumpSymbols.keySet())) { + linkDumpSymbol(id); + } + } + + /** + * 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. + */ + private String binaryName(String id) { + String known = binaryNames.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 rest = close < 0 ? "" : LAMBDA_SEGMENTS.matcher(id.substring(close + 1)).replaceFirst(""); + 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) + "$" + name; + String local = binaryNames.get(localId); + if (local == null) { + String enclosing = binaryName(id.substring(0, hash)); + int index = 1; + while (sourceNames.containsKey(enclosing + "$" + index + name)) { + index++; + } + local = enclosing + "$" + index + name; + binaryNames.put(localId, local); + sourceNames.put(local, localId); + } + String binary = nested < 0 ? local : local + rest.substring(nested); + binaryNames.put(id, binary); + sourceNames.put(binary, id); + return binary; + } + + private String sourceName(String fqn) { + return sourceNames.getOrDefault(fqn, fqn); + } + + /** Whether the document of this file declares the symbol {@code id}. */ + boolean inDocument(String id) { + return dumpSymbols.containsKey(id); + } + + /** 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; + } + + /** Asks whether a package is declared, with null when the answer is unknown. */ + public void loadPackages(Function loader) { + packageLoader = loader; + } + + /** + * 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. + */ + public void loadTypes(Function, JsonObject> loader) { + typeLoader = loader; + Set names = referencedTypeNames(); + requestedTypes.addAll(names); + ingestTypes(loader.apply(names)); + markUndeclared(); + } + + /** 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() && !PRIMITIVES.contains(fqn) && fqn.indexOf('<') < 0 && !fqn.endsWith("[]") && !fqn.contains("::")) { + missing.add(fqn); + } + } + Set fresh = new HashSet<>(missing); + fresh.removeIf(name -> !requestedTypes.add(name)); + if (!fresh.isEmpty()) { + ingestTypes(typeLoader.apply(fresh)); + } + for (String fqn : missing) { + if (!typeInfos.containsKey(fqn)) { + typesByName.get(fqn).unknown(true); + undefinedTypes.add(JProblem.undefinedType(fqn)); + } + } + } + + /** 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 boolean noLibraries; + + /** Without any library, a method of a type nothing declares is unknown instead of named after its written owner. */ + public void noLibraries(boolean noLibraries) { + this.noLibraries = noLibraries; + } + + public void ingestTypes(JsonObject types) { + typesLoaded = true; + for (Map.Entry entry : types.entrySet()) { + JsonObject info = entry.getValue().getAsJsonObject(); + if (!FRAMEWORK_TYPES && "framework-db".equals(text(info, "origin"))) { + continue; + } + typeInfos.put(entry.getKey(), info); + 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); + } + applyTypeInfo(symbol, info); + } + } + + public 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; + } + + /** The declared type a document gives a symbol, or null when it gives none. */ + @Nullable + private static TypeRef typeFact(org.sonarsource.semsitter.wire.Symbol symbol) { + FactValue value = symbol.getFactsMap().get("type"); + return value != null && value.hasType() ? value.getType() : null; + } + + private 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() && !PRIMITIVES.contains(erased) && erased.indexOf(' ') < 0) { + names.add(erased); + } + } + + private 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()); + } + } + + public void declare(String id, Tree tree) { + declarations.put(id, tree); + } + + public 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() || "!Unknown!".equals(fullyQualifiedName)) { + return Type.UNKNOWN; + } + if ("".equals(fullyQualifiedName)) { + return JType.nullType(this); + } + if (fullyQualifiedName.endsWith("[]")) { + JType element = asJType(getClassType(fullyQualifiedName.substring(0, fullyQualifiedName.length() - 2))); + return (JType) arraySymbol(element).type(); + } + if (PRIMITIVES.contains(fullyQualifiedName)) { + return primitiveType(fullyQualifiedName); + } + typeSymbol(fullyQualifiedName); + return rawNamed(fullyQualifiedName); + } + + /** Nothing is held open per file; the instance is per sema so cleaners of different files stay distinct. */ + private final Runnable environmentCleaner = new Runnable() { + @Override + public void run() { + // no file or jar stays open + } + }; + + public Runnable getEnvironmentCleaner() { + return environmentCleaner; + } + + public Set undefinedTypes() { + return undefinedTypes; + } + + 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)) { + createDumpSymbol(id); + linkDumpSymbol(id); + return symbols.getOrDefault(id, unknownSymbol); + } + if (id.indexOf('#') >= 0) { + return createMember(id); + } + if (id.indexOf('<') >= 0) { + return 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); + JsonObject info = typeInfos.get(fqn); + if (info == null && typesLoaded && requestedTypes.add(fqn)) { + JsonObject loaded = typeLoader.apply(Set.of(fqn)); + if (loaded == null) { + return created; + } + ingestTypes(loaded); + if (typeInfos.containsKey(fqn)) { + return created; + } + } + if (info != null) { + applyTypeInfo(created, info); + } else if (typesLoaded && !isWellKnown(fqn)) { + created.unknown(true); + undefinedTypes.add(JProblem.undefinedType(fqn)); + } + return created; + } + + private static boolean isWellKnown(String fqn) { + return "java.lang.Object".equals(fqn) || "java.lang.Cloneable".equals(fqn) || "java.io.Serializable".equals(fqn); + } + + Symbol.TypeSymbol arraySymbol(JType element) { + String name = element.fullyQualifiedName() + "[]"; + JTypeSymbol found = typesByName.get(name); + if (found != null) { + return found; + } + JTypeSymbol symbol = new JTypeSymbol(this, name, element.name() + "[]", false); + symbol.elementFqn(element.fullyQualifiedName()); + symbol.owner(Symbol.ROOT_PACKAGE); + symbol.type(JType.array(this, element)); + typesByName.put(name, symbol); + return symbol; + } + + Symbol.TypeSymbol primitiveSymbol(String name) { + JTypeSymbol found = typesByName.get(name); + if (found != null) { + return found; + } + JTypeSymbol symbol = new JTypeSymbol(this, name, name, false); + symbol.owner(Symbol.ROOT_PACKAGE); + symbol.type(primitiveType(name)); + typesByName.put(name, symbol); + return symbol; + } + + List annotationNames(@Nullable String id) { + return declaredAnnotations(id).stream().map(DeclaredAnnotation::name).toList(); + } + + List declaredAnnotations(@Nullable String id) { + if (id == null) { + return List.of(); + } + List typed = libraryAnnotations.get(id); + if (typed != null && !typed.isEmpty()) { + return typed; + } + Fact fact = facts.get(id); + return fact == null ? List.of() : fact.getAnnotationsList().stream().map(name -> new DeclaredAnnotation(erase(name), List.of(), false)).toList(); + } + + /** 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 : projectThrows.get(id); + return names == null ? null : names.stream().map(this::typeFromName).toList(); + } + + /** The typed annotations and thrown types of the project members of a {@code types} answer. */ + private void registerProjectMembers(JsonObject info) { + if (!"project".equals(text(info, "origin")) || !(info.get(MEMBERS) instanceof JsonArray members)) { + return; + } + for (JsonElement element : members) { + if (!(element instanceof JsonObject member) || !(member.get("id") instanceof JsonPrimitive memberId)) { + continue; + } + List spellings = new ArrayList<>(strings(member, "useIds")); + spellings.add(memberId.getAsString()); + List annotations = readAnnotations(member); + for (String id : spellings) { + if (!annotations.isEmpty()) { + libraryAnnotations.put(id, annotations); + } + registerParameterAnnotations(id, member); + if (member.get(THROWS) instanceof JsonArray) { + projectThrows.put(id, strings(member, THROWS)); + } + if (member.get("varargs") instanceof JsonPrimitive varArgs && varArgs.isBoolean()) { + projectVarArgs.put(id, varArgs.getAsBoolean()); + } + if (member.get("facts") instanceof JsonObject memberFact) { + projectMemberFacts.computeIfAbsent(id, key -> fact(memberFact)); + } + if (member.get("declaredType") instanceof JsonObject declared && (declared.get("args") instanceof JsonArray || "typevar".equals(text(declared, "kind")))) { + projectFieldTypes.putIfAbsent(id, declared); + } + } + } + } + + /** The graph fact a {@code types} answer gives a project member, in the shape a document gives it. */ + private static Fact fact(JsonObject json) { + Fact.Builder fact = Fact.newBuilder() + .setKind(Objects.requireNonNullElse(text(json, "kind"), "")) + .setParent(Objects.requireNonNullElse(text(json, "parent"), "")) + .addAllExtends(strings(json, EXTENDS)) + .addAllImplements(strings(json, "implements")) + .addAllReturns(strings(json, "returns")) + .addAllType(strings(json, "type")) + .addAllParams(strings(json, "params")) + .addAllAnnotations(strings(json, 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(); + } + + /** Annotations written directly on the parameters of a method, as the member's type-annotation facts tell them. */ + private void registerParameterAnnotations(String methodId, JsonObject member) { + if (!(member.get("facts") instanceof JsonObject facts && facts.get("props") instanceof JsonObject props)) { + return; + } + for (String encoded : strings(props, "type_annotation_values")) { + JsonElement parsed; + try { + parsed = JsonParser.parseString(encoded); + } catch (JsonParseException e) { + continue; + } + if (!(parsed instanceof JsonArray entries)) { + continue; + } + for (JsonElement entry : entries) { + if (entry instanceof JsonObject annotation && "param".equals(text(annotation, "on")) && annotation.get("path") instanceof JsonArray path && path.isEmpty() + && annotation.get("index") instanceof JsonPrimitive index && text(annotation, "id") != null) { + libraryAnnotations.computeIfAbsent(parameterKey(methodId, index.getAsInt()), key -> new ArrayList<>()) + .add(new DeclaredAnnotation(text(annotation, "id"), List.of())); + } + } + } + } + + private static String parameterKey(String methodId, int index) { + return methodId + "@param" + index; + } + + /** Annotations and deprecation a {@code types} answer gives a library type or member. */ + private void libraryAnnotations(JSymbol symbol, String id, 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()) { + libraryAnnotations.putIfAbsent(parameterKey(id, i), onParameter); + } + } + } + List annotations = readAnnotations(info); + if (annotations.isEmpty()) { + return; + } + libraryAnnotations.put(id, annotations); + if (annotations.stream().anyMatch(annotation -> "java.lang.Deprecated".equals(annotation.name()))) { + symbol.deprecated(true); + } + } + + /** The annotations of the package {@code name}, from its compiled {@code package-info}. */ + List packageAnnotations(String name) { + if (!typesLoaded) { + return List.of(); + } + List cached = packageAnnotations.get(name); + if (cached == null) { + String key = name + ".package-info"; + JsonObject loaded = typeLoader.apply(Set.of(key)); + cached = loaded != null && loaded.get(key) instanceof JsonObject info ? readAnnotations(info) : List.of(); + packageAnnotations.put(name, cached); + } + return cached; + } + + /** Annotations written on the outermost type of a field or return type are annotations of the member. */ + private List readAnnotations(JsonObject info) { + List annotations = new ArrayList<>(readAnnotationList(info.get(ANNOTATIONS))); + if (info.get("typeAnnotations") instanceof 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); + } + } + } + } + } + return annotations; + } + + private List readAnnotationList(@Nullable JsonElement list) { + if (list == null || !list.isJsonArray()) { + return List.of(); + } + List annotations = new ArrayList<>(); + for (JsonElement element : list.getAsJsonArray()) { + 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 readAnnotationElement(JsonObject value) { + String kind = text(value, "kind"); + JsonElement raw = value.get("value"); + if (kind == null) { + return null; + } + return switch (kind) { + case "boolean" -> Boolean.valueOf(raw != null && raw.isJsonPrimitive() && raw.getAsBoolean()); + case "byte" -> raw == null || !raw.isJsonPrimitive() ? null : Byte.valueOf(raw.getAsByte()); + case "short" -> raw == null || !raw.isJsonPrimitive() ? null : Short.valueOf(raw.getAsShort()); + case "int" -> raw == null || !raw.isJsonPrimitive() ? null : Integer.valueOf(raw.getAsInt()); + case "long" -> raw == null || !raw.isJsonPrimitive() ? null : Long.valueOf(raw.getAsLong()); + case "float" -> raw == null || !raw.isJsonPrimitive() ? null : Float.valueOf(raw.getAsFloat()); + case "double" -> raw == null || !raw.isJsonPrimitive() ? null : Double.valueOf(raw.getAsDouble()); + case "char" -> raw == null || !raw.isJsonPrimitive() ? null : Character.valueOf((char) raw.getAsInt()); + case "string" -> raw == null || !raw.isJsonPrimitive() ? null : raw.getAsString(); + case "class" -> raw == null || !raw.isJsonPrimitive() ? null : typeSymbol(erase(raw.getAsString())); + case "enum" -> enumConstant(text(value, "type"), text(value, "const")); + case "array" -> readAnnotationArray(raw); + case "annotation" -> raw != null && raw.isJsonObject() ? text(raw.getAsJsonObject(), "name") : null; + 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(); + } + + @Nullable + private 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 (symbols.get(id) instanceof Symbol.VariableSymbol variable) { + return variable; + } + JTypeSymbol type = ownerName.isEmpty() ? null : typeSymbol(ownerName); + JVariableSymbol created = new JVariableSymbol(this, id, constName, "enum_member"); + if (type != null) { + created.owner(type); + created.type(type.type()); + } + created.addModifiers(List.of("public", "static", "final")); + symbols.put(id, created); + return created; + } + + /** + * Return type of a call. A JDK member can name the class type parameter its erased return + * stands for ({@code List.get} returns {@code E}), which is taken from the receiver. + */ + Symbol receiverSymbol(Symbol.TypeSymbol type, String name, Type receiverType) { + String id = (type instanceof JSymbol symbol && symbol.id != null ? symbol.id : type.name()) + "#" + name; + JSymbol found = symbols.get(id); + if (found != null) { + return found; + } + JVariableSymbol variable = new JVariableSymbol(this, id, name, "field"); + variable.owner(type); + variable.type(receiverType); + variable.addModifiers(List.of("final")); + variable.receiver(true); + symbols.put(id, variable); + return variable; + } + + /** + * The type an invocation of {@code method} evaluates to. A self-typed method returns the receiver, or a + * capture of it when the receiver leaves its own type argument as a wildcard. + */ + Type invocationReturn(JMethodSymbol method, @Nullable Type receiver, List arguments) { + if (receiver != null && receiver.isArray() && "clone".equals(method.name()) && arguments.isEmpty()) { + return receiver; + } + Type result = invocationReturnType(method, receiver, arguments); + return withEnclosingArguments(method, receiver, result); + } + + /** The inner class a member of a parameterized class returns keeps the arguments of its enclosing class. */ + private Type withEnclosingArguments(JMethodSymbol method, @Nullable Type receiver, Type result) { + if (receiver == null || method.isStatic() || !(result instanceof JType inner) || !inner.isClass() || inner.isParameterized() || method.owner().type() == null) { + return result; + } + String ownerFqn = method.owner().type().erasure().fullyQualifiedName(); + if (!inner.fullyQualifiedName().startsWith(ownerFqn + "$") && !inner.fullyQualifiedName().startsWith(ownerFqn + ".")) { + return result; + } + Type declaring = asSuperType(receiver, ownerFqn, new HashSet<>()); + return declaring instanceof JType enclosing && enclosing.isParameterized() ? inner.withOuter(enclosing) : result; + } + + private Type invocationReturnType(JMethodSymbol method, @Nullable Type receiver, List arguments) { + Integer index = method.returnTypeParameter(); + if (method.returnsSelf() && receiver instanceof JType returned && returned.isCapture()) { + return returned; + } + if (receiver instanceof JType captured && captured.isCapture() && captured.element != null && captured.element.isClass() && !method.isStatic()) { + // a member of a capture is a member of its bound + return invocationReturnType(method, captured.element, arguments); + } + Type declaring = index == null || receiver == null ? null : declaringType(method, receiver); + if (declaring != null && declaring.isParameterized() && declaring.typeArguments().size() > index) { + Type argument = declaring.typeArguments().get(index); + if (method.returnsSelf() && argument instanceof JType captured && captured.isCapture() && receiver instanceof JType self && self.isClass()) { + return JType.capture(this, self); + } + if (!argument.isTypeVar()) { + return argument; + } + } + if (method.returnsSelf() && receiver instanceof JType returned && returned.isClass()) { + boolean wildcard = returned.typeArguments().stream().anyMatch(argument -> argument instanceof JType type && type.isCapture()); + return wildcard ? JType.capture(this, returned) : returned; + } + JsonObject declaredReturn = declaredReturn(method); + if (declaredReturn != null) { + Map classSubstitution = receiver == null ? Map.of() : classSubstitution(method, receiver); + Map substitution = new HashMap<>(methodSubstitution(method, arguments)); + substitution.putAll(classSubstitution); + if (!substitution.isEmpty() || method.isStatic()) { + JType substituted = typeFromFact(declaredReturn, substitution, true); + boolean leaks = classSubstitution.isEmpty() ? mentionsTypeVariable(substituted) : mentionsMethodTypeVariable(method, substituted); + if (!substituted.isUnknown() && !leaks) { + return substituted; + } + } + } + if (declaredReturn != null && !method.isStatic() && method.declaration() == null) { + // a library method with no type variables in play still returns the type arguments its signature spells out + JType plain = typeFromFact(declaredReturn, Map.of(), true); + if (!plain.isUnknown() && plain.isParameterized() && !mentionsTypeVariable(plain) + && plain.args.stream().noneMatch(argument -> argument.isCapture() || argument.isWildcard())) { + return plain; + } + } + Type declared = method.returnType().type(); + if ((declared == null || declared.isUnknown()) && declaredReturn != null) { + // the declaration comes later in the file than this call + JType plain = typeFromFact(declaredReturn, Map.of(), true); + if (!plain.isUnknown() && !mentionsMethodTypeVariable(method, plain)) { + return plain; + } + } + return declared == null ? Type.UNKNOWN : declared; + } + + /** The erased return type of an instance method of a generic class called on a raw receiver, or null when it does not apply. */ + @Nullable + Type rawReturn(JMethodSymbol method) { + JsonObject declaredReturn = declaredReturn(method); + if (declaredReturn == null || method.isStatic() || !hasClassTypeVariables(method)) { + return null; + } + JType plain = typeFromFact(declaredReturn, Map.of(), true); + if (plain.isTypeVar() && !method.returnType().type().isUnknown()) { + // the descriptor erases a type variable to its bound + return method.returnType().type(); + } + return plain.isUnknown() ? null : plain.erasure(); + } + + private boolean hasClassTypeVariables(JMethodSymbol method) { + JsonObject info = typeInfos.get(sourceName(method.owner().type().erasure().fullyQualifiedName())); + return info != null && !strings(info, "typeVars").isEmpty(); + } + + /** + * The thrown types of a call when the method throws a type variable, taken from the arguments the variable is + * inferred from, or null when the erased thrown types stand. + */ + @Nullable + List invocationThrown(JMethodSymbol method, @Nullable Type receiver, List arguments) { + JsonObject member = method.isUnknown() ? null : lookupGenericMember(method); + if (member == null || !(member.get("throwsTypes") instanceof JsonArray facts) || facts.isEmpty()) { + return null; + } + Map substitution = new HashMap<>(methodSubstitution(method, arguments)); + if (receiver != null) { + substitution.putAll(classSubstitution(method, receiver)); + } + List erased = method.thrownTypes(); + List result = new ArrayList<>(); + boolean changed = false; + for (int i = 0; i < facts.size(); i++) { + Type fallback = i < erased.size() ? erased.get(i) : Type.UNKNOWN; + Type inferred = facts.get(i) instanceof JsonObject fact && "typevar".equals(text(fact, "kind")) ? typeFromFact(fact, substitution, true) : null; + if (inferred == null || inferred.isUnknown() || mentionsTypeVariable(inferred)) { + result.add(fallback); + } else { + result.add(inferred); + changed = true; + } + } + return changed ? result : null; + } + + /** Maps the type variables of {@code method} itself to the arguments they are inferred from. */ + private Map methodSubstitution(JMethodSymbol method, List arguments) { + JsonObject member = arguments.isEmpty() && explicitTypeArguments.isEmpty() ? null : lookupGenericMember(method); + if (member == null || !(member.get("typeVars") instanceof JsonArray names)) { + return Map.of(); + } + List variables = parameterVariables(method); + Map substitution = new HashMap<>(); + for (int i = 0; i < names.size(); i++) { + Type inferred = methodArgument(variables, "m" + i, arguments); + if (inferred != null && !inferred.isUnknown()) { + substitution.put(names.get(i).getAsString(), inferred); + } + } + Set own = new HashSet<>(); + names.forEach(name -> own.add(name.getAsString())); + List declared = declaredParameters(method); + for (int i = 0; i < declared.size() && i < arguments.size(); i++) { + bindFromType(declared.get(i), arguments.get(i), own, substitution); + } + return substitution; + } + + /** + * The type {@code method} returns when the type its call is passed as fixes the type variables of the + * method, or null when they stay open. + */ + @Nullable + Type targetedReturn(JMethodSymbol method, Type target) { + JsonObject member = lookupGenericMember(method); + JsonObject declared = declaredReturn(method); + if (member == null || declared == null || !(member.get("typeVars") instanceof JsonArray names) || names.isEmpty()) { + return null; + } + Set own = new HashSet<>(); + names.forEach(name -> own.add(name.getAsString())); + Map bound = new HashMap<>(); + bindReturnToTarget(declared, target, own, bound); + if (bound.isEmpty()) { + return null; + } + JType result = typeFromFact(declared, bound); + return result.isUnknown() || mentionsTypeVariable(result) ? null : result; + } + + /** + * The result of a call that returns a bare method type variable, such as {@code Stream.collect(collector)}, when + * the type it is passed as takes a supertype of the element where the result carries it: a collector factory leaves + * its element free, so {@code Collection} fixes the result of a stream of {@code String} to + * {@code List}. Null when the result stands. + */ + @Nullable + Type retargetedElement(JMethodSymbol method, Type receiver, Type returned, Type target) { + JsonObject declared = declaredReturn(method); + JsonObject member = method.isUnknown() ? null : lookupGenericMember(method); + if (declared == null || member == null || !"typevar".equals(text(declared, "kind")) + || !(receiver instanceof JType owner) || owner.args.isEmpty() + || !(returned instanceof JType result) || !result.isParameterized() || !(target instanceof JType wantedType) || !wantedType.isParameterized()) { + return null; + } + JType element = owner.args.get(0); + if (element.isWildcard() || element.isUnknown() || element.isParameterized() || !element.isClass()) { + return null; + } + int open = -1; + for (int i = 0; i < result.args.size(); i++) { + if (result.args.get(i).fullyQualifiedName().equals(element.fullyQualifiedName())) { + if (open >= 0) { + return null; + } + open = i; + } + } + Type aligned = open < 0 ? null : asSuperType(result, wantedType.erasure().fullyQualifiedName(), new HashSet<>()); + if (aligned == null || !aligned.isParameterized() || aligned.typeArguments().size() != wantedType.args.size()) { + return null; + } + for (int k = 0; k < wantedType.args.size(); k++) { + JType wanted = wantedType.args.get(k); + if (aligned.typeArguments().get(k).fullyQualifiedName().equals(element.fullyQualifiedName()) + && !wanted.isWildcard() && !wanted.isUnknown() && !wanted.isParameterized() && wanted.isClass() + && !wanted.fullyQualifiedName().equals(element.fullyQualifiedName()) && element.isSubtypeOf(wanted)) { + List arguments = new ArrayList<>(result.args); + arguments.set(open, wanted); + return JType.named(this, result.erasure().fullyQualifiedName(), arguments); + } + } + return null; + } + + /** + * The functional interface {@code parameter} with only the type argument its method returns known, as the type a + * function that produces {@code produced} has there, or null when {@code parameter} is not such an interface. + */ + @Nullable + Type functionProducing(Type parameter, Type produced) { + if (!(parameter instanceof JType declared) || !declared.isParameterized() || produced.isUnknown() || produced.isTypeVar() || mentionsTypeVariable(produced)) { + return null; + } + JMethodSymbol functional = functionalMethod(declared); + Integer position = functional == null ? null : returnedClassVariable(functional, declared); + if (position == null || position >= declared.args.size()) { + return null; + } + List arguments = new ArrayList<>(); + for (int i = 0; i < declared.args.size(); i++) { + arguments.add(i == position ? asJType(produced.isPrimitive() ? produced.primitiveWrapperType() : produced) : JType.unknown(this)); + } + return JType.inferred(this, declared.erasure().fullyQualifiedName(), arguments); + } + + /** Whether {@code method} returns a type variable, as the descriptor erases it or as its source declares it. */ + boolean returnsClassVariable(JMethodSymbol method) { + JsonObject returned = method.isUnknown() ? null : declaredReturn(method); + Type declared = method.returnType().type(); + return returned == null ? declared != null && declared.isTypeVar() : "typevar".equals(text(returned, "kind")); + } + + /** + * What {@code Type::method} yields when the method returns a class type variable, read from the first + * parameter of {@code function}, the receiver it is applied to; null when that is not known. + */ + @Nullable + Type unboundReferenceResult(JMethodSymbol method, Type function) { + JMethodSymbol functional = functionalMethod(function); + if (method.isStatic() || !returnsClassVariable(method) || functional == null || declaresTypeVariables(method, false)) { + return null; + } + List parameters = invocationParameters(functional, groundType(function), List.of()); + if (parameters.isEmpty() || method.owner().type() == null) { + return null; + } + Type receiver = groundType(parameters.get(0)); + Type declaring = receiver.isUnknown() ? null : asSuperType(receiver, method.owner().type().erasure().fullyQualifiedName(), new HashSet<>()); + if (declaring == null || !declaring.isParameterized()) { + return null; + } + Type result = invocationReturn(method, declaring, List.of()); + return result.isUnknown() || result.isTypeVar() ? null : result; + } + + /** + * The parameter types of {@code method} when the type its call is passed as fixes the type variables of the + * method, or null when they stay open. + */ + @Nullable + List targetedParameters(JMethodSymbol method, Type target) { + JsonObject member = lookupGenericMember(method); + JsonObject declared = declaredReturn(method); + if (member == null || declared == null || !(member.get("typeVars") instanceof JsonArray names) || names.isEmpty()) { + return null; + } + Set own = new HashSet<>(); + names.forEach(name -> own.add(name.getAsString())); + Map bound = new HashMap<>(); + bindReturnToTarget(declared, target, own, bound); + List parameters = declaredParameters(method); + if (bound.isEmpty() || parameters.isEmpty()) { + return null; + } + List result = new ArrayList<>(); + for (JsonObject parameter : parameters) { + JType type = typeFromFact(parameter, bound); + result.add(type.isUnknown() || mentionsTypeVariable(type) ? Type.UNKNOWN : type); + } + return result; + } + + /** + * Binds the type variables a declared return type names from the type the call is passed as. The target may be a + * supertype of the declared type: its arguments are read through the supertype of the declared type it names. + */ + private void bindReturnToTarget(JsonObject declared, Type target, Set variables, Map bound) { + bindFromType(declared, target, variables, bound); + if (!bound.isEmpty() || !(target instanceof JType expected) || !expected.isParameterized() || declared.get("args") == null) { + return; + } + JType written = typeFromFact(declared); + Type aligned = written.isParameterized() ? asSuperType(written, expected.erasure().fullyQualifiedName(), new HashSet<>()) : null; + if (aligned == null || !aligned.isParameterized() || aligned.typeArguments().size() != expected.args.size()) { + return; + } + for (int i = 0; i < expected.args.size(); i++) { + Type argument = aligned.typeArguments().get(i); + JType given = expected.args.get(i); + if (argument.isTypeVar() && variables.contains(argument.name()) && !given.isWildcard() && !given.isUnknown()) { + bound.putIfAbsent(argument.name(), given); + } + } + } + + /** + * Binds the type variables of {@code variables} that the declared type {@code declared} names to the types + * {@code actual} gives them at the same position. Open type variables and unbounded wildcards bind nothing. + */ + private void bindFromType(JsonObject declared, Type actual, Set variables, Map bound) { + Type known = actual; + while (known instanceof JType wildcard && wildcard.isWildcard()) { + JType ground = wildcard.groundType(); + known = ground == wildcard.element && !ground.is("java.lang.Object") ? JType.capture(this, ground) : ground; + } + if (known.isUnknown() || known.isNullType() || known.isTypeVar() || (actual != known && known.is("java.lang.Object"))) { + return; + } + String kind = text(declared, "kind"); + if ("typevar".equals(kind)) { + String id = text(declared, "id"); + if (variables.contains(id)) { + bound.putIfAbsent(id, known.isPrimitive() ? known.primitiveWrapperType() : known); + } + } else if (WILDCARD.equals(kind)) { + JsonObject limit = declared.get("super") instanceof JsonObject lower ? lower : declared.get("extends") instanceof JsonObject upper ? upper : null; + if (limit != null) { + bindFromType(limit, known, variables, bound); + } + } else if (ARRAY.equals(kind) && declared.get("elem") instanceof JsonObject element && known instanceof Type.ArrayType array) { + bindFromType(element, array.elementType(), variables, bound); + } else if (declared.get("args") instanceof JsonArray arguments && !arguments.isEmpty() && text(declared, "id") != null) { + Type aligned = asSuperType(known, erase(text(declared, "id")), new HashSet<>()); + if (aligned == null || !aligned.isParameterized() || aligned.typeArguments().size() != arguments.size()) { + return; + } + for (int i = 0; i < arguments.size(); i++) { + if (arguments.get(i) instanceof JsonObject argument) { + bindFromType(argument, aligned.typeArguments().get(i), variables, bound); + } + } + } + } + + private static boolean mentionsTypeVariable(Type type) { + return mentionsTypeVariable(type, name -> true); + } + + private boolean mentionsMethodTypeVariable(JMethodSymbol method, Type type) { + JsonObject member = lookupGenericMember(method); + if (member == null || !(member.get("typeVars") instanceof JsonArray names) || names.isEmpty()) { + return false; + } + Set own = new HashSet<>(); + names.forEach(name -> own.add(name.getAsString())); + return mentionsTypeVariable(type, own::contains); + } + + private static boolean mentionsTypeVariable(Type type, Predicate variable) { + if (type.isTypeVar()) { + return variable.test(type.name()); + } + if (type.isArray()) { + return mentionsTypeVariable(((Type.ArrayType) type).elementType(), variable); + } + return type.isParameterized() && type.typeArguments().stream().anyMatch(argument -> mentionsTypeVariable(argument, variable)); + } + + /** {@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)); + } + + /** The type of {@code field} read through {@code receiver}: the owner's type variables take the receiver's type arguments. */ + Type fieldTypeOn(Symbol.VariableSymbol field, @Nullable Type receiver) { + Type declared = field.type(); + if (!(declared instanceof JType type) || receiver == null || field.isStatic() || !(field.owner() instanceof Symbol.TypeSymbol owner) || owner.type() == null) { + return declared; + } + String ownerFqn = owner.type().erasure().fullyQualifiedName(); + JsonObject info = typeInfos.get(sourceName(ownerFqn)); + List names = info == null ? List.of() : strings(info, "typeVars"); + Type declaring = names.isEmpty() ? null : asSuperType(receiver, ownerFqn, new HashSet<>()); + if (declaring == null || declaring.typeArguments().isEmpty()) { + return declared; + } + Map substitution = new HashMap<>(); + for (int i = 0; i < names.size() && i < declaring.typeArguments().size(); i++) { + substitution.put(names.get(i), declaring.typeArguments().get(i)); + } + return type.substitute(substitution); + } + + /** The supertype of {@code receiver} that declares {@code method}, with the receiver's type arguments applied. */ + @Nullable + private Type declaringType(JMethodSymbol method, Type receiver) { + Type owner = method.owner().type(); + if (owner == null || owner.isUnknown()) { + return receiver; + } + Type found = asSuperType(receiver, owner.erasure().fullyQualifiedName(), new HashSet<>()); + return found == null ? receiver : found; + } + + /** + * The parameterization of {@code created} a diamond infers from {@code target}: each type parameter of the created + * class takes the target argument it is passed to through the supertype matching the target. + */ + Type inferDiamond(Type created, Type target) { + if (!(created.erasure() instanceof JType raw) || raw.isUnknown() || !(target instanceof JType expected) || !expected.isParameterized()) { + return created; + } + String targetFqn = expected.erasure().fullyQualifiedName(); + if (raw.fullyQualifiedName().equals(targetFqn)) { + return JType.named(this, raw.fullyQualifiedName(), expected.args); + } + Type generic = raw.declaringType(); + Type declared = generic.isParameterized() ? asSuperType(generic, targetFqn, new HashSet<>()) : null; + if (declared == null || declared.typeArguments().size() != expected.args.size()) { + return created; + } + Map inferred = new HashMap<>(); + for (int i = 0; i < expected.args.size(); i++) { + if (declared.typeArguments().get(i).isTypeVar()) { + inferred.put(declared.typeArguments().get(i).fullyQualifiedName(), expected.args.get(i)); + } + } + List arguments = new ArrayList<>(); + for (Type variable : generic.typeArguments()) { + JType argument = inferred.get(variable.fullyQualifiedName()); + if (argument == null) { + return created; + } + arguments.add(argument); + } + return JType.named(this, raw.fullyQualifiedName(), arguments); + } + + /** + * The parameterization of {@code created} a diamond infers from the arguments of its constructor: each type + * parameter of the class takes the argument type it is passed as, or {@code created} when one stays open. + */ + Type inferDiamondFromArguments(JMethodSymbol constructor, Type created, List arguments) { + if (!(created.erasure() instanceof JType raw) || raw.isUnknown() || created.isParameterized()) { + return created; + } + JsonObject info = typeInfos.get(sourceName(raw.fullyQualifiedName())); + List names = info == null ? List.of() : strings(info, "typeVars"); + List declared = names.isEmpty() ? List.of() : declaredParameters(constructor); + if (declared.isEmpty() || declared.size() != arguments.size()) { + return created; + } + Set own = new HashSet<>(names); + Map bound = new HashMap<>(); + for (int i = 0; i < declared.size(); i++) { + bindFromType(declared.get(i), arguments.get(i), own, bound); + } + List inferred = new ArrayList<>(); + for (String name : names) { + Type argument = bound.get(name); + if (argument == null || argument.isUnknown()) { + return created; + } + inferred.add(asJType(argument)); + } + return JType.named(this, raw.fullyQualifiedName(), inferred); + } + + /** The type a lambda or method reference implements for a wildcard-parameterized target (JLS 9.9). */ + Type groundType(Type target) { + if (!(target instanceof JType type) || !type.isParameterized() || type.args.stream().noneMatch(JType::isWildcard)) { + return target; + } + return JType.named(this, type.fullyQualifiedName(), type.args.stream().map(JType::groundType).toList()); + } + + /** Capture conversion: a member is accessed through captures of the receiver's wildcard arguments. */ + private Type captureWildcards(Type receiver) { + if (!(receiver instanceof JType type) || !type.isParameterized() || type.args.stream().noneMatch(JType::isWildcard)) { + return receiver; + } + List captured = type.args.stream().map(argument -> argument.isWildcard() && argument.element != null ? JType.capture(this, argument.element) : argument).toList(); + return JType.named(this, type.fullyQualifiedName(), captured); + } + + /** + * Whether {@code method} declares type variables of its own. A constructor, whose diamond infers them, and a + * method whose declaration is unknown count when their types are substituted. + */ + private boolean declaresTypeVariables(JMethodSymbol method, boolean substituted) { + JsonObject member = "".equals(method.name()) ? null : lookupGenericMember(method); + if (member == null) { + return substituted; + } + return member.get("typeVars") instanceof JsonArray names && !names.isEmpty(); + } + + /** The method as seen from {@code receiver}, so its owner keeps that parameterization. */ + JMethodSymbol invocationView(JMethodSymbol method, @Nullable Type receiver, List parameters, Type returned) { + return invocationView(method, receiver, parameters, returned, null); + } + + /** As above, with the thrown types the call infers when the method throws a type variable. */ + JMethodSymbol invocationView(JMethodSymbol method, @Nullable Type receiver, List parameters, Type returned, @Nullable List thrown) { + boolean substituted = method.substitutes(parameters, returned) || thrown != null; + JMethodSymbol view = method.withSignature(parameters, returned); + if (thrown != null) { + view.thrownTypes(thrown); + } + if (!view.isParametrizedMethod() && declaresTypeVariables(method, substituted)) { + view.parametrized(true); + } + if (receiver != null && !method.isStatic() && method.owner().type() != null) { + Type declaring = asSuperType(captureWildcards(receiver), method.owner().type().erasure().fullyQualifiedName(), new HashSet<>()); + if (declaring != null && declaring.isParameterized()) { + view.owner(declaring.symbol()); + } + } + boolean same = !substituted && view.owner() == method.owner() && view.isParametrizedMethod() == method.isParametrizedMethod(); + return same ? method : view; + } + + /** + * The parameter types of {@code method} at one invocation: type variables of the owner are replaced by + * the receiver's type arguments, and type variables of the method by the boxed type of the first argument + * they are inferred from. + */ + List invocationParameters(JMethodSymbol method, @Nullable Type receiver, List arguments) { + List parameters = method.parameterTypes(); + List variables = parameterVariables(method); + if (variables.size() != parameters.size()) { + return parameters; + } + List result = new ArrayList<>(parameters); + for (int i = 0; i < variables.size(); i++) { + String variable = variables.get(i); + if (variable.isEmpty()) { + continue; + } + String base = variable.replace("[]", ""); + Type bound = base.charAt(0) == 'c' + ? classArgument(method, receiver, Integer.parseInt(base.substring(1))) + : methodArgument(variables, base, arguments); + if (bound != null) { + JType type = asJType(bound); + for (int dims = (variable.length() - base.length()) / 2; dims > 0; dims--) { + type = JType.array(this, type); + } + result.set(i, type); + } + } + substituteDeclaredParameters(method, receiver, variables, result); + return result; + } + + /** + * Fills in the parameters that are not a type variable on their own but are written in terms of one, + * such as {@code Consumer}. Their declared form is substituted for the arguments the receiver gives + * the declaring type, which may be a supertype of the receiver's own type. Without such arguments, a declared + * parameterized type that names no type variable is taken as written. + */ + private void substituteDeclaredParameters(JMethodSymbol method, @Nullable Type receiver, List variables, List result) { + List declared = declaredParameters(method); + if (declared.size() != result.size()) { + return; + } + Map substitution = receiver == null ? Map.of() : classSubstitution(method, receiver); + for (int i = 0; i < declared.size(); i++) { + if (variables.isEmpty() || variables.get(i).isEmpty()) { + JType type = typeFromFact(declared.get(i), substitution); + if (!substitution.isEmpty() || (type.isParameterized() && !mentionsTypeVariable(type))) { + result.set(i, type); + } + } + } + } + + /** Maps the type variables of the type declaring {@code method} to the arguments {@code receiver} gives them. */ + private Map classSubstitution(JMethodSymbol method, Type receiver) { + String ownerFqn = method.owner().type().erasure().fullyQualifiedName(); + JsonObject info = typeInfos.get(sourceName(ownerFqn)); + List names = info == null ? List.of() : strings(info, "typeVars"); + Map substitution = new HashMap<>(); + if (receiver instanceof JType inner && inner.outer() != null && inner.erasure().fullyQualifiedName().equals(ownerFqn)) { + substitution.putAll(enclosingSubstitution(inner.outer())); + } + Type declaring = names.isEmpty() ? null : asSuperType(receiver, ownerFqn, new HashSet<>()); + if (declaring != null && declaring.isParameterized()) { + List arguments = declaring.typeArguments(); + for (int i = 0; i < names.size() && i < arguments.size(); i++) { + substitution.put(names.get(i), arguments.get(i)); + } + } + return substitution; + } + + private Map enclosingSubstitution(JType enclosing) { + JsonObject info = typeInfos.get(sourceName(enclosing.erasure().fullyQualifiedName())); + List names = info == null ? List.of() : strings(info, "typeVars"); + Map substitution = new HashMap<>(); + for (int i = 0; i < names.size() && i < enclosing.args.size(); i++) { + substitution.put(names.get(i), enclosing.args.get(i)); + } + return substitution; + } + + /** Whether {@code from}, read as {@code to}'s class, gives it the type arguments {@code to} names; a wildcard argument takes any. */ + boolean preservesArguments(Type from, Type to) { + if (!to.isParameterized()) { + return true; + } + Type aligned = asSuperType(from, to.erasure().fullyQualifiedName(), new HashSet<>()); + if (aligned == null || !aligned.isParameterized() || aligned.typeArguments().size() != to.typeArguments().size()) { + return false; + } + for (int i = 0; i < to.typeArguments().size(); i++) { + Type written = to.typeArguments().get(i); + if (!(written instanceof JType type && type.isWildcard()) && !written.equals(aligned.typeArguments().get(i))) { + return false; + } + } + return true; + } + + /** The instantiation of {@code targetFqn} reached from {@code from}, which is itself or one of its supertypes. */ + @Nullable + private Type asSuperType(Type from, String targetFqn, Set visited) { + if (from.erasure().fullyQualifiedName().equals(targetFqn)) { + return from; + } + Symbol.TypeSymbol symbol = from.symbol(); + if (symbol.isUnknown() || !visited.add(from.erasure().fullyQualifiedName())) { + return null; + } + List supertypes = new ArrayList<>(symbol.interfaces()); + Type superClass = symbol.superClass(); + if (superClass != null) { + supertypes.add(0, superClass); + } + for (Type supertype : supertypes) { + Type found = asSuperType(instantiateSupertype(from, supertype), targetFqn, visited); + if (found != null) { + return found; + } + } + return null; + } + + /** 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)); + } + + private Map typeArgumentsOf(JType type) { + JsonObject info = typeInfos.get(sourceName(type.erasure().fullyQualifiedName())); + List names = info == null ? List.of() : strings(info, "typeVars"); + 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; + } + + @Nullable + private JsonObject declaredReturn(JMethodSymbol method) { + if (method.declaredReturnLoaded()) { + return method.declaredReturn(); + } + JsonObject member = lookupGenericMember(method); + JsonObject retType = member != null && member.get("retType") instanceof JsonObject fact ? fact : null; + method.declaredReturn(retType); + return retType; + } + + private List declaredParameters(JMethodSymbol method) { + List cached = method.declaredParameters(); + if (cached == null) { + JsonObject member = lookupGenericMember(method); + cached = member == null ? List.of() : objects(member, "paramTypes"); + method.declaredParameters(cached); + } + return cached; + } + + @Nullable + private static Type classArgument(JMethodSymbol method, @Nullable Type receiver, int index) { + if (receiver == null || !receiver.isParameterized() || receiver.typeArguments().size() <= index + || !receiver.erasure().equals(method.owner().type().erasure())) { + return null; + } + return receiver.typeArguments().get(index); + } + + private List explicitTypeArguments = List.of(); + + /** Runs {@code action} with the type arguments an invocation spells out, which fix the type variables of its method. */ + T withExplicitTypeArguments(List explicit, java.util.function.Supplier action) { + List previous = explicitTypeArguments; + explicitTypeArguments = explicit; + try { + return action.get(); + } finally { + explicitTypeArguments = previous; + } + } + + @Nullable + private Type methodArgument(List variables, String base, List arguments) { + if (base.charAt(0) == 'm' && !explicitTypeArguments.isEmpty()) { + try { + int index = Integer.parseInt(base.substring(1)); + if (index < explicitTypeArguments.size() && !explicitTypeArguments.get(index).isUnknown()) { + return explicitTypeArguments.get(index); + } + } catch (NumberFormatException e) { + // not a method type variable + } + } + for (int i = 0; i < variables.size() && i < arguments.size(); i++) { + String variable = variables.get(i); + if (!variable.replace("[]", "").equals(base)) { + continue; + } + Type argument = arguments.get(i); + if (!variable.equals(base)) { + boolean last = i == variables.size() - 1; + // an array of a primitive type cannot be the array of a type variable: it is one element of the variable arity + if (arguments.size() == variables.size() && argument.isArray() && !((Type.ArrayType) argument).elementType().isPrimitive()) { + argument = ((Type.ArrayType) argument).elementType(); + } else if (!last) { + continue; + } + } + if (!argument.isUnknown() && !argument.isNullType()) { + return argument.isPrimitive() ? argument.primitiveWrapperType() : argument; + } + } + return null; + } + + /** 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 = typeInfos.get(sourceName(declaring.erasure().fullyQualifiedName())); + int position = info == null ? -1 : strings(info, "typeVars").indexOf(text(parameters.get(index), "id")); + return position < 0 || position >= declaring.typeArguments().size() ? null : declaring.typeArguments().get(position); + } + + /** The position, among the type variables of {@code declaring}, of the one the library {@code method} returns. */ + @Nullable + Integer returnedClassVariable(JMethodSymbol method, Type declaring) { + JsonObject returned = declaredReturn(method); + if (returned == null || !"typevar".equals(text(returned, "kind"))) { + return null; + } + JsonObject info = typeInfos.get(sourceName(declaring.erasure().fullyQualifiedName())); + int position = info == null ? -1 : strings(info, "typeVars").indexOf(text(returned, "id")); + return position < 0 ? null : position; + } + + /** + * The annotations written on type argument {@code position} of the supertype {@code declaring}, in the supertype clause + * of {@code owner} or of one of its supertypes ({@code implements StatementCallback<@Nullable Object>}). + */ + List supertypeArgumentAnnotations(Type owner, Type declaring, int position) { + return supertypeArgumentAnnotations(sourceName(owner.erasure().fullyQualifiedName()), sourceName(declaring.erasure().fullyQualifiedName()), position, new HashSet<>()); + } + + private List supertypeArgumentAnnotations(String name, String declaring, int position, Set visited) { + JsonObject info = typeInfos.get(name); + if (info == null || !visited.add(name)) { + return List.of(); + } + List interfaces = strings(info, "interfaces"); + if (interfaces.isEmpty() && "interface".equals(text(info, "kind"))) { + interfaces = strings(info, "super"); + } + if (info.get("typeAnnotations") instanceof JsonArray typed) { + for (JsonElement element : typed) { + if (element instanceof JsonObject entry && isArgumentOf(entry, position)) { + String on = text(entry, "on"); + String parent = "super".equals(on) ? text(info, "super") : "interface".equals(on) && entry.get("index") instanceof JsonPrimitive index + && index.getAsInt() >= 0 && index.getAsInt() < interfaces.size() ? interfaces.get(index.getAsInt()) : null; + if (parent != null && sourceName(erase(parent)).equals(declaring)) { + JsonArray one = new JsonArray(); + one.add(entry); + return readAnnotationList(one); + } + } + } + } + for (String parent : parents(info)) { + List found = supertypeArgumentAnnotations(sourceName(erase(parent)), declaring, position, visited); + if (!found.isEmpty()) { + return found; + } + } + return List.of(); + } + + private static boolean isArgumentOf(JsonObject entry, int position) { + return entry.get("path") instanceof JsonArray path && path.size() == 1 && path.get(0).isJsonPrimitive() && ("<" + position + ">").equals(path.get(0).getAsString()); + } + + private List parameterVariables(JMethodSymbol method) { + List cached = method.parameterVariables(); + if (cached == null) { + cached = lookupParameterVariables(method); + method.parameterVariables(cached); + } + return cached; + } + + private List lookupParameterVariables(JMethodSymbol method) { + JsonObject member = lookupGenericMember(method); + if (member == null) { + return List.of(); + } + List variables = new ArrayList<>(); + member.getAsJsonArray("paramVars").forEach(v -> variables.add(v.getAsString())); + return variables; + } + + /** The loaded declaration of {@code method}, when its declaring type is known and carries a generic signature. */ + @Nullable + private JsonObject lookupGenericMember(JMethodSymbol method) { + String ownerFqn = method.owner().type().erasure().fullyQualifiedName(); + if (!declaresType(ownerFqn)) { + return null; + } + JsonArray members = typeInfos.get(sourceName(ownerFqn)).getAsJsonArray(MEMBERS); + if (members == null) { + return null; + } + List parameters = method.parameterTypes(); + for (JsonElement element : members) { + JsonObject member = element.getAsJsonObject(); + String descriptor = text(member, "desc"); + if (method.name().equals(text(member, "name")) && descriptor != null && member.has("paramVars") && member.get("paramVars").isJsonArray() + && sameParameters(parameters, parameterTypesOf(descriptor))) { + return member; + } + } + return null; + } + + /** 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("::"); + if (!variable && !name.equals(descriptor.get(i).erasure().fullyQualifiedName())) { + return false; + } + } + return true; + } + + Symbol memberFromTypeInfo(JTypeSymbol owner, JsonObject member) { + if (member.has("id") && !member.get("id").isJsonNull()) { + JSymbol project = resolve(member.get("id").getAsString()); + if (declaredAnnotations(project.id).stream().anyMatch(annotation -> "java.lang.Deprecated".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; + } + 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 = symbols.get(id); + if (existing != null) { + return existing; + } + if ("f".equals(text(member, "k"))) { + JVariableSymbol field = new JVariableSymbol(this, id, name == null ? "" : name, "field"); + field.owner(owner); + if (descriptor != null) { + field.type(readDescriptor(descriptor, new int[] {0})); + } + applyMemberFlags(field, member); + 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)); + } + symbols.put(id, field); + return field; + } + JMethodSymbol method = new JMethodSymbol(this, id, name == null ? "" : name); + method.owner(owner); + if (descriptor != null && descriptor.startsWith("(")) { + method.parameterTypes(parameterTypesOf(descriptor)); + method.returnTypeSymbol(readDescriptor(descriptor, new int[] {descriptor.indexOf(')') + 1}).symbol()); + } + applyMemberFlags(method, member); + if (owner.isInterface() && !truth(member, ABSTRACT) && !truth(member, STATIC) && !"private".equals(text(member, "vis"))) { + method.addModifiers(List.of("default")); + } + libraryAnnotations(method, id, member); + List thrown = strings(member, THROWS); + if (!thrown.isEmpty()) { + method.thrownTypes(thrown.stream().map(this::typeFromName).toList()); + } + if (member.has("varargs") && member.get("varargs").isJsonPrimitive()) { + method.varArgs(member.get("varargs").getAsBoolean()); + method.varArgsKnown(true); + } + if (member.has("retParam") && !member.get("retParam").isJsonNull()) { + method.returnTypeParameter(member.get("retParam").getAsInt()); + } + if (member.get("retType") instanceof JsonObject retType) { + method.declaredReturn(retType); + // a parameterized return keeps its arguments, so the member's return type is the one a call reports + if (!method.isStatic() && retType.has("args")) { + JType plain = typeFromFact(retType, Map.of(), true); + if (!plain.isUnknown() && plain.isParameterized() + && plain.args.stream().noneMatch(argument -> argument.isCapture() || argument.isWildcard())) { + method.returnTypeSymbol(plain.symbol()); + } + } + } + method.returnsSelf(member.has("retSelf") && member.get("retSelf").getAsBoolean()); + if (member.get("default") instanceof JsonObject defaultValue) { + Object value = readAnnotationElement(defaultValue); + if (value != null) { + annotationDefaults.put(id, value); + } + } + symbols.put(id, method); + return method; + } + + /** The default of an annotation element read from a class file. */ + @Nullable + Object annotationDefault(JMethodSymbol method) { + return method.id == null ? null : annotationDefaults.get(method.id); + } + + /** The value a field of type {@code descriptor} holds, from the text Java prints for it. */ + @Nullable + private static Object libraryConstant(@Nullable String descriptor, String text) { + try { + return switch (descriptor == null ? "" : descriptor) { + case "Z" -> Boolean.valueOf(text); + case "B" -> Byte.valueOf(text); + case "S" -> Short.valueOf(text); + case "C" -> text.length() == 1 ? (Object) (int) text.charAt(0) : null; + case "I" -> Integer.valueOf(text); + case "J" -> Long.valueOf(text); + case "F" -> Float.valueOf(text); + case "D" -> Double.valueOf(text); + default -> text; + }; + } catch (NumberFormatException notANumber) { + return null; + } + } + + private void createDumpSymbol(String id) { + if (symbols.containsKey(id)) { + return; + } + org.sonarsource.semsitter.wire.Symbol dump = 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(this, id, name, true); + } else if ("type".equals(kind)) { + symbol = new JTypeSymbol(this, id, simpleName(erase(id)), false); + typesByName.putIfAbsent(erase(id), (JTypeSymbol) symbol); + } else if ("method".equals(kind) || "constructor".equals(kind)) { + symbol = new JMethodSymbol(this, id, "constructor".equals(kind) ? "" : name); + } else { + symbol = new JVariableSymbol(this, id, name, kind); + } + symbols.put(id, symbol); + } + + private void linkDumpSymbol(String id) { + JSymbol symbol = symbols.get(id); + org.sonarsource.semsitter.wire.Symbol dump = dumpSymbols.get(id); + if (symbol == null || dump == null) { + return; + } + Fact fact = facts.get(id); + String ownerId = text(dump.getOwner()); + String parent = fact == null ? null : text(fact.getParent()); + if ((ownerId == null && symbol instanceof JMethodSymbol) || (ownerId != null && parent != null && !parent.contains("::") && !facts.containsKey(ownerId) && !dumpSymbols.containsKey(ownerId))) { + ownerId = parent; + } + if (ownerId != null) { + symbol.owner(resolve(ownerId)); + } else if (symbol instanceof JTypeSymbol typeSymbol && !typeSymbol.isTypeParameter()) { + symbol.owner(packageSymbol(packageName(erase(id)))); + } + if (fact != null) { + applyFact(symbol, fact); + } + if ((symbol.isMethodSymbol() || symbol.isVariableSymbol()) && (fact == null || !"IN_PROJECT".equals(fact.getTier()))) { + applyLibraryMember(symbol, id); + } + TypeRef declaredType = typeFact(dump); + if (symbol.isVariableSymbol() && declaredType != null) { + symbol.type(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 && PRIMITIVES.contains(declared.get(0))) { + symbol.type(primitiveType(declared.get(0))); + } + } + if (symbol instanceof JMethodSymbol method) { + fillMethod(method, fact, id); + implicitEnumMethod(method, id, ownerId, dump); + } else if (symbol instanceof JTypeSymbol typeSymbol && typeSymbol.isTypeParameter()) { + symbol.type(JType.typeVar(this, symbol.name(), id)); + } else if (symbol.isTypeSymbol()) { + symbol.type(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 || !declaresType(erase(id.substring(0, hash)))) { + return null; + } + JsonArray members = typeInfos.get(sourceName(erase(id.substring(0, hash)))).getAsJsonArray(MEMBERS); + if (members != null) { + for (JsonElement element : members) { + JsonObject member = element.getAsJsonObject(); + String constant = text(member, "constant"); + if (constant != null && id.equals(text(member, "id"))) { + return constantOf(field.type(), constant); + } + } + } + return null; + } + + /** 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 = 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 = typeFromName(erase(ownerId)); + method.returnTypeSymbol((valueOf ? enumType : JType.array(this, (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 = parseMember(id); + if (parsed == null || parsed.arityOnly || ARRAY.equals(parsed.owner)) { + return; + } + String ownerName = erase(parsed.owner); + typeSymbol(ownerName); + JsonObject member = findMember(ownerName, parsed, new HashSet<>(), Match.TYPED); + if (member == null || member.has("id")) { + return; + } + applyMemberFlags(symbol, member); + libraryAnnotations(symbol, id, member); + List thrown = strings(member, THROWS); + if (symbol instanceof JMethodSymbol method && !thrown.isEmpty()) { + method.thrownTypes(thrown.stream().map(this::typeFromName).toList()); + } + if (symbol instanceof JMethodSymbol method && member.get("varargs") instanceof JsonPrimitive varArgs && varArgs.isBoolean()) { + method.varArgs(varArgs.getAsBoolean()); + method.varArgsKnown(true); + } + } + + /** A constant spelled as text, as the boxed value of the field's primitive type. */ + private 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 ? (Object) (int) text.charAt(0) : text; + default -> text; + }; + } catch (NumberFormatException e) { + return text; + } + } + + /** 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 && symbols.get(id) instanceof JTypeSymbol parameter && parameter.firstBound() instanceof Type bound && !bound.isUnknown()) { + return bound; + } + return getClassType("java.lang.Object"); + } + + /** 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 && symbols.get(id) instanceof JTypeSymbol parameter && !parameter.bounds().isEmpty()) { + return parameter.bounds(); + } + return List.of(getClassType("java.lang.Object")); + } + + private 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(this, id, name, true); + symbol.type(JType.typeVar(this, name, id)); + symbols.put(id, symbol); + return symbol; + } + + private JSymbol createMember(String id) { + if (!creating.add(id)) { + return unknownSymbol; + } + try { + return createMemberOnce(id); + } finally { + creating.remove(id); + } + } + + private JSymbol createMemberOnce(String id) { + MemberId parsed = parseMember(id); + if (parsed == null) { + return typeSymbol(erase(id)); + } + if (ARRAY.equals(parsed.owner) && "length".equals(parsed.name)) { + JVariableSymbol length = new JVariableSymbol(this, id, "length", "field"); + length.addModifiers(List.of("public", "final")); + length.type(primitiveType("int")); + length.owner(Symbol.UNKNOWN_SYMBOL); + symbols.put(id, length); + return length; + } + String ownerName = erase(parsed.owner); + JTypeSymbol owner = typeSymbol(ownerName); + JsonObject member = null; + if (parsed.params != null && !parsed.arityOnly) { + member = findMember(ownerName, parsed, new HashSet<>(), Match.TYPED); + } + if (member == null) { + member = findMember(ownerName, parsed, new HashSet<>(), Match.ARITY); + } + if (member == null && parsed.params != null) { + member = findMember(ownerName, parsed, new HashSet<>(), Match.VARARGS); + } + String memberId = member == null ? null : text(member, "id"); + if (member != null && (memberId == null || !creating.contains(memberId))) { + Symbol resolved = memberFromTypeInfo(owner, member); + if (resolved instanceof JSymbol jSymbol) { + symbols.put(id, jSymbol); + return jSymbol; + } + } + if (parsed.params == null && parsed.name.contains("$lambda$")) { + JMethodSymbol lambda = new JMethodSymbol(this, id, parsed.name); + lambda.owner(owner); + lambda.lambda(true); + symbols.put(id, lambda); + return lambda; + } + if (parsed.params == null && parsed.name.contains(")$")) { + return createTypeInMethodBody(id, parsed); + } + if (parsed.params == null) { + JVariableSymbol field = new JVariableSymbol(this, 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 instanceof JTypeSymbol enumType && enumType.isEnum() && enumType.type() != null) { + // the facts of an enum constant carry no type: it is of its enum + applyFact(field, fieldFact); + field.type(enumType.type()); + field.enumSymbol(true); + } else if (fieldFact == null || fieldType.isEmpty()) { + field.unknown(true); + } else { + applyFact(field, fieldFact); + JsonObject declared = projectFieldTypes.get(id); + field.type(declared != null ? typeFromFact(declared) : typeFromName(fieldType.get(0))); + } + markDeprecated(field, id); + symbols.put(id, field); + return field; + } + JMethodSymbol method = new JMethodSymbol(this, id, parsed.name); + boolean undeclaredOwner = noLibraries && member == null && !declaresType(ownerName); + method.owner(parsed.arityOnly || undeclaredOwner ? Symbol.TypeSymbol.UNKNOWN_TYPE : owner); + method.unknown(parsed.arityOnly || undeclaredOwner); + fillMethod(method, factOf(id), id); + if ("".equals(parsed.name) && factOf(id) == null && member == null) { + // The implicit default constructor has the access of its class. + method.addModifiers(List.of("public", "protected", "private").stream().filter(owner::hasModifier).toList()); + } + if (method.parameterTypes().isEmpty() && !parsed.arityOnly && parsed.params != null && !parsed.params.isEmpty()) { + List types = new ArrayList<>(); + for (String param : parsed.paramList()) { + types.add(typeFromName(param)); + } + method.parameterTypes(types); + } + Fact methodFact = factOf(id); + if (methodFact != null && !parsed.arityOnly) { + applyFact(method, methodFact); + } + markDeprecated(method, id); + 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 = facts.get(id); + return fact != null ? fact : projectMemberFacts.get(id); + } + + private void markDeprecated(JSymbol symbol, String id) { + if (declaredAnnotations(id).stream().anyMatch(annotation -> "java.lang.Deprecated".equals(annotation.name()))) { + symbol.deprecated(true); + } + } + + /** + * The method {@code name} of {@code ownerFqn} or of one of its supertypes that Java would pick for {@code arguments}: + * applicable by subtyping first, then with boxing, then as varargs, and the most specific of those. + */ + @Nullable + Symbol.MethodSymbol declaredMethod(String ownerFqn, String name, List arguments) { + return declaredMethod(ownerFqn, name, arguments, Set.of()); + } + + /** [declaredMethod] where the arguments at {@code functions} are lambdas or method references, which only a functional interface takes. */ + @Nullable + Symbol.MethodSymbol declaredMethod(String ownerFqn, String name, List arguments, Set functions) { + if (!declaresType(ownerFqn)) { + return null; + } + List candidates = new ArrayList<>(); + collectMethods(ownerFqn, ownerFqn, name, new HashSet<>(), candidates); + if (!functions.isEmpty()) { + candidates.removeIf(method -> takesNoFunction(method, functions)); + } + for (int phase = 0; phase < 3; phase++) { + int current = phase; + List applicable = candidates.stream().filter(method -> applicable(method, arguments, current)).toList(); + if (!applicable.isEmpty()) { + return applicable.stream().filter(method -> applicable.stream().allMatch(other -> moreSpecific(method, other))).findFirst().orElse(applicable.get(0)); + } + } + List sameArity = candidates.stream() + .filter(method -> method.isVarArgsMethod() ? arguments.size() >= method.parameterTypes().size() - 1 : method.parameterTypes().size() == arguments.size()) + .toList(); + if (sameArity.size() == 1) { + return sameArity.get(0); + } + return null; + } + + private boolean takesNoFunction(Symbol.MethodSymbol method, Set functions) { + List parameters = method.parameterTypes(); + for (int index : functions) { + if (index >= parameters.size()) { + continue; + } + Type target = parameters.get(index).erasure(); + if (target.isPrimitive() || target.isArray() || (target.isClass() && !target.isUnknown() && !target.isTypeVar() && !target.symbol().isUnknown() + && (!target.symbol().isInterface() || (declaresType(target.fullyQualifiedName()) && functionalMethod(target) == null)))) { + return true; + } + } + return false; + } + + /** ECJ leaves a call unresolved when no declaration takes this many arguments, rather than guessing one. */ + static boolean arityMatches(Symbol.MethodSymbol method, int argumentCount) { + int parameters = method.parameterTypes().size(); + return method.isVarArgsMethod() ? argumentCount >= parameters - 1 : argumentCount == parameters; + } + + /** The single abstract method of {@code type} when it is a functional interface, else null. */ + @Nullable + JMethodSymbol functionalMethod(Type type) { + String fqn = type.erasure().fullyQualifiedName(); + if (!type.isClass() || !type.symbol().isInterface() || !declaresType(fqn)) { + return null; + } + Map found = new LinkedHashMap<>(); + collectAbstractMethods(fqn, new HashSet<>(), found); + return found.size() == 1 ? found.values().iterator().next() : null; + } + + private void collectAbstractMethods(String ownerFqn, Set seen, Map found) { + if (!seen.add(ownerFqn) || !declaresType(ownerFqn)) { + return; + } + JsonObject info = typeInfos.get(sourceName(ownerFqn)); + JsonArray members = info.getAsJsonArray(MEMBERS); + if (members != null) { + for (JsonElement element : members) { + if (memberFromTypeInfo(typeSymbol(ownerFqn), element.getAsJsonObject()) instanceof JMethodSymbol method && !method.isUnknown() && method.isAbstract() + && !OBJECT_METHODS.contains(method.name() + "/" + method.parameterTypes().size())) { + found.putIfAbsent(method.name() + "/" + method.parameterTypes().size(), method); + } + } + } + parents(info).forEach(parent -> collectAbstractMethods(erase(parent), seen, found)); + } + + /** The field {@code name} that {@code ownerFqn} or one of its supertypes declares, if any. */ + @Nullable + Symbol.VariableSymbol declaredField(String ownerFqn, String name) { + return declaredField(ownerFqn, name, new HashSet<>()); + } + + @Nullable + private Symbol.VariableSymbol declaredField(String ownerFqn, String name, Set seen) { + if (!seen.add(ownerFqn) || !declaresType(ownerFqn)) { + return null; + } + JsonObject info = typeInfos.get(sourceName(ownerFqn)); + JsonArray members = info.getAsJsonArray(MEMBERS); + if (members != null) { + for (JsonElement element : members) { + JsonObject member = element.getAsJsonObject(); + MemberId id = member.has("id") ? parseMember(member.get("id").getAsString()) : null; + boolean named = id == null ? (name.equals(text(member, "name")) && "f".equals(text(member, "k"))) : (name.equals(id.name) && id.params == null); + if (named && memberFromTypeInfo(typeSymbol(ownerFqn), member) instanceof Symbol.VariableSymbol field && !field.isUnknown()) { + return field; + } + } + } + for (String parent : parents(info)) { + Symbol.VariableSymbol found = declaredField(erase(parent), name, seen); + if (found != null) { + return found; + } + } + return null; + } + + /** Methods named {@code name} that {@code root} has: a static method of an interface is not inherited. */ + private void collectMethods(String root, String ownerFqn, String name, Set seen, List found) { + if (!seen.add(ownerFqn) || !declaresType(ownerFqn)) { + return; + } + JsonObject info = typeInfos.get(sourceName(ownerFqn)); + boolean inheritedInterface = !ownerFqn.equals(root) && typeSymbol(ownerFqn).isInterface(); + JsonArray members = info.getAsJsonArray(MEMBERS); + if (members != null) { + for (JsonElement element : members) { + JsonObject member = element.getAsJsonObject(); + MemberId id = member.has("id") ? parseMember(member.get("id").getAsString()) : null; + boolean named = id == null ? (name.equals(text(member, "name")) && "m".equals(text(member, "k"))) : (name.equals(id.name) && id.params != null); + if (named && memberFromTypeInfo(typeSymbol(ownerFqn), member) instanceof Symbol.MethodSymbol method && !method.isUnknown() + && !(inheritedInterface && method.isStatic())) { + found.add(method); + } + } + } + if (!"".equals(name)) { + parents(info).forEach(parent -> collectMethods(root, erase(parent), name, seen, found)); + } + } + + /** The overload that matches {@code arguments} when {@code candidate} is more specific than {@code current}. */ + Symbol.MethodSymbol preferOverload(Symbol.MethodSymbol current, @Nullable Symbol.MethodSymbol candidate, List arguments, Set functions) { + if (candidate == null || candidate == current || candidate.isUnknown() || !arityMatches(candidate, arguments.size())) { + return current; + } + if (!functions.isEmpty() && takesNoFunction(current, functions) && !takesNoFunction(candidate, functions)) { + return candidate; + } + for (int phase = 0; phase < 3; phase++) { + boolean currentOk = applicable(current, arguments, phase); + boolean candidateOk = applicable(candidate, arguments, phase); + if (currentOk && !candidateOk) { + return current; + } + if (candidateOk && !currentOk) { + return candidate; + } + if (currentOk && candidateOk) { + return moreSpecific(candidate, current) && !moreSpecific(current, candidate) ? candidate : current; + } + } + return current; + } + + /** The most specific variable-arity overload of {@code chosen} applicable to the arguments, when no earlier phase applies to {@code chosen}. */ + JMethodSymbol mostSpecificVarArgs(JMethodSymbol chosen, List arguments) { + if (chosen.isUnknown() || !chosen.isVarArgsMethod() || !(chosen.owner() instanceof Symbol.TypeSymbol owner) || applicable(chosen, arguments, 0) || applicable(chosen, arguments, 1) + || arguments.stream().anyMatch(Type::isUnknown)) { + return chosen; + } + List candidates = new ArrayList<>(); + for (Symbol member : owner.lookupSymbols(chosen.name())) { + if (member instanceof JMethodSymbol method && !method.isUnknown() && method.isVarArgsMethod() && method.isStatic() == chosen.isStatic() && applicable(method, arguments, 2)) { + candidates.add(method); + } + } + for (JMethodSymbol candidate : candidates) { + if (candidates.stream().allMatch(other -> other == candidate || moreSpecificVarArgs(candidate, other, arguments.size()))) { + return candidate; + } + } + return chosen; + } + + private static boolean moreSpecificVarArgs(Symbol.MethodSymbol method, Symbol.MethodSymbol other, int count) { + for (int i = 0; i < Math.max(count, Math.max(method.parameterTypes().size(), other.parameterTypes().size())); i++) { + if (!expanded(method, i).erasure().isSubtypeOf(expanded(other, i).erasure())) { + return false; + } + } + return true; + } + + private static Type expanded(Symbol.MethodSymbol method, int index) { + List parameters = method.parameterTypes(); + return index < parameters.size() - 1 ? parameters.get(index) : ((Type.ArrayType) parameters.get(parameters.size() - 1)).elementType(); + } + + /** Moves a recorded use of a method to another overload. */ + void moveUse(@Nullable String from, @Nullable String to, IdentifierTree use) { + List old = from == null ? null : usages.get(from); + if (old != null) { + old.remove(use); + } + if (to != null) { + use(to, use); + } + } + + private static boolean applicable(Symbol.MethodSymbol method, List arguments, int phase) { + List parameters = method.parameterTypes(); + int count = parameters.size(); + boolean varargs = phase == 2 && method.isVarArgsMethod(); + if (varargs ? arguments.size() < count - 1 : arguments.size() != count) { + return false; + } + for (int i = 0; i < arguments.size(); i++) { + Type parameter = varargs && i >= count - 1 ? ((Type.ArrayType) parameters.get(count - 1)).elementType() : parameters.get(i); + if (!convertible(arguments.get(i), parameter, phase > 0)) { + return false; + } + } + return true; + } + + private static boolean convertible(Type argument, Type parameter, boolean boxing) { + Type target = parameter.erasure(); + if (argument.isUnknown() || target.isUnknown() || target.isTypeVar() || argument.erasure().isSubtypeOf(target)) { + return true; + } + if (!boxing || argument.isPrimitive() == target.isPrimitive()) { + return false; + } + Type converted = argument.isPrimitive() ? argument.primitiveWrapperType() : argument.primitiveType(); + return converted != null && converted.isSubtypeOf(target); + } + + private static boolean moreSpecific(Symbol.MethodSymbol method, Symbol.MethodSymbol other) { + List mine = method.parameterTypes(); + List theirs = other.parameterTypes(); + if (mine.size() != theirs.size()) { + return true; + } + for (int i = 0; i < mine.size(); i++) { + Type target = theirs.get(i).erasure(); + if (!target.isTypeVar() && !mine.get(i).erasure().isSubtypeOf(target)) { + return false; + } + } + return true; + } + + @Nullable + private JsonObject findMember(String ownerFqn, MemberId parsed, Set seen, Match match) { + if (!seen.add(ownerFqn)) { + return null; + } + JsonObject info = typeInfos.get(sourceName(ownerFqn)); + JsonObject found = matchMembers(info == null ? null : info.getAsJsonArray(MEMBERS), parsed, match); + if (found != null) { + return found; + } + JTypeSymbol type = typesByName.get(sourceName(ownerFqn)); + if (type != null) { + for (JsonObject member : type.memberFacts()) { + if (matches(member, parsed, match)) { + return member; + } + } + } + if (info == null || "".equals(parsed.name)) { + return null; + } + for (String parent : parents(info)) { + found = findMember(erase(parent), parsed, seen, match); + if (found != null) { + return found; + } + } + return null; + } + + @Nullable + private JsonObject matchMembers(@Nullable JsonArray members, MemberId parsed, Match match) { + if (members == null) { + return null; + } + for (JsonElement element : members) { + JsonObject member = element.getAsJsonObject(); + if (matches(member, parsed, match)) { + return member; + } + } + return null; + } + + private boolean matches(JsonObject member, MemberId parsed, Match match) { + if (member.has("id")) { + MemberId other = parseMember(member.get("id").getAsString()); + return other != null && parsed.name.equals(other.name) && parsed.arity == other.arity + && (parsed.arityOnly || other.arityOnly || Objects.equals(parsed.params, other.params)); + } + if (!parsed.name.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 = 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("...", "[]").trim(); + } + + private enum Match { + TYPED, ARITY, VARARGS + } + + private void fillMethod(JMethodSymbol method, @Nullable Fact fact, String id) { + MemberId parsed = parseMember(id); + List returns = fact == null ? List.of() : flat(fact.getReturnsList()); + if (!returns.isEmpty()) { + method.returnTypeSymbol(typeFromName(returns.get(0)).symbol()); + } + List factParams = fact == null ? List.of() : flat(fact.getParamsList()); + if (!factParams.isEmpty() && (parsed == null || parsed.arityOnly || factParams.size() == parsed.arity)) { + List types = new ArrayList<>(); + for (String param : factParams) { + types.add(typeFromName(param)); + } + method.parameterTypes(types); + } else if (parsed != null && !parsed.arityOnly && parsed.params != null && !parsed.params.isEmpty()) { + List types = new ArrayList<>(); + for (String param : parsed.paramList()) { + types.add(typeFromName(param)); + } + method.parameterTypes(types); + } + if ("".equals(method.name())) { + method.returnTypeSymbol(primitiveSymbol("void")); + } + List declaredParams = fact == null ? List.of() : flat(prop(fact, "param_types")); + Boolean served = 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); + } + method.parametrized(id.replace("", "").replace("", "").indexOf('<') >= 0); + } + + private void applyFact(JSymbol symbol, Fact fact) { + String kind = fact.getKind(); + if (symbol instanceof JTypeSymbol type) { + 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(JSema::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); + } + } + symbol.addModifiers(flat(prop(fact, "modifiers"))); + if (symbol instanceof JTypeSymbol) { + symbol.addModifiers(implicitTypeModifiers(kind, text(fact.getParent()))); + } + for (String annotation : fact.getAnnotationsList()) { + if ("java.lang.Deprecated".equals(erase(annotation))) { + symbol.deprecated(true); + } + } + if (symbol.isVariableSymbol() && ("enum".equals(kind) || "enum_member".equals(kind))) { + symbol.enumSymbol(true); + symbol.addModifiers(List.of("public", STATIC, "final")); + } + } + + /** + * 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("::") && facts.get(parent) != null + && isTypeFact(facts.get(parent)); + if (member && ("interface".equals(kind) || "enum".equals(kind) || RECORD.equals(kind) || "annotation".equals(kind))) { + implied.add(STATIC); + } + if ("enum".equals(kind) || RECORD.equals(kind)) { + implied.add("final"); + } + return implied; + } + + private static boolean isTypeFact(Fact fact) { + String kind = fact.getKind(); + return "class".equals(kind) || "interface".equals(kind) || "enum".equals(kind) || RECORD.equals(kind) + || "annotation".equals(kind) || "exception".equals(kind); + } + + private void applyTypeInfo(JTypeSymbol symbol, JsonObject info) { + 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( + info.get("superType") instanceof JsonObject superType ? superType : null, + objects(info, "interfaceTypes")); + symbol.addModifiers(flat(info, "modifiers")); + libraryAnnotations(symbol, symbol.id == null ? symbol.name() : symbol.id, info); + if (info.has("typeParameters") && !info.get("typeParameters").isJsonNull()) { + symbol.typeParameterCount(info.get("typeParameters").getAsInt()); + } + List members = new ArrayList<>(); + if (info.has(MEMBERS)) { + for (JsonElement member : info.getAsJsonArray(MEMBERS)) { + members.add(member.getAsJsonObject()); + } + } + symbol.memberFacts(members); + symbol.unknown(false); + } + + private static void applyMemberFlags(JSymbol symbol, JsonObject member) { + List modifiers = new ArrayList<>(); + if (truth(member, STATIC)) { + modifiers.add(STATIC); + } + if (truth(member, "final")) { + modifiers.add("final"); + } + if (truth(member, "synchronized")) { + modifiers.add("synchronized"); + } + if (truth(member, ABSTRACT)) { + modifiers.add(ABSTRACT); + } + String visibility = text(member, "vis"); + if (visibility != null && !"package".equals(visibility)) { + modifiers.add(visibility); + } + symbol.addModifiers(modifiers); + } + + private 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; + } + + private JType typeFromFact(JsonObject fact) { + return typeFromFact(fact, Map.of()); + } + + private JType typeFromFact(JsonObject fact, Map substitution) { + return typeFromFact(fact, substitution, false); + } + + private JType typeFromFact(JsonObject fact, Map substitution, boolean captureWildcard) { + String kind = text(fact, "kind"); + if (ARRAY.equals(kind) && fact.getAsJsonObject("elem") != null) { + return JType.array(this, typeFromFact(fact.getAsJsonObject("elem"), substitution, captureWildcard)); + } + if (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(this); + } + String id = text(fact, "id"); + if (id == null) { + return JType.unknown(this); + } + 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. */ + private JType typeFromRef(TypeRef type) { + String kind = type.getKind(); + if (ARRAY.equals(kind) && type.hasElement()) { + return JType.array(this, typeFromRef(type.getElement())); + } + if (WILDCARD.equals(kind)) { + return JType.wildcard(this, asJType(getClassType("java.lang.Object"))); + } + if ("typevar".equals(kind)) { + return typeVariable(text(type.getId()), Map.of()); + } + if ("unknown".equals(kind) || type.getId().isEmpty()) { + return JType.unknown(this); + } + List args = new ArrayList<>(); + for (TypeRef argument : type.getArgumentsList()) { + args.add(typeFromRef(argument)); + } + return namedType(type.getId(), args, false); + } + + private JType typeVariable(@Nullable String id, Map substitution) { + Type substituted = substitution.get(id); + if (substituted != null) { + return 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(this, name == null ? "" : name, id); + } + + private JType namedType(String id, List args, boolean captureWildcard) { + String erased = erase(id); + if (PRIMITIVES.contains(erased)) { + return primitiveType(erased); + } + if (captureWildcard) { + boundCaptures(erased, args); + } + return JType.named(this, 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("java.lang.Object")) { + JType bound = declaredBound(owner, i); + if (bound != null) { + arguments.set(i, JType.capture(this, 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 = typeInfos.get(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("java.lang.Object") ? null : bound; + } + + private JType wildcardFromFact(JsonObject fact, Map substitution, boolean capture) { + JType object = asJType(getClassType("java.lang.Object")); + JType upper = fact.get(EXTENDS) instanceof JsonObject bound ? typeFromFact(bound, substitution) : object; + if (capture) { + return JType.capture(this, upper.isUnknown() ? object : upper); + } + if (fact.get("super") instanceof JsonObject bound) { + return JType.superWildcard(this, typeFromFact(bound, substitution)); + } + return JType.wildcard(this, upper); + } + + /** A supertype fact: the loaded raw type, parameterized when the fact has type arguments. */ + Type supertypeFromFact(JsonObject fact) { + Type raw = getClassType(erase(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(this, rawType.fullyQualifiedName(), resolved); + } + + private 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; + } + + /** + * The type variable a callable or class result names as {@code ::``}, the position-th variable + * the dump declares as {@code }. + */ + @Nullable + private JTypeSymbol typeParameterItem(String name) { + int marker = name.lastIndexOf("::`"); + int digits = marker < 0 ? -1 : (name.startsWith("::``", marker) ? marker + 4 : marker + 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)); + int seen = 0; + for (Map.Entry entry : dumpSymbols.entrySet()) { + String key = entry.getKey(); + String prefix = key.startsWith(owner + "<") ? owner : (key.startsWith(erase(owner) + "<") ? erase(owner) : null); + boolean declared = prefix != null && key.length() > prefix.length() + 2 && key.endsWith(">") + && key.indexOf('<', prefix.length() + 1) < 0 && "type".equals(entry.getValue().getKind()); + if (declared && seen++ == position) { + if (resolve(key) instanceof JTypeSymbol variable && variable.isTypeParameter()) { + if (variable.type().isUnknown()) { + variable.type(JType.typeVar(this, variable.name(), key)); + } + return variable; + } + return null; + } + } + return null; + } + + private Type typeFromName(String name) { + JTypeSymbol variable = typeParameterItem(name); + if (variable != null) { + return variable.type(); + } + String erased = erase(name); + if (PRIMITIVES.contains(erased)) { + return primitiveType(erased); + } + if (erased.endsWith("[]")) { + return JType.array(this, asJType(typeFromName(erased.substring(0, erased.length() - 2)))); + } + return getClassType(erased); + } + + private JType primitiveType(String name) { + return rawTypes.computeIfAbsent(name, key -> JType.primitive(this, key)); + } + + private final Map initializerBlockSymbols = new HashMap<>(); + private final Map staticInitializerBlockSymbols = new HashMap<>(); + + JInitializerBlockSymbol initializerBlockSymbol(JTypeSymbol owner) { + return initializerBlockSymbols.computeIfAbsent(owner, k -> new JInitializerBlockSymbol(k, false)); + } + + JInitializerBlockSymbol staticInitializerBlockSymbol(JTypeSymbol owner) { + return staticInitializerBlockSymbols.computeIfAbsent(owner, k -> new JInitializerBlockSymbol(k, true)); + } + + /** 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 && libraryAnnotations.containsKey(parameterKey(method.id, index))) { + return placeholders.computeIfAbsent(key, k -> { + JVariableSymbol annotated = new JVariableSymbol(this, 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)); + } + + JType asJType(Type type) { + return type instanceof JType jType ? jType : JType.unknown(this); + } + + private JType rawNamed(String fqn) { + return rawTypes.computeIfAbsent(sourceName(fqn), name -> JType.named(this, binaryNames.getOrDefault(name, name), List.of())); + } + + private List parameterTypesOf(String descriptor) { + List types = new ArrayList<>(); + int[] index = {1}; + while (index[0] < descriptor.length() && descriptor.charAt(index[0]) != ')') { + types.add(readDescriptor(descriptor, index)); + } + return types; + } + + private 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 = getClassType(binary); + } else { + index[0]++; + type = 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(this, asJType(type)); + } + return type; + } + + /** 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 && requestedTypes.add(fqn)) { + ingestTypes(typeLoader.apply(Set.of(fqn))); + } + return typeInfos.containsKey(fqn); + } + + /** Whether a type of the package {@code name} is known, which is how a package shows itself. */ + boolean knowsPackage(String name) { + Boolean declared = typesLoaded ? packageLoader.apply(name) : null; + if (declared != null) { + return declared; + } + String prefix = sourceName(name) + "."; + return typeInfos.keySet().stream().anyMatch(type -> type.startsWith(prefix) && type.indexOf('.', prefix.length()) < 0); + } + + /** The unknown type a written name stands for when nothing declares it. */ + JTypeSymbol recoveredType(String name) { + JTypeSymbol recovered = typeSymbol(name); + if (!recovered.isUnknown() && !declaresType(name)) { + recovered.unknown(true); + } + return recovered; + } + + 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; + } + + @Nullable + /** + * 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(this, id, anonymous ? "" : simpleName, false); + symbols.put(id, symbol); + typesByName.putIfAbsent(id, symbol); + symbol.owner(resolve(parsed.owner + "#" + parsed.name.substring(0, lastSegment))); + symbol.type(rawNamed(id)); + Fact fact = facts.get(id); + if (fact != null) { + applyFact(symbol, fact); + } + return symbol; + } + + /** Member ids repeat across lookups and files, so their parse is kept; the cache is dropped when it grows large. */ + @Nullable + private static MemberId parseMember(String id) { + MemberId cached = MEMBER_IDS.get(id); + if (cached == null) { + cached = parseMemberUncached(id); + if (MEMBER_IDS.size() >= MEMBER_IDS_LIMIT) { + MEMBER_IDS.clear(); + } + MEMBER_IDS.put(id, cached == null ? NOT_A_MEMBER : cached); + } + return cached == NOT_A_MEMBER ? null : cached; + } + + @Nullable + private static MemberId parseMemberUncached(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); + } + + 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; + } + + static String erase(String id) { + if (id.indexOf('`') < 0) { + return id; + } + StringBuilder out = new StringBuilder(id.length()); + for (int i = 0; i < id.length(); i++) { + char current = id.charAt(i); + if (current == '`') { + while (i + 1 < id.length() && Character.isDigit(id.charAt(i + 1))) { + i++; + } + } else { + out.append(current); + } + } + return out.toString(); + } + + private 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); + } + + private 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 + private 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 + private 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. */ + private 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; + } + + private static boolean truth(JsonObject object, String key) { + return object.has(key) && object.get(key).isJsonPrimitive() && object.get(key).getAsBoolean(); + } + + private 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; + } + + private static List flat(JsonObject object, String key) { + return flat(strings(object, key)); + } + + private 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 record MemberId(String owner, String name, @Nullable String params, boolean arityOnly, int arity, List paramList) { + } + + record DeclaredAnnotation(String name, List values, boolean valuesKnown) { + DeclaredAnnotation(String name, List values) { + this(name, values, 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..18786d16720 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbol.java @@ -0,0 +1,325 @@ +/* + * 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.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; + +/** + * 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 SymbolMetadata metadata; + 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 == null ? "" : name; + } + + void owner(Symbol owner) { + this.owner = owner == null ? Symbol.UNKNOWN_SYMBOL : 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 removeModifier(String modifier) { + modifiers.remove(modifier); + } + + 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); + if (hash == 0) { + hash = 1; + } + } + 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 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(); + } + + /** A nested or local record, enum or interface is implicitly static. */ + private boolean implicitlyStaticType() { + return isTypeSymbol() && owner != null && !owner.isPackageSymbol() + && (enumSymbol || interfaceSymbol || declaration() instanceof ClassTree declared && declared.is(Tree.Kind.RECORD, Tree.Kind.ENUM, Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE)); + } + + @Override + public final boolean isFinal() { + return hasModifier("final") || (inInterface() && isVariableSymbol()) || enumConstant(); + } + + /** 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() && "".equals(name) && owner instanceof JSymbol ownerType && ownerType.isTypeSymbol() && ownerType.enumSymbol; + } + + @Override + public final boolean isEnum() { + return enumSymbol; + } + + @Override + public final boolean isInterface() { + return interfaceSymbol; + } + + @Override + public final boolean isAbstract() { + if (interfaceSymbol && isTypeSymbol()) { + 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(); + } + + @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() { + if (metadata == null) { + metadata = new JSymbolMetadata(this); + } + return 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. + Symbol current = this.isTypeSymbol() ? owner() : this; + if (this.isTypeSymbol() && !(current instanceof Symbol.MethodSymbol) && !current.isTypeSymbol()) { + return (TypeSymbol) this; + } + while (current != null && !current.isTypeSymbol()) { + 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; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbolMetadata.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbolMetadata.java new file mode 100644 index 00000000000..ca47aac94ab --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JSymbolMetadata.java @@ -0,0 +1,634 @@ +/* + * 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.Arrays; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Stream; +import javax.annotation.CheckForNull; +import javax.annotation.Nullable; +import org.sonar.java.model.AnnotationValueImpl; +import org.sonar.java.model.JNullabilityData; +import org.sonar.java.model.JSymbolMetadataNullabilityHelper; +import org.sonar.java.model.LiteralUtils; +import org.sonar.java.model.ModifiersUtils; +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.NullabilityData; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.NullabilityLevel; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.NullabilityTarget; +import org.sonar.plugins.java.api.semantic.SymbolMetadata.NullabilityType; +import org.sonar.plugins.java.api.semantic.SymbolMetadata; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.AnnotationTree; +import org.sonar.plugins.java.api.tree.ArrayTypeTree; +import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; +import org.sonar.plugins.java.api.tree.ClassTree; +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.MethodTree; +import org.sonar.plugins.java.api.tree.NewArrayTree; +import org.sonar.plugins.java.api.tree.ParameterizedTypeTree; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.TypeTree; +import org.sonar.plugins.java.api.tree.VariableTree; + +/** + * Annotations of one symbol, taken from its declaration tree when the file contains it and from + * the graph fact otherwise. Nullability walks those annotations and then overridden methods. + */ +final class JSymbolMetadata implements SymbolMetadata { + + private static final NullabilityData[] NO_ANNOTATION_NULLABILITY = + forEachLevel(level -> new JNullabilityData(NullabilityType.NO_ANNOTATION, level, null, null, false)); + private static final NullabilityData[] UNKNOWN_NULLABILITY = + forEachLevel(level -> new JNullabilityData(NullabilityType.UNKNOWN, level, null, null, false)); + + private final JSymbol symbol; + private List annotations; + private final Map nullabilityCache = new EnumMap<>(NullabilityTarget.class); + + JSymbolMetadata(JSymbol symbol) { + this.symbol = symbol; + } + + private static NullabilityData[] forEachLevel(Function initializer) { + return Arrays.stream(NullabilityLevel.values()).map(initializer).toArray(NullabilityData[]::new); + } + + public static NullabilityData noNullabilityAnnotationAt(NullabilityLevel level) { + return NO_ANNOTATION_NULLABILITY[level.ordinal()]; + } + + public static NullabilityData unknownNullabilityAt(NullabilityLevel level) { + return UNKNOWN_NULLABILITY[level.ordinal()]; + } + + @Override + public List annotations() { + if (annotations == null) { + annotations = loadAnnotations(); + } + return annotations; + } + + @Override + public List symbolAnnotations() { + return annotations(); + } + + private List loadAnnotations() { + Tree declaration = symbol.declaration(); + if (declaration != null) { + List fromTree = new ArrayList<>(); + TypeTree written = declaredType(declaration); + boolean array = written instanceof ArrayTypeTree; + for (AnnotationTree annotation : ModifiersUtils.getAnnotations(declaration)) { + // an annotation only a type can carry, written before an array type, is on its elements + if (!(array && isTypeUseOnly(annotation)) && !namesDeclaredNonAnnotation(annotation)) { + fromTree.add(new TreeAnnotation(symbol.sema, annotation)); + } + } + if (written != null) { + for (AnnotationTree annotation : outermostTypeAnnotations(written)) { + fromTree.add(new TreeAnnotation(symbol.sema, annotation)); + } + } + return fromTree; + } + List fromFacts = new ArrayList<>(); + List declared = symbol instanceof JPackageSymbol ? symbol.sema.packageAnnotations(symbol.name()) : symbol.sema.declaredAnnotations(symbol.id); + for (JSema.DeclaredAnnotation annotation : declared) { + fromFacts.add(new FactAnnotation(symbol.sema, JSema.erase(annotation.name()), annotation.values(), annotation.valuesKnown())); + } + return fromFacts; + } + + /** A class or interface declared in the sources is not an annotation, whatever the code writes after the {@code @}. */ + private static boolean namesDeclaredNonAnnotation(AnnotationTree annotation) { + return annotation.annotationType().symbolType().symbol().declaration() instanceof ClassTree declared && !declared.is(Tree.Kind.ANNOTATION_TYPE); + } + + @Nullable + private static TypeTree declaredType(Tree declaration) { + if (declaration instanceof MethodTree method) { + return method.returnType(); + } + return declaration instanceof VariableTree variable ? variable.type() : null; + } + + /** The annotations written on the type itself: on an array type those of its first dimension. */ + private static List outermostTypeAnnotations(TypeTree type) { + TypeTree current = type; + while (current instanceof ArrayTypeTree array && array.type() instanceof ArrayTypeTree inner) { + current = inner; + } + if (current instanceof ArrayTypeTree array) { + return array.annotations(); + } + if (current instanceof IdentifierTree identifier) { + return identifier.annotations(); + } + if (current instanceof MemberSelectExpressionTree select) { + return select.identifier().annotations(); + } + return current instanceof ParameterizedTypeTree parameterized ? outermostTypeAnnotations(parameterized.type()) : List.of(); + } + + private static boolean isTypeUseOnly(AnnotationTree annotation) { + List targets = annotation.annotationType().symbolType().symbol().metadata().valuesForAnnotation("java.lang.annotation.Target"); + if (targets == null) { + return false; + } + Set names = new HashSet<>(); + for (AnnotationValue target : targets) { + collectTargets(target.value(), names); + } + return names.contains("TYPE_USE") && Stream.of("METHOD", "FIELD", "PARAMETER", "LOCAL_VARIABLE").noneMatch(names::contains); + } + + private static void collectTargets(@Nullable Object value, Set names) { + if (value instanceof Object[] values) { + for (Object item : values) { + collectTargets(item, names); + } + } else if (value instanceof Symbol symbol) { + names.add(symbol.name()); + } + } + + @Override + public boolean isAnnotatedWith(String fullyQualifiedName) { + for (AnnotationInstance annotation : annotations()) { + if (annotation.symbol().type().is(fullyQualifiedName)) { + return true; + } + } + return false; + } + + @Nullable + @Override + public List valuesForAnnotation(String fullyQualifiedNameOfAnnotation) { + for (AnnotationInstance annotation : annotations()) { + if (annotation.symbol().type().is(fullyQualifiedNameOfAnnotation)) { + return annotation.values(); + } + } + return null; + } + + @Override + public NullabilityData nullabilityData() { + NullabilityTarget target = target(symbol); + if (target == null) { + return unknownNullabilityAt(NullabilityLevel.UNKNOWN); + } + return nullabilityData(target); + } + + @Override + public NullabilityData nullabilityData(NullabilityTarget target) { + return nullabilityCache.computeIfAbsent(target, this::resolveNullability); + } + + @Nullable + @Override + public AnnotationTree findAnnotationTree(AnnotationInstance annotationInstance) { + Tree declaration = symbol.declaration(); + if (declaration == null) { + return null; + } + for (AnnotationTree annotation : ModifiersUtils.getAnnotations(declaration)) { + if (annotation.annotationType().symbolType().symbol().equals(annotationInstance.symbol()) + && annotation.arguments().size() == annotationInstance.values().size()) { + return annotation; + } + } + return null; + } + + @Override + public SymbolMetadata[] parametersMetadata() { + Tree declaration = symbol.declaration(); + return declaration == null ? new SymbolMetadata[0] : typeArgumentsMetadata(symbol.sema, declaredType(declaration)); + } + + private static SymbolMetadata[] typeArgumentsMetadata(JSema sema, @Nullable TypeTree written) { + if (!(written instanceof ParameterizedTypeTree parameterized)) { + return new SymbolMetadata[0]; + } + return parameterized.typeArguments().stream() + .filter(TypeTree.class::isInstance) + .map(argument -> new TypeTreeMetadata(sema, (TypeTree) argument)) + .toArray(SymbolMetadata[]::new); + } + + static boolean isAnnotatedType(TypeTree type) { + return !outermostTypeAnnotations(type).isEmpty(); + } + + static SymbolMetadata ofTypeTree(JSema sema, TypeTree type) { + return new TypeTreeMetadata(sema, type); + } + + static SymbolMetadata ofDeclared(JSema sema, List declared) { + return new DeclaredTypeMetadata(sema, declared); + } + + /** The annotations written on a type, such as an argument of a parameterized type. */ + private abstract static class AnnotatedType implements SymbolMetadata { + + private List annotations; + + abstract List loadAnnotations(); + + @Override + public List annotations() { + if (annotations == null) { + annotations = loadAnnotations(); + } + return annotations; + } + + @Override + public List symbolAnnotations() { + return annotations(); + } + + @Override + public boolean isAnnotatedWith(String fullyQualifiedName) { + return annotations().stream().anyMatch(annotation -> annotation.symbol().type().is(fullyQualifiedName)); + } + + @Nullable + @Override + public List valuesForAnnotation(String fullyQualifiedNameOfAnnotation) { + return annotations().stream() + .filter(annotation -> annotation.symbol().type().is(fullyQualifiedNameOfAnnotation)) + .map(AnnotationInstance::values) + .findFirst() + .orElse(null); + } + + @Override + public NullabilityData nullabilityData() { + return nullabilityData(NullabilityTarget.PARAMETER); + } + + @Override + public NullabilityData nullabilityData(NullabilityTarget target) { + return JSymbolMetadataNullabilityHelper.getNullabilityDataAtLevel(this, target, NullabilityLevel.VARIABLE); + } + } + + private static final class TypeTreeMetadata extends AnnotatedType { + + private final JSema sema; + private final TypeTree type; + + private TypeTreeMetadata(JSema sema, TypeTree type) { + this.sema = sema; + this.type = type; + } + + @Override + List loadAnnotations() { + return outermostTypeAnnotations(type).stream().map(annotation -> new TreeAnnotation(sema, annotation)).toList(); + } + + @Nullable + @Override + public AnnotationTree findAnnotationTree(AnnotationInstance annotationInstance) { + return outermostTypeAnnotations(type).stream() + .filter(annotation -> annotation.annotationType().symbolType().symbol().equals(annotationInstance.symbol())) + .findFirst() + .orElse(null); + } + + @Override + public SymbolMetadata[] parametersMetadata() { + return typeArgumentsMetadata(sema, type); + } + } + + /** The annotations of a type a server answer states, such as a type argument of a supertype. */ + private static final class DeclaredTypeMetadata extends AnnotatedType { + + private final JSema sema; + private final List declared; + + private DeclaredTypeMetadata(JSema sema, List declared) { + this.sema = sema; + this.declared = declared; + } + + @Override + List loadAnnotations() { + return declared.stream().map(annotation -> new FactAnnotation(sema, JSema.erase(annotation.name()), annotation.values(), annotation.valuesKnown())).toList(); + } + + @Nullable + @Override + public AnnotationTree findAnnotationTree(AnnotationInstance annotationInstance) { + return null; + } + + @Override + public SymbolMetadata[] parametersMetadata() { + return new SymbolMetadata[0]; + } + } + + private NullabilityData resolveNullability(NullabilityTarget target) { + NullabilityLevel level = level(symbol); + NullabilityData atLevel = JSymbolMetadataNullabilityHelper.getNullabilityDataAtLevel(this, target, level); + if (atLevel.type() != NullabilityType.NO_ANNOTATION) { + return atLevel; + } + if (symbol.isMethodSymbol()) { + NullabilityData inherited = inheritedNullability((Symbol.MethodSymbol) symbol, target); + if (inherited.type() != NullabilityType.NO_ANNOTATION) { + return inherited; + } + } + if (symbol.isPackageSymbol()) { + return NO_ANNOTATION_NULLABILITY[level.ordinal()]; + } + Symbol owner = symbol.owner(); + // a local or anonymous class is declared in a method or initializer; the contract of that member is not its own + while (symbol.isTypeSymbol() && owner != null && (owner.isMethodSymbol() || owner.isVariableSymbol())) { + owner = owner.owner(); + } + if (owner == null || owner.isUnknown()) { + return unknownNullabilityAt(level); + } + return owner.metadata().nullabilityData(target); + } + + private static NullabilityData inheritedNullability(Symbol.MethodSymbol method, NullabilityTarget target) { + for (Symbol.MethodSymbol overridden : method.overriddenSymbols()) { + NullabilityData data = JSymbolMetadataNullabilityHelper.getNullabilityDataAtLevel(overridden.metadata(), target, NullabilityLevel.METHOD); + if (data.type() != NullabilityType.NO_ANNOTATION && !data.equals(unknownNullabilityAt(NullabilityLevel.METHOD))) { + return data; + } + } + return NO_ANNOTATION_NULLABILITY[NullabilityLevel.METHOD.ordinal()]; + } + + private static NullabilityLevel level(Symbol symbol) { + if (symbol.isVariableSymbol()) { + return NullabilityLevel.VARIABLE; + } + if (symbol.isMethodSymbol()) { + return NullabilityLevel.METHOD; + } + if (symbol.isTypeSymbol()) { + return NullabilityLevel.CLASS; + } + if (symbol.isPackageSymbol()) { + return NullabilityLevel.PACKAGE; + } + return NullabilityLevel.UNKNOWN; + } + + @CheckForNull + private static NullabilityTarget target(Symbol symbol) { + if (symbol.isMethodSymbol()) { + return NullabilityTarget.METHOD; + } + if (!symbol.isVariableSymbol()) { + return null; + } + Symbol owner = symbol.owner(); + if (owner != null && owner.isTypeSymbol()) { + return NullabilityTarget.FIELD; + } + Tree declaration = symbol.declaration(); + if (declaration == null || declaration.parent() == null || declaration.parent() instanceof MethodTree) { + return NullabilityTarget.PARAMETER; + } + if (declaration.parent().is(Tree.Kind.LAMBDA_EXPRESSION)) { + return null; + } + return NullabilityTarget.LOCAL_VARIABLE; + } + + static final class JNullabilityData implements NullabilityData { + + private final NullabilityType type; + private final NullabilityLevel level; + @Nullable + private final AnnotationInstance annotation; + @Nullable + private final AnnotationTree annotationTree; + private final boolean metaAnnotation; + + public JNullabilityData(NullabilityType type, NullabilityLevel level, @Nullable AnnotationInstance annotation, + @Nullable AnnotationTree annotationTree, boolean metaAnnotation) { + this.type = type; + this.level = level; + this.annotation = annotation; + this.annotationTree = annotationTree; + this.metaAnnotation = metaAnnotation; + } + + @Override + public NullabilityType type() { + return type; + } + + @Override + public NullabilityLevel level() { + return level; + } + + @Override + public boolean metaAnnotation() { + return metaAnnotation; + } + + @Override + public boolean isNonNull(NullabilityLevel minLevel, boolean ignoreMetaAnnotation, boolean defaultValue) { + return test(minLevel, ignoreMetaAnnotation, defaultValue, candidate -> candidate == NullabilityType.NON_NULL); + } + + @Override + public boolean isNullable(NullabilityLevel minLevel, boolean ignoreMetaAnnotation, boolean defaultValue) { + return test(minLevel, ignoreMetaAnnotation, defaultValue, + candidate -> candidate == NullabilityType.STRONG_NULLABLE || candidate == NullabilityType.WEAK_NULLABLE); + } + + @Override + public boolean isStrongNullable(NullabilityLevel minLevel, boolean ignoreMetaAnnotation, boolean defaultValue) { + return test(minLevel, ignoreMetaAnnotation, defaultValue, candidate -> candidate == NullabilityType.STRONG_NULLABLE); + } + + private boolean test(NullabilityLevel minLevel, boolean ignoreMetaAnnotation, boolean defaultValue, Predicate typePredicate) { + if (type == NullabilityType.NO_ANNOTATION) { + return false; + } + if (type == NullabilityType.UNKNOWN || (ignoreMetaAnnotation && metaAnnotation)) { + return defaultValue; + } + return typePredicate.test(type) && minLevel.ordinal() <= level.ordinal(); + } + + @Nullable + @Override + public AnnotationInstance annotation() { + return annotation; + } + + @Nullable + @Override + public Tree declaration() { + return annotationTree; + } + } + + static final class TreeAnnotation implements AnnotationInstance { + + private final JSema sema; + private final AnnotationTree tree; + + private TreeAnnotation(JSema sema, AnnotationTree tree) { + this.sema = sema; + this.tree = tree; + } + + @Override + public Symbol symbol() { + Type type = tree.annotationType().symbolType(); + if (type.isUnknown() && tree.symbolType().isUnknown() && !"!Unknown!".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; + } + + /** + * 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() instanceof Symbol.TypeSymbol annotation + && annotation.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; + } + default -> value; + }; + } + + 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 = expression instanceof MemberSelectExpressionTree select ? select.identifier().symbol() + : (expression instanceof IdentifierTree identifier ? identifier.symbol() : null); + if (symbol instanceof Symbol.VariableSymbol variable && !variable.isUnknown()) { + return variable.constantValue().orElse(variable.isEnum() ? variable : null); + } + if (symbol != null && symbol.isUnknown()) { + return Symbol.UNKNOWN_SYMBOL; + } + return expression.toString(); + } + + } + + private static final class FactAnnotation implements AnnotationInstance { + + private final Symbol symbol; + private final List values; + + private FactAnnotation(JSema sema, String fqn, List values, boolean valuesKnown) { + this.symbol = sema.typeSymbol(fqn); + // An annotation known by name only keeps one unknown value, so a consumer that reads a value never meets an empty list. + this.values = valuesKnown ? values : List.of(new AnnotationValueImpl("value", null)); + } + + @Override + public Symbol symbol() { + return symbol; + } + + @Override + public List values() { + return values; + } + } +} 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..4c8c6173d8d --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JType.java @@ -0,0 +1,543 @@ +/* + * 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.HashSet; +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, Type.ArrayType { + + enum Kind { + NAMED, PRIMITIVE, VOID, NULL, ARRAY, TYPEVAR, UNKNOWN, INTERSECTION, CAPTURE, WILDCARD + } + + /** Marks a parameterization the compiler builds itself; compared by identity. */ + private static final List INFERRED = Collections.unmodifiableList(new ArrayList<>()); + + 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; + private final List intersection; + @Nullable + private final JType lower; + /** The parameterized enclosing type of an inner class of a generic class, which gives the inner class's members the outer type arguments. */ + @Nullable + private JType outer; + + private JType(JSema sema, Kind kind, String fqn, List args, @Nullable JType element, @Nullable String typeVarId, List intersection) { + this(sema, kind, fqn, args, element, typeVarId, intersection, null); + } + + private JType(JSema sema, Kind kind, String fqn, List args, @Nullable JType element, @Nullable String typeVarId, List intersection, + @Nullable JType lower) { + this.sema = sema; + this.kind = kind; + this.fqn = fqn; + this.args = args; + this.element = element; + this.typeVarId = typeVarId; + this.intersection = intersection; + this.lower = lower; + } + + @Nullable + JType outer() { + return outer; + } + + /** A copy of this class type that is an inner class of the parameterized {@code enclosing} type. */ + JType withOuter(JType enclosing) { + JType copy = new JType(sema, kind, fqn, args, element, typeVarId, intersection, lower); + copy.outer = enclosing; + return copy; + } + + static JType named(JSema sema, String fqn, List args) { + return new JType(sema, Kind.NAMED, fqn, List.copyOf(args), null, null, List.of()); + } + + /** A parameterization the compiler builds itself, like the type of a class literal: its arguments are not checked. */ + static JType inferred(JSema sema, String fqn, List args) { + return new JType(sema, Kind.NAMED, fqn, List.copyOf(args), null, null, INFERRED); + } + + 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, "", List.of(), null, null, List.of()); + } + + static JType unknown(JSema sema) { + return new JType(sema, Kind.UNKNOWN, "!Unknown!", List.of(), null, null, List.of()); + } + + static JType array(JSema sema, JType element) { + return new JType(sema, Kind.ARRAY, element.fullyQualifiedName() + "[]", 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 (substitution.isEmpty()) { + return this; + } + if (kind == Kind.TYPEVAR) { + Type found = typeVarId == null ? null : substitution.get(typeVarId); + if (found == null) { + found = substitution.get(fqn); + } + if (found instanceof JType replaced) { + return replaced; + } + } + if (kind == Kind.CAPTURE && element != null) { + JType replaced = element.substitute(substitution); + return replaced == element ? this : capture(sema, replaced); + } + if (kind == Kind.WILDCARD && lower != null) { + JType replaced = lower.substitute(substitution); + return replaced == lower ? this : superWildcard(sema, replaced); + } + if (kind == Kind.WILDCARD && element != null) { + JType replaced = element.substitute(substitution); + return replaced == element ? this : wildcard(sema, replaced); + } + if (kind == Kind.ARRAY && element != null) { + JType replaced = element.substitute(substitution); + return replaced == element ? this : array(sema, replaced); + } + if (kind == Kind.NAMED && !args.isEmpty()) { + 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; + } + 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 = sema.getClassType("java.lang.Object") instanceof JType type ? type : unknown(sema); + return new JType(sema, Kind.WILDCARD, object.fullyQualifiedName(), List.of(), object, null, List.of(), lower); + } + + boolean isWildcard() { + return kind == Kind.WILDCARD; + } + + /** The type a lambda sees for this type argument: the bound a wildcard is written with, or the type itself. */ + JType groundType() { + if (kind != Kind.WILDCARD) { + return this; + } + return lower != null ? lower : element; + } + + static JType intersection(JSema sema, List bounds) { + String name = bounds.stream().map(JType::fullyQualifiedName).sorted().reduce((a, b) -> a + " & " + b).orElse("!Unknown!"); + 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 isSubtypeOf(superType, new HashSet<>()); + } + + private boolean isSubtypeOf(Type superType, Set visited) { + if ((kind == Kind.CAPTURE || kind == Kind.WILDCARD) && element != null) { + return element.isSubtypeOf(superType, visited); + } + if (superType == null || superType.isUnknown() || isUnknown()) { + return false; + } + if (isNullType()) { + return !superType.isPrimitive(); + } + if (!visited.add(fullyQualifiedName() + ">" + superType.fullyQualifiedName())) { + return false; + } + if (superType.isTypeVar()) { + if (isTypeVar() && superType instanceof JType other && Objects.equals(typeVarId, other.typeVarId)) { + return true; + } + if (!isTypeVar()) { + return false; + } + } + if (!isArray() && sameErasure(superType) && argumentsMatch(superType)) { + return true; + } + if (isPrimitive() && superType.isPrimitive()) { + return widensTo(fullyQualifiedName(), superType.fullyQualifiedName()); + } + if (kind == Kind.INTERSECTION) { + return intersection.stream().anyMatch(bound -> bound.isSubtypeOf(superType, visited)); + } + if (isArray()) { + if (superType.isArray()) { + return elementType().isSubtypeOf(((Type.ArrayType) superType).elementType()); + } + return superType.is("java.lang.Object") || superType.is("java.lang.Cloneable") || superType.is("java.io.Serializable"); + } + if (isTypeVar()) { + return sema.typeVariableBounds(typeVarId).stream() + .anyMatch(bound -> bound instanceof JType upper && !upper.isUnknown() && upper != this && upper.isSubtypeOf(superType, visited)); + } + if (isPrimitive() || superType.isPrimitive()) { + return false; + } + Symbol.TypeSymbol owner = declaredSymbol(); + if (owner.isUnknown()) { + return false; + } + // 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 && erasedSuper.isSubtypeOf(superType, visited)) { + return true; + } + for (Type iface : owner.interfaces()) { + if (iface.erasure() instanceof JType erasedIface && erasedIface.isSubtypeOf(superType, visited)) { + return true; + } + } + return false; + } + + private boolean sameErasure(Type superType) { + return fullyQualifiedName().equals(superType.erasure().fullyQualifiedName()); + } + + private boolean argumentsMatch(Type superType) { + List theirs = superType.typeArguments(); + if (args.isEmpty() || theirs.isEmpty()) { + return true; + } + if (args.size() != theirs.size()) { + return false; + } + for (int i = 0; i < args.size(); i++) { + if (!contains(theirs.get(i), 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 == null || wanted.element.is("java.lang.Object")) { + return true; + } + return mine.isSubtypeOf(wanted.element); + } + return !mine.isWildcard() && mine.is(theirs.fullyQualifiedName()); + } + + private static boolean widensTo(String from, String to) { + if (from.equals(to)) { + return true; + } + 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; + }; + } + + @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() { + if (kind != Kind.NAMED || isUnknown()) { + return false; + } + Symbol.TypeSymbol owner = declaredSymbol(); + return owner instanceof JTypeSymbol typeSymbol && typeSymbol.typeParameterCount() > 0 && args.isEmpty(); + } + + @Override + public Type declaringType() { + if (isUnknown() || kind != Kind.NAMED) { + return this; + } + if (isRawType()) { + return declaredSymbol() instanceof JTypeSymbol typeSymbol ? typeSymbol.declaringType(this) : this; + } + return sema.getClassType(fqn); + } + + @Override + public boolean isUnknown() { + if (kind == Kind.UNKNOWN) { + return true; + } + if (kind == Kind.ARRAY && element != null) { + return element.isUnknown(); + } + if (kind == Kind.NAMED) { + Symbol.TypeSymbol owner = declaredSymbol(); + // the compiler cannot bind a parameterization with an argument nothing declares + return owner.isUnknown() || (intersection != INFERRED && args.stream().anyMatch(JType::isUnknown)); + } + return false; + } + + @Override + public boolean isNumerical() { + return NUMERIC.contains(fullyQualifiedName()); + } + + @Override + public String fullyQualifiedName() { + return fqn; + } + + @Override + public String name() { + if (kind == Kind.NULL) { + return ""; + } + if (kind == Kind.ARRAY) { + return element.name() + "[]"; + } + if (kind == Kind.WILDCARD) { + if (lower != null) { + return "? super " + lower.name(); + } + return element == null || element.is("java.lang.Object") ? "?" : "? extends " + element.name(); + } + int boundary = Math.max(fqn.lastIndexOf('.'), fqn.lastIndexOf('$')); + String simple = boundary < 0 ? fqn : fqn.substring(boundary + 1); + return JSema.isAnonymousName(simple) ? "" : simple; + } + + @Override + public String toString() { + return name(); + } + + @Override + public Symbol.TypeSymbol symbol() { + Symbol.TypeSymbol declared = declaredSymbol(); + return !args.isEmpty() && declared instanceof JTypeSymbol generic ? generic.parameterizedAs(this) : declared; + } + + private Symbol.TypeSymbol declaredSymbol() { + return switch (kind) { + case ARRAY -> sema.arraySymbol(element); + case PRIMITIVE, VOID -> sema.primitiveSymbol(fqn); + case TYPEVAR -> sema.resolveTypeSymbol(typeVarId); + case NULL, UNKNOWN, INTERSECTION -> Symbol.TypeSymbol.UNKNOWN_TYPE; + case CAPTURE, WILDCARD -> element == null ? Symbol.TypeSymbol.UNKNOWN_TYPE : element.symbol(); + case NAMED -> sema.typeSymbol(fqn); + }; + } + + @Override + public Type erasure() { + if ((kind == Kind.CAPTURE || kind == Kind.WILDCARD) && element != null) { + 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.typeVariableBound(typeVarId); + return bound == this ? this : bound.erasure(); + } + return this; + } + + @Override + public boolean isParameterized() { + return kind == Kind.NAMED && !args.isEmpty() && !isGenericSelf(); + } + + /** 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)); + } + + @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 (intersection.isEmpty()) { + return new Type[] {this}; + } + return intersection.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); + } + + /** 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 kind == Kind.TYPEVAR && typeVarId != null && other.typeVarId != null && (typeVarId.indexOf('<') < 0 || other.typeVarId.indexOf('<') < 0); + } + + @Override + public int hashCode() { + return fqn.hashCode(); + } +} 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..5790dc8be26 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JTypeSymbol.java @@ -0,0 +1,488 @@ +/* + * 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.HashSet; +import java.util.List; +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.TypeTree; + +final class JTypeSymbol extends JSymbol implements Symbol.TypeSymbol { + + private static final String ENUM = "java.lang.Enum"; + + 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 Collection members; + @Nullable + private Type declaredSuperClass; + private List declaredInterfaces = List.of(); + @Nullable + private JTypeSymbol generic; + + JTypeSymbol(JSema sema, @Nullable String id, String name, boolean typeParameter) { + super(sema, Kind.TYPE, id, name); + this.typeParameter = typeParameter; + } + + /** + * 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); + } + + boolean isTypeParameter() { + return typeParameter; + } + + private List boundTrees = List.of(); + + void boundTrees(List bounds) { + this.boundTrees = List.copyOf(bounds); + } + + /** 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; + } + + void interfaceNames(List interfaceNames) { + this.interfaceNames = interfaceNames; + } + + /** 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; + } + + /** 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; + } + } + + void memberFacts(List memberFacts) { + this.memberFacts = memberFacts; + this.members = null; + } + + List memberFacts() { + return memberFacts; + } + + void elementFqn(@Nullable String elementFqn) { + this.elementFqn = elementFqn; + } + + @CheckForNull + @Override + public Type superClass() { + if (typeParameter || elementFqn != null) { + return sema.getClassType("java.lang.Object"); + } + if (isInterface() || isAnnotation()) { + return sema.getClassType("java.lang.Object"); + } + String erased = JSema.erase(id == null ? name() : id); + if ("java.lang.Object".equals(erased)) { + return null; + } + boolean noSuper = superName == null || superName.isEmpty(); + if (isEnum() && superTypeFact == null && (noSuper || ENUM.equals(JSema.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("java.lang.Object"); + } + if (namesSameClass(superTypeFact, superName)) { + return sema.supertypeFromFact(superTypeFact); + } + return withDeclaredArguments(sema.getClassType(JSema.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 = JSema.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 = JSema.erase(parent.superName); + } + return false; + } + + @Override + public List interfaces() { + List declared = ownInterfaces(); + if (generic == null || type() == null || !type().isParameterized()) { + return declared; + } + return declared.stream().map(iface -> sema.instantiateSupertype(type(), iface)).toList(); + } + + private List ownInterfaces() { + List resolved = resolvedInterfaces(); + List unresolved = declaredInterfaces.stream() + .filter(Type::isUnknown) + .filter(distinctByName(new HashSet<>())) + .filter(declared -> resolved.stream().noneMatch(known -> known.fullyQualifiedName().equals(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 generic = interfaceTypeFacts.size() == interfaceNames.size(); + List types = new ArrayList<>(); + for (int i = 0; i < interfaceNames.size(); i++) { + String name = interfaceNames.get(i); + JsonObject fact = generic ? interfaceTypeFacts.get(i) : null; + Type erased = sema.getClassType(JSema.erase(name)); + types.add(namesSameClass(fact, name) ? sema.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() || isAnnotation() || typeParameter || elementFqn != null) { + return null; + } + String erased = JSema.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() + && JSema.erase(fact.get("id").getAsString()).equals(JSema.erase(name)); + } + + @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.memberFromTypeInfo(this, member)); + } + } + addImplicitConstructor(resolved); + addImplicitEnumMethods(resolved); + addDeclaredMembers(resolved); + members = resolved; + } + return members; + } + + /** 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 org.sonar.plugins.java.api.tree.ClassTree tree) || resolved.stream().anyMatch(member -> !member.name().endsWith(""))) { + return; + } + tree.recordComponents().forEach(component -> resolved.add(component.symbol())); + for (org.sonar.plugins.java.api.tree.Tree member : tree.members()) { + if (member instanceof org.sonar.plugins.java.api.tree.VariableTree variable) { + resolved.add(variable.symbol()); + } else if (member instanceof org.sonar.plugins.java.api.tree.MethodTree method && !method.is(org.sonar.plugins.java.api.tree.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() && "".equals(member.name()))) { + return; + } + Symbol constructor = sema.resolve(id + "#()"); + if (!constructor.isUnknown()) { + resolved.add(constructor); + } + } + + @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); + } + List found = new ArrayList<>(); + if (members != null || id == null || sema.inDocument(id) || declaration() != null) { + // The implicit members of a type this file declares depend on all of its members. + for (Symbol member : memberSymbols()) { + if (name.equals(member.name())) { + found.add(member); + } + } + return found; + } + for (JsonObject member : memberFacts) { + if (!isTypeParameterFact(member) && mayBeNamed(member, name)) { + Symbol symbol = sema.memberFromTypeInfo(this, member); + if (name.equals(symbol.name())) { + found.add(symbol); + } + } + } + return found; + } + + /** False only when the fact surely names another member: by its written name, or by the name its id gives. */ + private boolean mayBeNamed(JsonObject member, String name) { + if (member.get("id") instanceof JsonPrimitive memberId) { + String simple = JSema.memberName(memberId.getAsString()); + return simple == null || simple.equals(name) || !isIdentifier(simple); + } + if (member.has("id")) { + return true; + } + return !(member.get("name") instanceof JsonPrimitive written) || name.equals(written.getAsString()); + } + + 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; + } + + @Nullable + @Override + public ClassTree declaration() { + return super.declaration() instanceof ClassTree classTree ? classTree : null; + } + + @Override + public Set superTypes() { + if (isUnknown()) { + return Collections.emptySet(); + } + Set collected = new HashSet<>(); + collectSuperTypes(collected, new HashSet<>(), type()); + return collected; + } + + /** 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(JSema.erase(id == null ? name() : id))) { + return; + } + Type superClass = superClass(); + if (superClass != null && superClass.isUnknown() && isRecovered(superClass)) { + collected.add(superClass); + } else if (superClass != null && !superClass.isUnknown()) { + Type instantiated = sema.instantiateSupertype(from, superClass); + collected.add(instantiated); + if (superClass.symbol() instanceof JTypeSymbol parent) { + parent.collectSuperTypes(collected, visited, instantiated); + } + } + for (Type iface : interfaces()) { + if (iface.isUnknown() && isRecovered(iface)) { + collected.add(iface); + } else if (!iface.isUnknown()) { + Type instantiated = sema.instantiateSupertype(from, iface); + collected.add(instantiated); + if (iface.symbol() instanceof JTypeSymbol parent) { + parent.collectSuperTypes(collected, visited, instantiated); + } + } + } + } + + @Nullable + @Override + public TypeSymbol outermostClass() { + Symbol current = this; + Symbol result = this; + while (current != null && !current.isPackageSymbol()) { + result = current; + current = current.owner(); + } + return result instanceof TypeSymbol typeSymbol ? typeSymbol : this; + } + + @Override + public boolean isAnnotation() { + return !isUnknown() && isAnnotationSymbol(); + } + + /** 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 != Type.UNKNOWN && !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..c5c4855c255 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JVariableSymbol.java @@ -0,0 +1,271 @@ +/* + * 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.AnnotationTree; +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 Optional constant; + + 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 = Optional.ofNullable(value); + } + + @Nullable + @Override + public VariableTree declaration() { + return (VariableTree) super.declaration(); + } + + @Override + public boolean isEffectivelyFinal() { + return isFinal() || effectivelyFinal; + } + + @Override + public Optional constantValue() { + if (constant == null) { + Object declared = declaredConstant(); + constant = Optional.ofNullable(declared != null ? declared : sema.servedConstant(this)); + } + return constant; + } + + /** 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 || !isStaticFinalOrInterfaceMember()) { + 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 boolean isStaticFinalOrInterfaceMember() { + boolean constantKind = isFinal() || owner().isInterface() || isEnum(); + return constantKind && (isStatic() || owner().isInterface()); + } + + @Nullable + private static Object literalNumber(LiteralTree literal) { + String text = literal.value().replace("_", ""); + try { + return switch (literal.kind()) { + case LONG_LITERAL -> LiteralUtils.longLiteralValue(literal); + case FLOAT_LITERAL -> Float.valueOf(text); + default -> Double.valueOf(text); + }; + } catch (NumberFormatException e) { + return null; + } + } + + @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; + } + + @Override + public boolean isLocalVariable() { + return local || owner().isMethodSymbol(); + } + + @Override + public boolean isParameter() { + return parameter; + } + + 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 == null ? Type.UNKNOWN : 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 PlaceholderMetadata.INSTANCE; + } + + @Override + public boolean isVariableSymbol() { + return true; + } + + @Override + public boolean isFinal() { + return false; + } + } + /** A parameter no source declares carries no annotation, so nothing is known to be nullable or not. */ + private static final class PlaceholderMetadata implements SymbolMetadata { + static final PlaceholderMetadata INSTANCE = new PlaceholderMetadata(); + + @Override + public boolean isAnnotatedWith(String fullyQualifiedName) { + return false; + } + + @Nullable + @Override + public List valuesForAnnotation(String fullyQualifiedNameOfAnnotation) { + return null; + } + + @Override + public List annotations() { + return Collections.emptyList(); + } + + @Override + public List symbolAnnotations() { + return Collections.emptyList(); + } + + @Override + public NullabilityData nullabilityData() { + return JSymbolMetadata.noNullabilityAnnotationAt(NullabilityLevel.PACKAGE); + } + + @Override + public NullabilityData nullabilityData(NullabilityTarget target) { + return JSymbolMetadata.noNullabilityAnnotationAt(NullabilityLevel.PACKAGE); + } + + @Nullable + @Override + public AnnotationTree findAnnotationTree(AnnotationInstance annotationInstance) { + return null; + } + + @Override + public SymbolMetadata[] parametersMetadata() { + return new SymbolMetadata[0]; + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JWarning.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JWarning.java new file mode 100644 index 00000000000..6052b3ee1d1 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/JWarning.java @@ -0,0 +1,170 @@ +/* + * 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.Comparator; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.sonar.java.annotations.VisibleForTesting; +import org.sonar.java.ast.visitors.SubscriptionVisitor; +import org.sonar.java.model.JavaTree; +import org.sonar.java.model.location.InternalPosition; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; +import org.sonar.plugins.java.api.location.Position; +import org.sonar.plugins.java.api.tree.Tree; + +import static org.sonar.plugins.java.api.location.Position.endOf; +import static org.sonar.plugins.java.api.location.Position.startOf; + +public final class JWarning extends JProblem implements Warning { + private final Position start; + private final Position end; + + private Tree syntaxTree; + + JWarning(String message, ProblemKind type, int startLine, int startColumnOffset, int endLine, int endColumnOffset) { + super(message, type); + this.start = InternalPosition.atOffset(startLine, startColumnOffset); + this.end = InternalPosition.atOffset(endLine, endColumnOffset); + } + + JWarning(String message, ProblemKind type, Tree syntaxTree) { + super(message, type); + this.start = startOf(syntaxTree); + this.end = endOf(syntaxTree); + this.syntaxTree = syntaxTree; + } + + @Override + public Tree syntaxTree() { + return Objects.requireNonNull(syntaxTree); + } + + Position start() { + return start; + } + + Position end() { + return end; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof JWarning)) { + return false; + } + if (!super.equals(o)) { + return false; + } + JWarning jWarning = (JWarning) o; + // skip syntaxTree + return start.equals(jWarning.start) && end.equals(jWarning.end); + } + + @Override + public int hashCode() { + // skip syntaxTree + return Objects.hash(super.hashCode(), start, end); + } + + public static class Mapper extends SubscriptionVisitor { + + private static final Set KINDS = Stream.of(ProblemKind.values()) + .map(JProblem::kinds) + .flatMap(Set::stream) + .collect(Collectors.toSet()); + + private final Map> warningsByType = new EnumMap<>(ProblemKind.class); + + private final PriorityQueue warnings = new PriorityQueue<>(Comparator.comparing(JWarning::start).thenComparing(JWarning::end)); + + private Mapper() { + } + + public void mappedInto(JavaTree.CompilationUnitTreeImpl cut) { + scanTree(cut); + cut.addWarnings(warningsByType); + } + + @Override + public List nodesToVisit() { + return new ArrayList<>(KINDS); + } + + @Override + public void visitNode(Tree tree) { + if (warnings.isEmpty()) { + return; + } + for (Iterator iterator = warnings.iterator(); iterator.hasNext();) { + JWarning warning = iterator.next(); + if (isInsideTree(warning, tree)) { + setSyntaxTree(warning, tree); + warningsByType.computeIfAbsent(warning.type(), k -> new LinkedHashSet<>()).add(warning); + + if (matchesTreeExactly(warning)) { + iterator.remove(); + } + } + } + } + + @VisibleForTesting + static void setSyntaxTree(JWarning warning, Tree tree) { + if (warning.syntaxTree == null || isMorePreciseTree(warning.syntaxTree, tree)) { + warning.syntaxTree = tree; + } + } + + @VisibleForTesting + static boolean isInsideTree(JWarning warning, Tree tree) { + if (JProblem.kinds(warning.type()).stream().noneMatch(tree::is)) { + // wrong kind + return false; + } + return warning.start().compareTo(startOf(tree)) >= 0 + && warning.end().compareTo(endOf(tree)) <= 0; + } + + @VisibleForTesting + static boolean isMorePreciseTree(Tree currentTree, Tree newTree) { + return startOf(newTree).compareTo(startOf(currentTree)) >= 0 + && endOf(newTree).compareTo(endOf(currentTree)) <= 0; + } + + @VisibleForTesting + static boolean matchesTreeExactly(JWarning warning) { + Tree syntaxTree = warning.syntaxTree(); + return warning.start().compareTo(startOf(syntaxTree)) == 0 + && warning.end().compareTo(endOf(syntaxTree)) == 0; + } + } + +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParserProvider.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParserProvider.java index 45b4716ad55..e69d95d41c1 100644 --- a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParserProvider.java +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParserProvider.java @@ -58,7 +58,7 @@ public final class SemSitterParserProvider implements JParserProvider { private volatile Path executable; public SemSitterParserProvider() { - this(LaunchDarklyFeatureFlags::connect, System::getenv, null); + this(LaunchDarklyFeatureFlags::connect, System::getenv, SemSitterTranslator::translate); } SemSitterParserProvider(FeatureFlags.Connector flags, UnaryOperator environment, @Nullable DocumentTranslator translator) { diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterTranslator.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterTranslator.java new file mode 100644 index 00000000000..750376ac564 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterTranslator.java @@ -0,0 +1,4030 @@ +/* + * 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.sonar.sslr.api.RecognitionException; +import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import org.sonar.java.ast.parser.ArgumentListTreeImpl; +import org.sonar.java.ast.parser.FormalParametersListTreeImpl; +import org.sonar.java.ast.parser.InitializerListTreeImpl; +import org.sonar.java.ast.parser.ModuleNameListTreeImpl; +import org.sonar.java.ast.parser.ModuleNameTreeImpl; +import org.sonar.java.ast.parser.QualifiedIdentifierListTreeImpl; +import org.sonar.java.ast.parser.ResourceListTreeImpl; +import org.sonar.java.ast.parser.StatementListTreeImpl; +import org.sonar.java.ast.parser.TypeParameterListTreeImpl; +import org.sonar.java.model.AbstractTypedTree; +import org.sonar.java.model.ArrayDimensionTreeImpl; +import org.sonar.java.model.InternalSyntaxToken; +import org.sonar.java.model.InternalSyntaxTrivia; +import org.sonar.java.model.JLabelSymbol; +import org.sonar.java.model.JParseResult; +import org.sonar.java.model.JavaTree; +import org.sonar.java.model.KeywordSuper; +import org.sonar.java.model.KeywordThis; +import org.sonar.java.model.ModifiersUtils; +import org.sonar.java.model.Symbols; +import org.sonar.java.model.TypeParameterTreeImpl; +import org.sonar.java.model.declaration.AnnotationTreeImpl; +import org.sonar.java.model.declaration.ClassTreeImpl; +import org.sonar.java.model.declaration.EnumConstantTreeImpl; +import org.sonar.java.model.declaration.ExportsDirectiveTreeImpl; +import org.sonar.java.model.declaration.MethodTreeImpl; +import org.sonar.java.model.declaration.ModifierKeywordTreeImpl; +import org.sonar.java.model.declaration.ModifiersTreeImpl; +import org.sonar.java.model.declaration.ModuleDeclarationTreeImpl; +import org.sonar.java.model.declaration.OpensDirectiveTreeImpl; +import org.sonar.java.model.declaration.ProvidesDirectiveTreeImpl; +import org.sonar.java.model.declaration.RequiresDirectiveTreeImpl; +import org.sonar.java.model.declaration.UsesDirectiveTreeImpl; +import org.sonar.java.model.declaration.VariableTreeImpl; +import org.sonar.java.model.expression.ArrayAccessExpressionTreeImpl; +import org.sonar.java.model.expression.AssignmentExpressionTreeImpl; +import org.sonar.java.model.expression.BinaryExpressionTreeImpl; +import org.sonar.java.model.expression.ConditionalExpressionTreeImpl; +import org.sonar.java.model.expression.IdentifierTreeImpl; +import org.sonar.java.model.expression.InstanceOfTreeImpl; +import org.sonar.java.model.expression.InternalPostfixUnaryExpression; +import org.sonar.java.model.expression.InternalPrefixUnaryExpression; +import org.sonar.java.model.expression.LambdaExpressionTreeImpl; +import org.sonar.java.model.expression.LiteralTreeImpl; +import org.sonar.java.model.expression.MemberSelectExpressionTreeImpl; +import org.sonar.java.model.expression.MethodInvocationTreeImpl; +import org.sonar.java.model.expression.MethodReferenceTreeImpl; +import org.sonar.java.model.expression.NewArrayTreeImpl; +import org.sonar.java.model.expression.NewClassTreeImpl; +import org.sonar.java.model.expression.ParenthesizedTreeImpl; +import org.sonar.java.model.expression.TypeArgumentListTreeImpl; +import org.sonar.java.model.expression.TypeCastExpressionTreeImpl; +import org.sonar.java.model.expression.VarTypeTreeImpl; +import org.sonar.java.model.pattern.DefaultPatternTreeImpl; +import org.sonar.java.model.pattern.GuardedPatternTreeImpl; +import org.sonar.java.model.pattern.NullPatternTreeImpl; +import org.sonar.java.model.pattern.RecordPatternTreeImpl; +import org.sonar.java.model.pattern.TypePatternTreeImpl; +import org.sonar.java.model.statement.AssertStatementTreeImpl; +import org.sonar.java.model.statement.BlockTreeImpl; +import org.sonar.java.model.statement.BreakStatementTreeImpl; +import org.sonar.java.model.statement.CaseGroupTreeImpl; +import org.sonar.java.model.statement.CaseLabelTreeImpl; +import org.sonar.java.model.statement.CatchTreeImpl; +import org.sonar.java.model.statement.ContinueStatementTreeImpl; +import org.sonar.java.model.statement.DoWhileStatementTreeImpl; +import org.sonar.java.model.statement.EmptyStatementTreeImpl; +import org.sonar.java.model.statement.ExpressionStatementTreeImpl; +import org.sonar.java.model.statement.ForEachStatementImpl; +import org.sonar.java.model.statement.ForStatementTreeImpl; +import org.sonar.java.model.statement.IfStatementTreeImpl; +import org.sonar.java.model.statement.LabeledStatementTreeImpl; +import org.sonar.java.model.statement.ReturnStatementTreeImpl; +import org.sonar.java.model.statement.StaticInitializerTreeImpl; +import org.sonar.java.model.statement.SwitchExpressionTreeImpl; +import org.sonar.java.model.statement.SwitchStatementTreeImpl; +import org.sonar.java.model.statement.SynchronizedStatementTreeImpl; +import org.sonar.java.model.statement.ThrowStatementTreeImpl; +import org.sonar.java.model.statement.TryStatementTreeImpl; +import org.sonar.java.model.statement.WhileStatementTreeImpl; +import org.sonar.java.model.statement.YieldStatementTreeImpl; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.AnnotationTree; +import org.sonar.plugins.java.api.tree.ArrayDimensionTree; +import org.sonar.plugins.java.api.tree.ArrayTypeTree; +import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.CaseGroupTree; +import org.sonar.plugins.java.api.tree.CaseLabelTree; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.ConditionalExpressionTree; +import org.sonar.plugins.java.api.tree.ExpressionStatementTree; +import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.ImportClauseTree; +import org.sonar.plugins.java.api.tree.InferedTypeTree; +import org.sonar.plugins.java.api.tree.LambdaExpressionTree; +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; +import org.sonar.plugins.java.api.tree.MethodTree; +import org.sonar.plugins.java.api.tree.Modifier; +import org.sonar.plugins.java.api.tree.ModifierTree; +import org.sonar.plugins.java.api.tree.ModuleDeclarationTree; +import org.sonar.plugins.java.api.tree.ModuleDirectiveTree; +import org.sonar.plugins.java.api.tree.ParameterizedTypeTree; +import org.sonar.plugins.java.api.tree.PatternTree; +import org.sonar.plugins.java.api.tree.ReturnStatementTree; +import org.sonar.plugins.java.api.tree.StatementTree; +import org.sonar.plugins.java.api.tree.SwitchExpressionTree; +import org.sonar.plugins.java.api.tree.SyntaxToken; +import org.sonar.plugins.java.api.tree.SyntaxTrivia; +import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.TypeParameterTree; +import org.sonar.plugins.java.api.tree.TypeTree; +import org.sonar.plugins.java.api.tree.VariableTree; +import org.sonar.plugins.java.api.tree.WildcardTree; +import org.sonar.plugins.java.api.tree.YieldStatementTree; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Ref; + +/** + * Builds the SonarJava AST from one SemSitter CST document. + * Positions come from the CST. Symbols and types come from {@link JSema}. + */ +final class SemSitterTranslator { + + private static final String BOUND = "bound"; + + private static final Pattern ARITY_ONLY = Pattern.compile("[^#]+#[^#(]+\\(\\d+\\)"); + private final JSema sema; + private final Map tokens = new IdentityHashMap<>(); + private final Deque labels = new ArrayDeque<>(); + private final Deque types = new ArrayDeque<>(); + private InternalSyntaxToken eof = new InternalSyntaxToken(1, 0, "", List.of(), true); + private boolean switchExpression; + private static final List FINAL_MODIFIER = List.of("final"); + private String implicitClassName = ""; + private String packageName = ""; + private boolean naming; + private final Map singleImports = new HashMap<>(); + private final List onDemandImports = new ArrayList<>(); + private final Map staticImports = new HashMap<>(); + private final List staticOnDemandImports = new ArrayList<>(); + private final Deque> scopes = new ArrayDeque<>(); + private final Deque returnTargets = new ArrayDeque<>(); + private final Set rawResults = new HashSet<>(); + + /** Whether {@code _} declares an unnamed variable (Java 22 and later) instead of a plain name. */ + private boolean unnamedVariables = true; + private boolean records = true; + /** Whether consecutive {@code ///} lines form one Markdown comment (Java 23 and later). */ + private boolean markdownComments = true; + + /** Work that needs declarations met later in the file. */ + private final List deferred = new ArrayList<>(); + + private SemSitterTranslator(JSema sema) { + this.sema = sema; + } + + static JParseResult translate(Document document, Function, JsonObject> types, Function packages, boolean noLibraries, + int javaVersion) { + JSema sema = new JSema(); + sema.noLibraries(noLibraries); + sema.ingestDocument(document); + sema.loadTypes(types); + sema.loadPackages(packages); + return JParseResult.success(translate(sema, document, javaVersion)); + } + + static JavaTree.CompilationUnitTreeImpl translate(JSema sema, Document document) { + return translate(sema, document, Integer.MAX_VALUE); + } + + static JavaTree.CompilationUnitTreeImpl translate(JSema sema, Document document, int javaVersion) { + boolean broken = document.getHasError(); + SemSitterTranslator translator = new SemSitterTranslator(sema); + translator.unnamedVariables = javaVersion >= 22; + translator.records = javaVersion >= 16; + translator.markdownComments = javaVersion >= 23; + if (!document.getPath().isEmpty()) { + String fileName = Path.of(document.getPath()).getFileName().toString(); + translator.implicitClassName = fileName.endsWith(".java") ? fileName.substring(0, fileName.length() - 5) : fileName; + } + Node root = new Node(document.getTree()); + if (broken) { + Node problem = firstProblem(root); + int line = problem == null ? 1 : problem.line(); + int column = problem == null ? 1 : problem.col() + 1; + throw new RecognitionException(line, String.format("Parse error at line %d column %d: Syntax error", line, column)); + } + translator.indexTokens(root); + translator.declareGenericReturns(root); + JavaTree.CompilationUnitTreeImpl unit = translator.compilationUnit(root); + translator.deferred.forEach(Runnable::run); + unit.setSemanticModel(sema, sema.undefinedTypes(), sema.getEnvironmentCleaner()); + setParents(unit); + CompilerWarnings.addTo(unit); + EffectivelyFinalVariables.mark(unit); + return unit; + } + + @Nullable + private static Node firstProblem(Node node) { + if ("ERROR".equals(node.k()) || node.missing()) { + return node; + } + for (org.sonarsource.semsitter.wire.Node child : node.proto.getChildrenList()) { + Node problem = firstProblem(new Node(child)); + if (problem != null) { + return problem; + } + } + return null; + } + + private void indexTokens(Node root) { + List leaves = new ArrayList<>(); + collectLeaves(root, leaves); + List pending = new ArrayList<>(); + for (Node leaf : leaves) { + if (isComment(leaf)) { + SyntaxTrivia previous = pending.isEmpty() ? null : pending.get(pending.size() - 1); + if (markdownComments && previous != null && previous.isComment(SyntaxTrivia.CommentKind.MARKDOWN) && leaf.text().startsWith("///") + && previous.range().end().line() + 1 == leaf.line()) { + pending.set(pending.size() - 1, new InternalSyntaxTrivia(SyntaxTrivia.CommentKind.MARKDOWN, + previous.comment() + "\n" + " ".repeat(leaf.col()) + trivia(leaf).comment(), previous.range().start().line(), previous.range().start().columnOffset())); + } else { + pending.add(trivia(leaf)); + } + } else { + tokens.put(leaf.proto, new InternalSyntaxToken(leaf.line(), leaf.col(), leaf.text(), pending, false)); + pending = new ArrayList<>(); + } + } + eof = new InternalSyntaxToken(root.proto.getEndLine(), root.proto.getEndCol(), "", pending, true); + } + + private static void collectLeaves(Node node, List leaves) { + if (node.missing()) { + return; + } + if (isComment(node) || node.allChildren().isEmpty() || isLiteral(node.k())) { + if (!node.text().isEmpty() || isComment(node)) { + leaves.add(node); + } + return; + } + for (Node child : node.allChildren()) { + collectLeaves(child, leaves); + } + } + + private JavaTree.CompilationUnitTreeImpl compilationUnit(Node program) { + JavaTree.PackageDeclarationTreeImpl packageDeclaration = null; + List imports = new ArrayList<>(); + List types = new ArrayList<>(); + List compactMembers = new ArrayList<>(); + ModuleDeclarationTree module = null; + boolean[] compact = {false}; + for (Node child : program.children()) { + TopLevel collected = addTopLevel(child, imports, types, compactMembers, compact[0]); + packageDeclaration = collected.packageDeclaration == null ? packageDeclaration : collected.packageDeclaration; + module = collected.module == null ? module : collected.module; + compact[0] = collected.compact; + } + if (compact[0]) { + ClassTreeImpl implicitClass = new ClassTreeImpl(Tree.Kind.IMPLICIT_CLASS, null, compactMembers, null); + bindImplicitClass(implicitClass, compactMembers); + types.add(implicitClass); + } + return new JavaTree.CompilationUnitTreeImpl(packageDeclaration, imports, types, module, eof); + } + + /** One top-level construct. Children of an error node are kept, so a syntax error does not drop the rest of the file. */ + private TopLevel addTopLevel(Node child, List imports, List types, List compactMembers, boolean compact) { + if ("ERROR".equals(child.k())) { + JavaTree.PackageDeclarationTreeImpl packageDeclaration = null; + ModuleDeclarationTree module = null; + for (Node nested : child.children()) { + TopLevel collected = addTopLevel(nested, imports, types, compactMembers, compact); + packageDeclaration = collected.packageDeclaration == null ? packageDeclaration : collected.packageDeclaration; + module = collected.module == null ? module : collected.module; + compact = collected.compact; + } + return new TopLevel(packageDeclaration, module, compact); + } + return switch (child.k()) { + case "package_declaration" -> new TopLevel(packageDeclaration(child), null, compact); + case "module_declaration" -> new TopLevel(null, moduleDeclaration(child), compact); + case "import_declaration" -> { + imports.add(importDeclaration(child)); + yield new TopLevel(null, null, compact); + } + case ";" -> { + EmptyStatementTreeImpl empty = new EmptyStatementTreeImpl(token(child)); + if (compact) { + compactMembers.add(empty); + } else if (types.isEmpty()) { + imports.add(empty); + } else { + types.add(empty); + } + yield new TopLevel(null, null, compact); + } + case "class_declaration", "interface_declaration", "enum_declaration", "record_declaration", "annotation_type_declaration" -> { + addMember(compact ? compactMembers : types, child); + yield new TopLevel(null, null, compact); + } + case "method_declaration", "constructor_declaration", "field_declaration", "constant_declaration", "local_variable_declaration", "static_initializer", "block" -> { + if (!compact) { + compact = true; + compactMembers.addAll(types); + types.clear(); + } + addMember(compactMembers, child); + yield new TopLevel(null, null, compact); + } + default -> new TopLevel(null, null, compact); + }; + } + + private record TopLevel(@Nullable JavaTree.PackageDeclarationTreeImpl packageDeclaration, @Nullable ModuleDeclarationTree module, boolean compact) { + } + + private ModuleDeclarationTreeImpl moduleDeclaration(Node node) { + Node body = requiredField(node, "body", childKind(node, "module_body")); + List directives = new ArrayList<>(); + for (Node child : body.children()) { + if (child.k().endsWith("_module_directive")) { + directives.add(moduleDirective(child)); + } + } + return new ModuleDeclarationTreeImpl( + node.children().stream().filter(SemSitterTranslator::isAnnotation).map(this::annotation).toList(), + optionalToken(node, "open"), + token(required(node, "module")), + moduleName(requiredField(node, "name", firstNamed(node))), + token(required(body, "{")), + directives, + token(required(body, "}"))); + } + + private ModuleDirectiveTree moduleDirective(Node node) { + InternalSyntaxToken keyword = token(node.children().get(0)); + InternalSyntaxToken semicolon = token(required(node, ";")); + return switch (node.k()) { + case "requires_module_directive" -> new RequiresDirectiveTreeImpl(keyword, requiresModifiers(node), moduleName(requiredField(node, "module", lastNamed(node))), semicolon); + case "exports_module_directive" -> new ExportsDirectiveTreeImpl(keyword, expression(requiredField(node, "package", firstNamed(node))), optionalToken(node, "to"), moduleNames(node), semicolon); + case "opens_module_directive" -> new OpensDirectiveTreeImpl(keyword, expression(requiredField(node, "package", firstNamed(node))), optionalToken(node, "to"), moduleNames(node), semicolon); + case "uses_module_directive" -> new UsesDirectiveTreeImpl(keyword, (TypeTree) expression(requiredField(node, "type", firstNamed(node))), semicolon); + default -> new ProvidesDirectiveTreeImpl(keyword, (TypeTree) expression(requiredField(node, "provided", firstNamed(node))), token(required(node, "with")), providers(node), semicolon); + }; + } + + private ModifiersTreeImpl requiresModifiers(Node node) { + List modifiers = new ArrayList<>(); + for (Node child : node.children()) { + if ("requires_modifier".equals(child.k())) { + Node keyword = child.children().get(0); + modifiers.add(new ModifierKeywordTreeImpl("static".equals(keyword.text()) ? Modifier.STATIC : Modifier.TRANSITIVE, token(keyword))); + } + } + return new ModifiersTreeImpl(modifiers); + } + + private ModuleNameListTreeImpl moduleNames(Node node) { + ModuleNameListTreeImpl names = ModuleNameListTreeImpl.emptyList(); + for (Node child : node.children()) { + if ("modules".equals(child.f())) { + names.add(moduleName(child)); + } else if (",".equals(child.text())) { + names.separators().add(token(child)); + } + } + return names; + } + + private QualifiedIdentifierListTreeImpl providers(Node node) { + QualifiedIdentifierListTreeImpl providers = QualifiedIdentifierListTreeImpl.emptyList(); + boolean afterWith = false; + for (Node child : node.children()) { + if ("with".equals(child.text())) { + afterWith = true; + } else if (",".equals(child.text())) { + providers.separators().add(token(child)); + } else if (afterWith && !";".equals(child.text())) { + providers.add((TypeTree) expression(child)); + } + } + return providers; + } + + private ModuleNameTreeImpl moduleName(Node node) { + ModuleNameTreeImpl name = ModuleNameTreeImpl.emptyList(); + addModuleName(name, node); + return name; + } + + private void addModuleName(ModuleNameTreeImpl name, Node node) { + if ("scoped_identifier".equals(node.k())) { + addModuleName(name, requiredField(node, "scope", firstNamed(node))); + name.add(new IdentifierTreeImpl(token(requiredField(node, "name", lastNamed(node))))); + } else { + name.add(new IdentifierTreeImpl(token(node))); + } + } + + private JavaTree.PackageDeclarationTreeImpl packageDeclaration(Node node) { + naming = true; + ExpressionTree name = expression(requiredField(node, "name", firstOf(node, "scoped_identifier", "identifier"))); + naming = false; + packageName = dottedName(name); + bindPackage(name, packageName); + return new JavaTree.PackageDeclarationTreeImpl(annotations(node), token(required(node, "package")), name, token(required(node, ";"))); + } + + private JavaTree.ImportTreeImpl importDeclaration(Node node) { + InternalSyntaxToken staticToken = optionalToken(node, "static"); + naming = true; + ExpressionTree name = expression(requiredField(node, "name", firstNamed(node))); + naming = false; + if (keyword(node, "*") != null || keyword(node, "asterisk") != null) { + Node star = keyword(node, "*"); + if (star == null) { + star = keyword(node, "asterisk"); + } + (staticToken == null ? onDemandImports : staticOnDemandImports).add(dottedName(name)); + name = new MemberSelectExpressionTreeImpl(name, token(lastKeyword(node, ".")), new IdentifierTreeImpl(token(star))); + } else if (name instanceof MemberSelectExpressionTree select) { + if (staticToken == null) { + singleImports.putIfAbsent(select.identifier().name(), dottedName(name)); + } else { + staticImports.putIfAbsent(select.identifier().name(), dottedName(select.expression())); + } + } + JavaTree.ImportTreeImpl imported = new JavaTree.ImportTreeImpl(token(required(node, "import")), staticToken, optionalToken(node, "module"), name, token(required(node, ";"))); + if (staticToken == null && name instanceof MemberSelectExpressionTree select && !"*".equals(select.identifier().name())) { + String fqn = dottedName(name); + if (sema.declaresType(fqn) && sema.resolve(fqn) instanceof Symbol.TypeSymbol type) { + imported.setSymbol(type); + } else if (!imported.isModule()) { + imported.setSymbol(Symbol.TypeSymbol.UNKNOWN_TYPE); + } + } + return imported; + } + + private void addMember(List members, Node node) { + switch (node.k()) { + case "field_declaration", "constant_declaration", "local_variable_declaration" -> members.addAll(variables(node)); + case "method_declaration", "constructor_declaration", "compact_constructor_declaration" -> members.add(method(node)); + case "annotation_type_element_declaration" -> members.add(annotationElement(node)); + case "class_declaration", "interface_declaration", "enum_declaration", "record_declaration", "annotation_type_declaration" -> members.add(typeDeclaration(node)); + case "static_initializer" -> members.add(staticInitializer(node)); + case "block" -> members.add(initializer(node)); + case "enum_constant" -> members.add(enumConstant(node, null)); + case ";" -> members.add(new EmptyStatementTreeImpl(token(node))); + case "{", "}" -> { + // punctuation of the body + } + case "ERROR" -> { + for (Node nested : node.children()) { + addMember(members, nested); + } + } + default -> { + // skipped construct + } + } + } + + private ClassTreeImpl typeDeclaration(Node node) { + Tree.Kind kind = switch (node.k()) { + case "interface_declaration" -> Tree.Kind.INTERFACE; + case "enum_declaration" -> Tree.Kind.ENUM; + case "record_declaration" -> records ? Tree.Kind.RECORD : Tree.Kind.CLASS; + case "annotation_type_declaration" -> Tree.Kind.ANNOTATION_TYPE; + default -> Tree.Kind.CLASS; + }; + Node body = field(node, "body"); + Node declaredName = nameNode(node); + if (declaredName != null && declaredName.decl() != null && sema.resolve(declaredName.decl()) instanceof Symbol.TypeSymbol typeSymbol) { + types.push(typeSymbol); + } else { + types.push(Symbol.TypeSymbol.UNKNOWN_TYPE); + } + // translated before the members so that the bounds of the type parameters are known inside the bodies + Node typeParameters = field(node, "type_parameters"); + TypeParameterListTreeImpl typeParameterList = typeParameters == null ? null : typeParameters(typeParameters); + List members; + try { + members = body == null ? new ArrayList<>() : membersOf(body); + } finally { + types.pop(); + } + InternalSyntaxToken open = body == null ? synthetic("{") : token(required(body, "{")); + InternalSyntaxToken close = body == null ? synthetic("}") : token(required(body, "}")); + ClassTreeImpl tree = new ClassTreeImpl(kind, open, members, close); + String keyword = switch (kind) { + case INTERFACE, ANNOTATION_TYPE -> "interface"; + case ENUM -> "enum"; + case RECORD -> "record"; + default -> "record_declaration".equals(node.k()) ? "record" : "class"; + }; + IdentifierTreeImpl name = identifier(requiredField(node, "name", firstOf(node, "identifier", "type_identifier"))); + InternalSyntaxToken keywordToken = token(required(node, keyword)); + InternalSyntaxToken atToken = null; + if (kind == Tree.Kind.ANNOTATION_TYPE && "@interface".equals(keywordToken.text())) { + // The grammar has one token for both; the tree keeps the at sign and the keyword apart. + atToken = new InternalSyntaxToken(keywordToken.line(), keywordToken.column(), "@", keywordToken.trivias(), false); + keywordToken = new InternalSyntaxToken(keywordToken.line(), keywordToken.column() + 1, "interface", List.of(), false); + } + tree.complete(modifiers(node), keywordToken, name); + if (typeParameterList != null) { + tree.completeTypeParameters(typeParameterList); + } + if (kind == Tree.Kind.ANNOTATION_TYPE) { + Node at = keyword(node, "@"); + if (atToken != null) { + tree.completeAtToken(atToken); + } else if (at != null) { + tree.completeAtToken(token(at)); + } + } + if (kind == Tree.Kind.RECORD) { + Node parameters = field(node, "parameters"); + // the components must not shadow same-named variables of the enclosing method after the record + scopes.addFirst(new HashMap<>()); + try { + tree.completeRecordComponents( + parameters == null ? synthetic("(") : token(required(parameters, "(")), + parameters == null ? List.of() : parameters(parameters), + parameters == null ? synthetic(")") : token(required(parameters, ")"))); + } finally { + scopes.removeFirst(); + } + } + Node superclass = childKind(node, "superclass"); + if (superclass != null) { + tree.completeSuperclass(token(required(superclass, "extends")), type(firstType(superclass))); + } + Node interfaces = childKind(node, "super_interfaces"); + if (interfaces == null) { + interfaces = childKind(node, "extends_interfaces"); + } + if (interfaces != null) { + tree.completeInterfaces(firstKeyword(interfaces), separatedTypes(interfaces)); + } + Node permits = childKind(node, "permits"); + if (permits != null) { + tree.completePermittedTypes(token(required(permits, "permits")), separatedTypes(permits)); + } + bindDeclaration(tree, nameNode(node), name); + if (kind == Tree.Kind.RECORD && tree.symbol() instanceof JTypeSymbol record) { + // the components of a record belong to the record, not to its canonical constructor + tree.recordComponents().stream().map(VariableTree::symbol).filter(JVariableSymbol.class::isInstance).map(JVariableSymbol.class::cast).forEach(component -> component.owner(record)); + } + if (tree.symbol() instanceof JTypeSymbol declared) { + if (tree.superClass() != null + && tree.superClass().symbolType().symbol() instanceof JTypeSymbol parent && parent.id != null && !parent.isUnknown() && !parent.equals(declared)) { + declared.superName(parent.id); + } else if (kind == Tree.Kind.RECORD) { + declared.superName("java.lang.Record"); + } else if (kind == Tree.Kind.ENUM) { + declared.superName("java.lang.Enum"); + } + declared.declaredSupertypes(tree.superClass() == null ? null : tree.superClass().symbolType(), + tree.superInterfaces().stream().map(TypeTree::symbolType).toList()); + } + return tree; + } + + private List membersOf(Node body) { + List members = new ArrayList<>(); + List children = body.children(); + for (int i = 0; i < children.size(); i++) { + Node child = children.get(i); + if ("enum_constant".equals(child.k())) { + members.add(enumConstant(child, enumSeparator(children, i))); + } else if ("enum_body_declarations".equals(child.k())) { + List declarations = child.children(); + int j = 0; + while (childKind(body, "enum_constant") != null && j < declarations.size() && ";".equals(declarations.get(j).text())) { + j++; + } + for (; j < declarations.size(); j++) { + addMember(members, declarations.get(j)); + } + } else if (i + 1 < children.size() && brokenCompactConstructor(child, children.get(i + 1))) { + members.add(recoveredRecordConstructor(child, children.get(i + 1))); + i++; + } else { + addMember(members, child); + } + } + return members; + } + + /** Tree-sitter splits {@code Record throws Ex} into a field named {@code throws} and a compact constructor named {@code Ex}. */ + private static boolean brokenCompactConstructor(Node field, Node next) { + if (!"field_declaration".equals(field.k()) || !"compact_constructor_declaration".equals(next.k())) { + return false; + } + for (Node child : field.children()) { + if ("variable_declarator".equals(child.k())) { + Node name = field(child, "name"); + return name != null && "throws".equals(name.text()); + } + } + return false; + } + + private MethodTreeImpl recoveredRecordConstructor(Node field, Node compact) { + Node typeNode = field(field, "type"); + IdentifierTreeImpl name = identifier(typeNode == null ? field : typeNode); + Node throwsName = null; + for (Node child : field.children()) { + if ("variable_declarator".equals(child.k())) { + throwsName = field(child, "name"); + } + } + Node thrownName = nameNode(compact); + QualifiedIdentifierListTreeImpl thrown = QualifiedIdentifierListTreeImpl.emptyList(); + if (thrownName != null && !"throws".equals(thrownName.text())) { + thrown.add(type(thrownName)); + } + Node body = field(compact, "body"); + BlockTreeImpl block = body == null ? null : block(body); + MethodTreeImpl tree = new MethodTreeImpl( + null, + name, + new FormalParametersListTreeImpl(null, null), + throwsName == null ? null : token(throwsName), + thrown, + block, + null) + .completeWithModifiers(modifiers(field)); + bindDeclaration(tree, nameNode(compact), name); + return tree; + } + + @Nullable + private static Node enumSeparator(List siblings, int index) { + if (index + 1 >= siblings.size()) { + return null; + } + Node next = siblings.get(index + 1); + if (",".equals(next.text())) { + return next; + } + if ("enum_body_declarations".equals(next.k())) { + List declarations = next.children(); + if (!declarations.isEmpty() && ";".equals(declarations.get(0).text())) { + return declarations.get(0); + } + } + return null; + } + + private EnumConstantTreeImpl enumConstant(Node node, @Nullable Node separatorNode) { + IdentifierTreeImpl name = identifier(requiredField(node, "name", firstOf(node, "identifier"))); + Node arguments = field(node, "arguments"); + ArgumentListTreeImpl args = arguments == null ? ArgumentListTreeImpl.emptyList() : arguments(arguments); + Node body = field(node, "body"); + ClassTreeImpl classBody = null; + if (body != null) { + classBody = new ClassTreeImpl(Tree.Kind.CLASS, token(required(body, "{")), membersOf(body), token(required(body, "}"))); + bindType(classBody, node.decl() != null ? node : body); + } + InternalSyntaxToken separator = separatorNode == null ? null : token(separatorNode); + EnumConstantTreeImpl tree = new EnumConstantTreeImpl(modifiers(node), name, new NewClassTreeImpl(name, args, classBody), separator); + bindDeclaration(tree, nameNode(node), name); + Symbol.TypeSymbol enumType = types.peek(); + if (classBody != null && enumType instanceof JSymbol enumSymbol) { + // An enum with a constant body is not final. + enumSymbol.removeModifier("final"); + } + boolean knownEnum = enumType != null && !enumType.isUnknown(); + bindEnumConstructor(name, args, knownEnum ? enumType : null); + if (knownEnum) { + ascribe(name, enumType.type()); + if (tree.symbol() instanceof JSymbol field && field.type().isUnknown()) { + field.type(enumType.type()); + } + } + return tree; + } + + /** The name of an enum constant is also its constructor call: it names the constructor of {@code enumType}, or nothing. */ + private void bindEnumConstructor(IdentifierTreeImpl name, ArgumentListTreeImpl args, @Nullable Symbol.TypeSymbol enumType) { + Symbol constructor = null; + if (enumType != null) { + String owner = enumType.type().fullyQualifiedName(); + Symbol.MethodSymbol declared = sema.declaredMethod(owner, "", argumentTypes(args)); + constructor = declared != null || !args.isEmpty() ? declared : sema.resolve(owner + "#()"); + } + bind(name, constructor instanceof Symbol.MethodSymbol ? constructor : null); + if (name.symbol() instanceof Symbol.MethodSymbol method && !method.isUnknown()) { + recordUse(method, name); + } + } + + private MethodTreeImpl annotationElement(Node node) { + FormalParametersListTreeImpl formals = new FormalParametersListTreeImpl(token(required(node, "(")), token(required(node, ")"))); + Node value = field(node, "value"); + IdentifierTreeImpl name = identifier(requiredField(node, "name", firstOf(node, "identifier"))); + MethodTreeImpl tree = new MethodTreeImpl(formals, value == null ? null : token(required(node, "default")), value == null ? null : expression(value)) + .complete(arrayType(type(requiredField(node, "type", firstType(node))), field(node, "dimensions")), name, token(required(node, ";"))) + .completeWithModifiers(modifiers(node)); + bindDeclaration(tree, nameNode(node), name); + return tree; + } + + private MethodTreeImpl method(Node node) { + scopes.addFirst(new HashMap<>()); + Node typeNode = field(node, "type"); + returnTargets.push(typeNode == null || field(node, "dimensions") != null ? Type.UNKNOWN : syntacticType(typeNode)); + try { + return methodInScope(node); + } finally { + scopes.removeFirst(); + returnTargets.pop(); + } + } + + private MethodTreeImpl methodInScope(Node node) { + // translated before the parameters and the body so that the bounds of the type parameters are known there + Node typeParameters = field(node, "type_parameters"); + TypeParameterListTreeImpl typeParameterList = typeParameters == null ? null : typeParameters(typeParameters); + Node parameters = field(node, "parameters"); + FormalParametersListTreeImpl formals = new FormalParametersListTreeImpl( + parameters == null ? null : token(required(parameters, "(")), + parameters == null ? null : token(required(parameters, ")"))); + if (parameters != null) { + VariableTree previous = null; + for (Node child : parameters.children()) { + if ("formal_parameter".equals(child.k()) || "spread_parameter".equals(child.k()) || "receiver_parameter".equals(child.k())) { + VariableTreeImpl parameter = variable(child, false); + formals.add(parameter); + previous = parameter; + } else if (",".equals(child.text()) && previous != null) { + ((VariableTreeImpl) previous).setEndToken(token(child)); + } + } + } + Node body = field(node, "body"); + BlockTreeImpl block = body == null ? null : block(body); + Node typeNode = field(node, "type"); + TypeTree returnType = null; + if (typeNode != null && !"constructor_declaration".equals(node.k())) { + TypeTree written = recoverQualifiedType(type(typeNode)); + List afterTypeParameters = node.children().stream().filter(SemSitterTranslator::isAnnotation).map(this::annotation).toList(); + TypeTree element = written; + while (element instanceof ArrayTypeTree array) { + element = array.type(); + } + if (!afterTypeParameters.isEmpty() && element instanceof JavaTree.AnnotatedTypeTree annotated) { + annotated.complete(afterTypeParameters); + } + returnType = arrayType(written, field(node, "dimensions")); + } + IdentifierTreeImpl name = identifier(requiredField(node, "name", firstOf(node, "identifier"))); + Node thrown = childKind(node, "throws"); + MethodTreeImpl tree = new MethodTreeImpl( + returnType, + name, + formals, + thrown == null ? null : token(required(thrown, "throws")), + thrown == null ? QualifiedIdentifierListTreeImpl.emptyList() : separatedTypes(thrown), + block, + body == null ? token(required(node, ";")) : null) + .completeWithModifiers(modifiers(node)); + if (typeParameterList != null) { + tree.completeWithTypeParameters(typeParameterList); + } + bindDeclaration(tree, nameNode(node), name); + return tree; + } + + private List parameters(Node parameters) { + List trees = new ArrayList<>(); + VariableTreeImpl previous = null; + for (Node child : parameters.children()) { + if ("formal_parameter".equals(child.k()) || "spread_parameter".equals(child.k())) { + previous = variable(child, false); + trees.add(previous); + } else if (",".equals(child.text()) && previous != null) { + previous.setEndToken(token(child)); + } + } + return trees; + } + + private List variables(Node declaration) { + ModifiersTreeImpl modifiers = modifiers(declaration); + Node typeNode = field(declaration, "type"); + TypeTree type; + if (typeNode != null) { + type = type(typeNode); + if ("field_declaration".equals(declaration.k()) || "constant_declaration".equals(declaration.k())) { + type = recoverQualifiedType(type); + } else if (!naming && type instanceof MemberSelectExpressionTreeImpl select && select.symbolType().isUnknown()) { + // an unresolved qualified name of a local or a parameter is not typed by what is written + ascribe(select, JType.unknown(sema)); + } + } else if ("spread_parameter".equals(declaration.k())) { + type = spreadType(declaration); + } else { + Node catchTypeNode = childKind(declaration, "catch_type"); + type = catchTypeNode == null ? new VarTypeTreeImpl(synthetic("var")) : catchType(catchTypeNode); + } + List trees = new ArrayList<>(); + VariableTreeImpl previous = null; + for (Node child : declaration.children()) { + if ("variable_declarator".equals(child.k()) || "formal_parameter".equals(child.k())) { + previous = declarator(child, modifiers, type); + trees.add(previous); + } else if ("ERROR".equals(child.k()) && previous != null && previous.initializer() == null && containsNew(child)) { + InternalSyntaxToken equals = null; + for (Node part : child.children()) { + if ("=".equals(part.text())) { + equals = token(part); + } + } + previous.completeTypeAndInitializer(previous.type(), equals == null ? synthetic("=") : equals, arrayFromError(child)); + } else if ((",".equals(child.text()) || ";".equals(child.text())) && previous != null) { + previous.setEndToken(token(child)); + } + } + if (trees.isEmpty() && field(declaration, "name") != null) { + trees.add(declarator(declaration, modifiers, type)); + } + return trees; + } + + private static boolean containsNew(Node node) { + for (Node child : node.children()) { + if ("new".equals(child.text()) || containsNew(child)) { + return true; + } + } + return false; + } + + /** {@code new byte[]} left inside an error node beside the declarator. */ + private NewArrayTreeImpl arrayFromError(Node error) { + InternalSyntaxToken newKeyword = synthetic("new"); + Node typeNode = null; + List dims = new ArrayList<>(); + for (Node child : error.children()) { + if ("new".equals(child.text())) { + newKeyword = token(child); + } else if (isTypeKind(child.k())) { + typeNode = child; + } else if ("dimensions".equals(child.k()) || "dimensions_expr".equals(child.k())) { + dims.addAll(dimensions(child)); + } + } + if (dims.isEmpty()) { + dims.addAll(dimensions(error)); + } + NewArrayTreeImpl tree = new NewArrayTreeImpl(dims, InitializerListTreeImpl.emptyList()) + .complete(type(typeNode == null ? error : typeNode)) + .completeWithNewKeyword(newKeyword); + ascribe(tree, arrayTypeOf(tree.type(), Math.max(dims.size(), 1))); + return tree; + } + + private TypeTree spreadType(Node node) { + TypeTree element = type(firstType(node)); + List annotations = node.children().stream().filter(SemSitterTranslator::isAnnotation).map(this::annotation).toList(); + JavaTree.ArrayTypeTreeImpl array = new JavaTree.ArrayTypeTreeImpl(element, annotations, token(required(node, "..."))); + ascribe(array, JType.array(sema, element.symbolType() instanceof JType elementType ? elementType : JType.unknown(sema))); + return array; + } + + private VariableTreeImpl variable(Node parameter, boolean sharedModifiers) { + return variables(parameter).get(0); + } + + private VariableTreeImpl declarator(Node node, ModifiersTreeImpl modifiers, TypeTree type) { + IdentifierTreeImpl name = identifier(requiredField(node, "name", firstOf(node, "identifier"))); + VariableTreeImpl tree = new VariableTreeImpl(name).completeModifiersAndType(modifiers, applyDimensions(type, node)); + Node value = field(node, "value"); + if (value != null) { + ExpressionTree initializer = expression(value); + ascribeTarget(initializer, tree.type().symbolType()); + tree.completeTypeAndInitializer(tree.type(), token(required(node, "=")), initializer); + } + bindDeclaration(tree, nameNode(node) == null ? node : nameNode(node), name); + Type declared = tree.type().symbolType(); + if (tree.type() instanceof VarTypeTreeImpl && tree.initializer() != null && tree.initializer().symbolType().isIntersectionType() && tree.symbol() instanceof JSymbol symbol) { + symbol.type(tree.initializer().symbolType()); + ascribe(tree.type(), tree.initializer().symbolType()); + } else if (keepsArguments(declared) && tree.symbol() instanceof JSymbol symbol) { + symbol.type(declared); + } else if (tree.symbol().type() != null && !tree.symbol().type().isUnknown()) { + ascribe(tree.type(), tree.symbol().type()); + } + return tree; + } + + private TypeTree applyDimensions(TypeTree type, Node node) { + Node dimensions = field(node, "dimensions"); + if (dimensions == null) { + return type; + } + return arrayType(type, dimensions); + } + + private BlockTreeImpl staticInitializer(Node node) { + Node body = field(node, "body"); + if (body == null) { + body = node; + } + BlockTreeImpl block = block(body); + ownInitializerVariables(block, true); + return new StaticInitializerTreeImpl(token(required(node, "static")), (InternalSyntaxToken) block.openBraceToken(), block.body(), (InternalSyntaxToken) block.closeBraceToken()); + } + + /** Variables declared in an initializer block belong to the block, not to the class. */ + private void ownInitializerVariables(BlockTreeImpl block, boolean isStatic) { + Symbol.TypeSymbol enclosing = types.peek(); + if (!(enclosing instanceof JTypeSymbol enclosingType)) { + return; + } + JInitializerBlockSymbol owner = isStatic ? sema.staticInitializerBlockSymbol(enclosingType) : sema.initializerBlockSymbol(enclosingType); + block.accept(new BaseTreeVisitor() { + @Override + public void visitVariable(VariableTree tree) { + if (tree.symbol() instanceof JVariableSymbol variable && enclosing.equals(variable.owner())) { + variable.owner(owner); + } + super.visitVariable(tree); + } + + @Override + public void visitClass(ClassTree tree) { + // members of local and anonymous classes keep their own owner + } + + @Override + public void visitLambdaExpression(LambdaExpressionTree tree) { + // lambda variables belong to the lambda + } + }); + } + + private BlockTreeImpl initializer(Node node) { + BlockTreeImpl block = block(node); + ownInitializerVariables(block, false); + return new BlockTreeImpl(Tree.Kind.INITIALIZER, (InternalSyntaxToken) block.openBraceToken(), block.body(), (InternalSyntaxToken) block.closeBraceToken()); + } + + private BlockTreeImpl block(Node node) { + scopes.addFirst(new HashMap<>()); + try { + return blockInScope(node); + } finally { + scopes.removeFirst(); + } + } + + private BlockTreeImpl blockInScope(Node node) { + if (!"block".equals(node.k())) { + Node nested = childKind(node, "block"); + if (nested != null) { + node = nested; + } + } + InternalSyntaxToken open = token(required(node, "{")); + InternalSyntaxToken close = token(required(node, "}")); + List statements = new ArrayList<>(); + for (Node child : node.children()) { + if ("{".equals(child.text()) || "}".equals(child.text())) { + continue; + } + addStatement(statements, child); + } + return new BlockTreeImpl(open, statements, close); + } + + private void addStatement(List statements, Node node) { + if ("ERROR".equals(node.k())) { + for (Node nested : node.children()) { + if (nested.children().isEmpty() && nested.text().equals(nested.k())) { + continue; + } + addStatement(statements, nested); + } + return; + } + if ("local_variable_declaration".equals(node.k())) { + statements.addAll(variables(node)); + return; + } + if (";".equals(node.text())) { + statements.add(new EmptyStatementTreeImpl(token(node))); + return; + } + Node switchNode = childKind(node, "switch_expression"); + if ("expression_statement".equals(node.k()) && switchNode != null) { + statements.add(switchStatement(switchNode)); + statements.add(new EmptyStatementTreeImpl(token(required(node, ";")))); + return; + } + statements.add(statement(node)); + } + + private StatementTree statement(Node node) { + return switch (node.k()) { + case "block" -> block(node); + case "expression_statement" -> expressionStatement(node); + case "explicit_constructor_invocation" -> constructorInvocation(node); + case "if_statement" -> ifStatement(node); + case "while_statement" -> whileStatement(node); + case "do_statement" -> doStatement(node); + case "for_statement" -> forStatement(node); + case "enhanced_for_statement" -> forEach(node); + case "break_statement" -> breakStatement(node); + case "continue_statement" -> continueStatement(node); + case "return_statement" -> returnStatement(node); + case "yield_statement" -> yieldStatement(node); + case "throw_statement" -> throwStatement(node); + case "assert_statement" -> assertStatement(node); + case "labeled_statement" -> labeled(node); + case "try_statement", "try_with_resources_statement" -> tryStatement(node); + case "synchronized_statement" -> synchronizedStatement(node); + case "switch_statement", "switch_expression" -> switchStatement(node); + case "local_variable_declaration" -> variables(node).get(0); + case "class_declaration", "interface_declaration", "enum_declaration", "record_declaration" -> typeDeclaration(node); + case "ERROR" -> recoveredStatement(node); + default -> new EmptyStatementTreeImpl(";".equals(node.text()) ? token(node) : token(required(node, ";"))); + }; + } + + private ExpressionStatementTreeImpl expressionStatement(Node node) { + ExpressionTree expression = null; + InternalSyntaxToken semicolon = null; + for (Node child : node.children()) { + if (";".equals(child.text())) { + semicolon = token(child); + } else if (expression == null) { + expression = expression(child); + } + } + return new ExpressionStatementTreeImpl(expression == null ? literal(Tree.Kind.NULL_LITERAL, synthetic("null"), sema.getClassType("")) : expression, semicolon); + } + + private ExpressionStatementTreeImpl constructorInvocation(Node node) { + Node constructor = requiredField(node, "constructor", firstOf(node, "super", "this")); + IdentifierTreeImpl identifier = identifier(constructor); + bindUse(identifier, constructor); + Node object = field(node, "object"); + ExpressionTree select = object == null + ? identifier + : new MemberSelectExpressionTreeImpl(expression(object), token(required(node, ".")), identifier); + Node typeArguments = field(node, "type_arguments"); + MethodInvocationTreeImpl invocation = new MethodInvocationTreeImpl(select, typeArguments == null ? null : typeArguments(typeArguments), + arguments(requiredField(node, "arguments", childKind(node, "argument_list")))); + if (identifier.symbol() instanceof Symbol.MethodSymbol method) { + bindMethod(invocation, method); + ascribe(invocation, method.owner().type()); + ascribe(identifier, Type.UNKNOWN); + } + Symbol.TypeSymbol enclosing = types.peek(); + if (invocation.symbolType().isUnknown() && enclosing != null) { + Type constructed = "this".equals(identifier.name()) ? enclosing.type() : enclosing.superClass(); + ascribe(invocation, constructed == null ? Type.UNKNOWN : constructed); + } + return new ExpressionStatementTreeImpl(invocation, token(required(node, ";"))); + } + + private IfStatementTreeImpl ifStatement(Node node) { + Parens condition = parens(requiredField(node, "condition", childKind(node, "parenthesized_expression"))); + Node consequence = field(node, "consequence"); + Node alternative = field(node, "alternative"); + return new IfStatementTreeImpl( + token(required(node, "if")), + condition.open, + condition.expr, + condition.close, + consequence == null ? new EmptyStatementTreeImpl(synthetic(";")) : statement(consequence), + alternative == null ? null : token(required(node, "else")), + alternative == null ? null : statement(alternative)); + } + + private WhileStatementTreeImpl whileStatement(Node node) { + Parens condition = parens(requiredField(node, "condition", childKind(node, "parenthesized_expression"))); + return new WhileStatementTreeImpl(token(required(node, "while")), condition.open, condition.expr, condition.close, statement(requiredField(node, "body", lastNamed(node)))); + } + + private DoWhileStatementTreeImpl doStatement(Node node) { + Node body = field(node, "body"); + Parens condition = parens(requiredField(node, "condition", childKind(node, "parenthesized_expression"))); + return new DoWhileStatementTreeImpl( + token(required(node, "do")), + body == null ? new EmptyStatementTreeImpl(synthetic(";")) : statement(body), + token(required(node, "while")), + condition.open, + condition.expr, + condition.close, + token(lastKeyword(node, ";"))); + } + + private ForStatementTreeImpl forStatement(Node node) { + scopes.addFirst(new HashMap<>()); + try { + return forStatementInScope(node); + } finally { + scopes.removeFirst(); + } + } + + private ForStatementTreeImpl forStatementInScope(Node node) { + StatementListTreeImpl init = StatementListTreeImpl.emptyList(); + StatementListTreeImpl update = StatementListTreeImpl.emptyList(); + InternalSyntaxToken firstSemicolon = null; + InternalSyntaxToken secondSemicolon = null; + ExpressionTree condition = null; + int semicolons = 0; + for (Node child : node.children()) { + if (")".equals(child.text())) { + break; + } + if ("for".equals(child.text()) || "(".equals(child.text())) { + continue; + } + if (";".equals(child.text())) { + semicolons++; + if (semicolons == 1) { + firstSemicolon = token(child); + } else { + secondSemicolon = token(child); + } + continue; + } + if (",".equals(child.text())) { + (semicolons == 0 ? init : update).separators().add(token(child)); + continue; + } + if ("local_variable_declaration".equals(child.k()) && semicolons == 0) { + List declared = variables(child); + init.addAll(declared); + InternalSyntaxToken semi = optionalToken(child, ";"); + if (semi != null) { + if (!declared.isEmpty()) { + declared.get(declared.size() - 1).setEndToken(null); + } + firstSemicolon = semi; + semicolons = 1; + } + } else if (semicolons == 0) { + init.add(new ExpressionStatementTreeImpl(expression(child), null)); + } else if (semicolons == 1 && condition == null && !"block".equals(child.k()) && !same(field(node, "body"), child)) { + condition = expression(child); + } else if (semicolons >= 1 && same(child, field(node, "body"))) { + break; + } else if (semicolons >= 2 || same(field(node, "update"), child)) { + update.add(new ExpressionStatementTreeImpl(expression(child), null)); + } + } + Node body = field(node, "body"); + return new ForStatementTreeImpl( + token(required(node, "for")), + token(required(node, "(")), + init, + firstSemicolon == null ? synthetic(";") : firstSemicolon, + condition, + secondSemicolon == null ? synthetic(";") : secondSemicolon, + update, + token(required(node, ")")), + body == null ? new EmptyStatementTreeImpl(synthetic(";")) : statement(body)); + } + + private ForEachStatementImpl forEach(Node node) { + scopes.addFirst(new HashMap<>()); + try { + return forEachInScope(node); + } finally { + scopes.removeFirst(); + } + } + + private ForEachStatementImpl forEachInScope(Node node) { + TypeTree type = arrayType(type(requiredField(node, "type", firstType(node))), field(node, "dimensions")); + IdentifierTreeImpl name = identifier(requiredField(node, "name", firstOf(node, "identifier"))); + VariableTreeImpl variable = new VariableTreeImpl(modifiers(node), type, name); + bindDeclaration(variable, requiredField(node, "name", nameNode(node)), name); + return new ForEachStatementImpl( + token(required(node, "for")), + token(required(node, "(")), + variable, + token(required(node, ":")), + expression(requiredField(node, "value", firstNamed(node))), + token(required(node, ")")), + statement(requiredField(node, "body", lastNamed(node)))); + } + + private BreakStatementTreeImpl breakStatement(Node node) { + IdentifierTreeImpl label = labelUse(node); + return new BreakStatementTreeImpl(token(required(node, "break")), label, token(required(node, ";"))); + } + + private ContinueStatementTreeImpl continueStatement(Node node) { + return new ContinueStatementTreeImpl(token(required(node, "continue")), labelUse(node), token(required(node, ";"))); + } + + private ReturnStatementTreeImpl returnStatement(Node node) { + ExpressionTree expression = null; + for (Node child : node.children()) { + if (!"return".equals(child.text()) && !";".equals(child.text())) { + expression = expression(child); + } + } + if (expression instanceof NewClassTreeImpl newClass && !returnTargets.isEmpty()) { + inferDiamond(newClass, returnTargets.peek()); + } + if (expression != null && expression.is(Tree.Kind.LAMBDA_EXPRESSION, Tree.Kind.METHOD_REFERENCE, Tree.Kind.METHOD_INVOCATION) && !returnTargets.isEmpty() && !returnTargets.peek().isUnknown()) { + ascribeTarget(expression, returnTargets.peek()); + } + return new ReturnStatementTreeImpl(token(required(node, "return")), expression, token(required(node, ";"))); + } + + private YieldStatementTreeImpl yieldStatement(Node node) { + ExpressionTree expression = null; + for (Node child : node.children()) { + if (!"yield".equals(child.text()) && !";".equals(child.text())) { + expression = expression(child); + } + } + Node keyword = keyword(node, "yield"); + return new YieldStatementTreeImpl(keyword == null ? null : token(keyword), expression, token(required(node, ";"))); + } + + private ThrowStatementTreeImpl throwStatement(Node node) { + return new ThrowStatementTreeImpl(token(required(node, "throw")), expression(firstNamed(node)), token(required(node, ";"))); + } + + private AssertStatementTreeImpl assertStatement(Node node) { + List expressions = new ArrayList<>(); + InternalSyntaxToken colon = null; + for (Node child : node.children()) { + if (":".equals(child.text())) { + colon = token(child); + } else if (!"assert".equals(child.text()) && !";".equals(child.text())) { + expressions.add(expression(child)); + } + } + AssertStatementTreeImpl tree = new AssertStatementTreeImpl(token(required(node, "assert")), expressions.get(0), token(required(node, ";"))); + if (expressions.size() > 1) { + tree.complete(colon == null ? synthetic(":") : colon, expressions.get(1)); + } + return tree; + } + + private LabeledStatementTreeImpl labeled(Node node) { + IdentifierTreeImpl name = identifier(firstOf(node, "identifier")); + JLabelSymbol symbol = new JLabelSymbol(name.name()); + labels.push(symbol); + List children = node.children(); + LabeledStatementTreeImpl tree = new LabeledStatementTreeImpl(name, token(required(node, ":")), statement(children.get(children.size() - 1))); + labels.pop(); + symbol.setDeclaration(tree); + tree.labelSymbol = symbol; + name.labelSymbol = symbol; + String id = nameNode(node) == null ? null : firstOf(node, "identifier").decl(); + if (id != null) { + sema.declare(id, tree); + } + return tree; + } + + private TryStatementTreeImpl tryStatement(Node node) { + ResourceListTreeImpl resources = ResourceListTreeImpl.emptyList(); + Node resourceNode = field(node, "resources"); + if (resourceNode != null) { + for (Node child : resourceNode.children()) { + if ("resource".equals(child.k()) && field(child, "name") == null) { + resources.add(expression(firstNamed(child))); + } else if ("resource".equals(child.k()) || "local_variable_declaration".equals(child.k())) { + for (VariableTreeImpl resource : variables(child)) { + // A resource variable is implicitly final. + if (resource.symbol() instanceof JSymbol symbol) { + symbol.addModifiers(FINAL_MODIFIER); + } + resources.add(resource); + } + } else if (";".equals(child.text())) { + resources.separators().add(token(child)); + } else if (!"(".equals(child.text()) && !")".equals(child.text())) { + resources.add(expression(child)); + } + } + } + List catches = new ArrayList<>(); + for (Node child : node.children()) { + if ("catch_clause".equals(child.k())) { + scopes.addFirst(new HashMap<>()); + try { + Node parameter = field(child, "parameter"); + if (parameter == null) { + parameter = childKind(child, "formal_parameter") == null ? childKind(child, "catch_formal_parameter") : childKind(child, "formal_parameter"); + } + VariableTreeImpl variable = parameter == null ? variables(child).get(0) : variable(parameter, false); + catches.add(new CatchTreeImpl(token(required(child, "catch")), token(required(child, "(")), variable, token(required(child, ")")), block(requiredField(child, "body", childKind(child, "block"))))); + } finally { + scopes.removeFirst(); + } + } + } + Node body = field(node, "body"); + Node finallyBlock = childKind(node, "finally_clause"); + if (finallyBlock == null) { + finallyBlock = field(node, "finally"); + } + return new TryStatementTreeImpl( + token(required(node, "try")), + resources.isEmpty() ? null : token(required(resourceNode, "(")), + resources, + resources.isEmpty() ? null : token(required(resourceNode, ")")), + body == null ? block(node) : block(body), + catches, + finallyBlock == null ? null : token(required(finallyBlock, "finally")), + finallyBlock == null ? null : block(childKind(finallyBlock, "block") == null ? finallyBlock : childKind(finallyBlock, "block"))); + } + + private SynchronizedStatementTreeImpl synchronizedStatement(Node node) { + Parens parens = parens(requiredField(node, "condition", childKind(node, "parenthesized_expression"))); + return new SynchronizedStatementTreeImpl(token(required(node, "synchronized")), parens.open, parens.expr, parens.close, block(requiredField(node, "body", childKind(node, "block")))); + } + + private SwitchStatementTreeImpl switchStatement(Node node) { + Parens parens = parens(requiredField(node, "condition", childKind(node, "parenthesized_expression"))); + Node body = field(node, "body"); + return new SwitchStatementTreeImpl( + token(required(node, "switch")), + parens.open, + parens.expr, + parens.close, + body == null ? synthetic("{") : token(required(body, "{")), + body == null ? List.of() : switchGroups(body, false), + body == null ? synthetic("}") : token(required(body, "}"))); + } + + private SwitchExpressionTreeImpl switchExpression(Node node) { + boolean previous = switchExpression; + switchExpression = true; + Parens parens = parens(requiredField(node, "condition", childKind(node, "parenthesized_expression"))); + Node body = field(node, "body"); + SwitchExpressionTreeImpl tree = new SwitchExpressionTreeImpl( + token(required(node, "switch")), + parens.open, + parens.expr, + parens.close, + body == null ? synthetic("{") : token(required(body, "{")), + body == null ? List.of() : switchGroups(body, true), + body == null ? synthetic("}") : token(required(body, "}"))); + switchExpression = previous; + ascribe(tree, switchResultType(tree)); + return tree; + } + + private static Type switchResultType(SwitchExpressionTreeImpl tree) { + List results = new ArrayList<>(); + for (CaseGroupTree group : tree.cases()) { + List body = group.body(); + if (group.labels().stream().noneMatch(CaseLabelTree::isFallThrough) && body.size() == 1 && body.get(0) instanceof ExpressionStatementTree statement) { + results.add(statement.expression().symbolType()); + } + body.forEach(statement -> statement.accept(new BaseTreeVisitor() { + @Override + public void visitYieldStatement(YieldStatementTree yield) { + results.add(yield.expression().symbolType()); + } + + @Override + public void visitSwitchExpression(SwitchExpressionTree nested) { + // nested switch expressions yield their own results + } + + @Override + public void visitLambdaExpression(LambdaExpressionTree lambda) { + // lambdas cannot yield to the enclosing switch + } + + @Override + public void visitClass(ClassTree type) { + // classes cannot yield to the enclosing switch + } + })); + } + if (results.isEmpty() || results.stream().anyMatch(Type::isUnknown) || results.stream().distinct().count() != 1) { + return Type.UNKNOWN; + } + return results.get(0); + } + + private List switchGroups(Node body, boolean expression) { + List groups = new ArrayList<>(); + List labels = new ArrayList<>(); + List carried = new ArrayList<>(); + StatementListTreeImpl statements = StatementListTreeImpl.emptyList(); + List children = body.children(); + for (int i = 0; i < children.size(); i++) { + Node child = children.get(i); + if ("{".equals(child.text()) || "}".equals(child.text())) { + continue; + } + if ("switch_label".equals(child.k()) || "switch_rule".equals(child.k()) || "switch_block_statement_group".equals(child.k())) { + if ("switch_label".equals(child.k())) { + if (!statements.isEmpty()) { + groups.add(new CaseGroupTreeImpl(labels, statements)); + labels = new ArrayList<>(); + statements = StatementListTreeImpl.emptyList(); + } + Node next = i + 1 < children.size() ? children.get(i + 1) : null; + boolean separator = next != null && ":".equals(next.text()); + labels.add(caseLabel(child, separator ? token(next) : null)); + if (separator) { + i++; + } + } else { + CaseGroupTreeImpl group = switchArm(child, expression, carried); + if (group.body().isEmpty() && "switch_block_statement_group".equals(child.k()) && nextIsGroup(children, i)) { + carried = group.labels().stream().map(CaseLabelTreeImpl.class::cast).collect(Collectors.toCollection(ArrayList::new)); + } else { + groups.add(group); + carried = new ArrayList<>(); + } + } + } else if (!labels.isEmpty()) { + addStatement(statements, child); + } + } + if (!labels.isEmpty()) { + groups.add(new CaseGroupTreeImpl(labels, statements)); + } + return groups; + } + + private static boolean nextIsGroup(List siblings, int index) { + return index + 1 < siblings.size() && "switch_block_statement_group".equals(siblings.get(index + 1).k()); + } + + private CaseGroupTreeImpl switchArm(Node node, boolean expression, List carried) { + List labels = new ArrayList<>(carried); + StatementListTreeImpl body = StatementListTreeImpl.emptyList(); + List children = node.children(); + for (int i = 0; i < children.size(); i++) { + Node child = children.get(i); + if ("switch_label".equals(child.k())) { + Node next = i + 1 < children.size() ? children.get(i + 1) : null; + boolean separator = next != null && (":".equals(next.text()) || "->".equals(next.text())); + labels.add(caseLabel(child, separator ? token(next) : null)); + if (separator) { + i++; + } + continue; + } + if ("->".equals(child.text()) || ":".equals(child.text())) { + continue; + } + if ("expression_statement".equals(child.k()) && "switch_rule".equals(node.k())) { + ExpressionStatementTreeImpl statement = expressionStatement(child); + body.add(new YieldStatementTreeImpl(null, statement.expression(), (InternalSyntaxToken) statement.semicolonToken())); + } else if (expression && !isStatementKind(child.k())) { + ExpressionTree value = expression(child); + body.add(new YieldStatementTreeImpl(null, value, optionalToken(node, ";"))); + } else { + addStatement(body, child); + } + } + return new CaseGroupTreeImpl(labels, body); + } + + private CaseLabelTreeImpl caseLabel(Node node, @Nullable InternalSyntaxToken separator) { + InternalSyntaxToken keyword = keyword(node, "case") != null ? token(keyword(node, "case")) : token(required(node, "default")); + List expressions = new ArrayList<>(); + InternalSyntaxToken end = separator; + boolean caseLabel = keyword(node, "case") != null; + for (Node child : node.children()) { + if ("case".equals(child.text())) { + continue; + } + if ("default".equals(child.text())) { + if (caseLabel) { + expressions.add(new DefaultPatternTreeImpl(token(child), Type.UNKNOWN)); + } + } else if (":".equals(child.text()) || "->".equals(child.text())) { + end = token(child); + } else if (",".equals(child.text())) { + continue; + } else if ("pattern".equals(child.k()) || "record_pattern".equals(child.k()) || "type_pattern".equals(child.k())) { + expressions.add(pattern(child)); + } else if ("guard".equals(child.k()) && !expressions.isEmpty() && expressions.get(expressions.size() - 1) instanceof PatternTree guarded) { + GuardedPatternTreeImpl pattern = new GuardedPatternTreeImpl(guarded, token(required(child, "when")), expression(firstNamed(child)), guarded.symbolType()); + expressions.set(expressions.size() - 1, pattern); + } else if ("null_literal".equals(child.k())) { + expressions.add(new NullPatternTreeImpl((LiteralTreeImpl) expression(child))); + } else { + expressions.add(expression(child)); + } + } + return new CaseLabelTreeImpl(keyword, expressions, end == null ? synthetic(":") : end); + } + + private ExpressionTree expression(Node node) { + if (node == null) { + return literal(Tree.Kind.NULL_LITERAL, synthetic("null"), JType.nullType(sema)); + } + ExpressionTree tree = switch (node.k()) { + case "identifier", "type_identifier", "this", "super", "true", "false", "null_literal" -> primary(node); + case "decimal_integer_literal", "hex_integer_literal", "octal_integer_literal", "binary_integer_literal" -> integerLiteral(node); + case "decimal_floating_point_literal", "hex_floating_point_literal" -> floatingLiteral(node); + case "string_literal", "string_fragment" -> literal(node.text().startsWith("\"\"\"") ? Tree.Kind.TEXT_BLOCK : Tree.Kind.STRING_LITERAL, token(node), sema.getClassType("java.lang.String")); + case "character_literal" -> literal(Tree.Kind.CHAR_LITERAL, token(node), sema.getClassType("char")); + case "text_block" -> literal(Tree.Kind.TEXT_BLOCK, token(node), sema.getClassType("java.lang.String")); + case "scoped_identifier", "scoped_type_identifier", "field_access" -> memberSelect(node); + case "method_invocation" -> invocation(node); + case "object_creation_expression" -> creation(node); + case "array_creation_expression" -> arrayCreation(node); + case "array_initializer", "element_value_array_initializer" -> arrayInitializer(node); + case "element_value_pair" -> elementValuePair(node); + case "class_literal" -> classLiteral(node); + case "annotation", "marker_annotation" -> annotation(node); + case "array_access" -> arrayAccess(node); + case "assignment_expression" -> assignment(node); + case "binary_expression" -> binary(node); + case "unary_expression" -> unary(node, true); + case "update_expression" -> update(node); + case "parenthesized_expression" -> parenthesized(node); + case "ternary_expression" -> ternary(node); + case "cast_expression" -> cast(node); + case "instanceof_expression" -> instanceOf(node); + case "lambda_expression" -> lambda(node); + case "method_reference" -> methodReference(node); + case "switch_expression" -> switchExpression(node); + case "generic_type", "array_type", "integral_type", "floating_point_type", "boolean_type", "void_type", "wildcard", "annotated_type" -> typeExpression(node); + case "ERROR" -> recoveredExpression(node); + default -> primary(node); + }; + return tree; + } + + /** The first recognizable expression inside a syntax error, so the surrounding code keeps a tree. */ + private ExpressionTree recoveredExpression(Node node) { + for (Node child : node.children()) { + String kind = child.k(); + if ("ERROR".equals(kind) || kind.endsWith("_expression") || kind.endsWith("_literal") || kind.endsWith("_identifier") + || "identifier".equals(kind) || "array_creation_expression".equals(kind) || "object_creation_expression".equals(kind) + || "method_invocation".equals(kind) || "field_access".equals(kind) || "array_access".equals(kind) + || "lambda_expression".equals(kind) || "method_reference".equals(kind) || "class_literal".equals(kind) + || "array_initializer".equals(kind) || "this".equals(kind) || "super".equals(kind)) { + return expression(child); + } + } + return literal(Tree.Kind.NULL_LITERAL, synthetic("null"), JType.nullType(sema)); + } + + /** The first recognizable statement inside a syntax error. */ + private StatementTree recoveredStatement(Node node) { + for (Node child : node.children()) { + String kind = child.k(); + if ("ERROR".equals(kind) || kind.endsWith("_statement") || "block".equals(kind) || kind.endsWith("_declaration")) { + return statement(child); + } + } + return new EmptyStatementTreeImpl(synthetic(";")); + } + + private ExpressionTree primary(Node node) { + if ("this".equals(node.k()) || "this".equals(node.text())) { + KeywordThis keyword = new KeywordThis(token(node), Symbol.UNKNOWN_SYMBOL); + Symbol.TypeSymbol enclosing = types.peek(); + if (enclosing != null) { + bind(keyword, sema.receiverSymbol(enclosing, "this", enclosing.type())); + ascribe(keyword, enclosing.type()); + } + return keyword; + } + if ("super".equals(node.k()) || "super".equals(node.text())) { + KeywordSuper keyword = new KeywordSuper(token(node), Symbol.UNKNOWN_SYMBOL); + Symbol.TypeSymbol enclosing = types.peek(); + if (enclosing != null) { + Type superType = enclosing.superClass() == null ? Type.UNKNOWN : enclosing.superClass(); + bind(keyword, sema.receiverSymbol(enclosing, "super", superType)); + ascribe(keyword, superType); + } + return keyword; + } + if ("true".equals(node.k()) || "false".equals(node.k()) || "true".equals(node.text()) || "false".equals(node.text())) { + return literal(Tree.Kind.BOOLEAN_LITERAL, token(node), sema.getClassType("boolean")); + } + if ("null_literal".equals(node.k()) || "null".equals(node.text())) { + return literal(Tree.Kind.NULL_LITERAL, token(node), JType.nullType(sema)); + } + IdentifierTreeImpl identifier = identifier(node); + bindUse(identifier, node); + if (!naming && identifier.symbol().isUnknown() && node.unresolved()) { + String type = importedType(identifier.name()); + if (type != null) { + bindType(identifier, type); + } + } + if (!naming && identifier.symbol().isUnknown() && node.unresolved() && !"type_identifier".equals(node.k())) { + importedField(identifier); + } + if (!naming && "type_identifier".equals(node.k())) { + preferSingleImport(identifier); + recoverType(identifier); + } + return identifier; + } + + /** An unresolved qualified type name keeps its written name where the compiler's recovery does. */ + private TypeTree recoverQualifiedType(TypeTree type) { + if (!naming && type instanceof MemberSelectExpressionTreeImpl select && select.symbolType().isUnknown() + && select.identifier() instanceof IdentifierTreeImpl identifier && identifier.symbol().isUnknown()) { + String name = dottedName(select); + if (!name.isEmpty()) { + JTypeSymbol recovered = sema.recoveredType(name); + bind(identifier, recovered); + ascribe(identifier, recovered.type()); + ascribe(select, recovered.type()); + } + } + return type; + } + + /** The type of an annotation: an unresolved one keeps its written, possibly qualified, name. */ + private Type annotationType(TypeTree type) { + String name = type instanceof ExpressionTree expression ? dottedName(expression) : ""; + if (type.symbolType().isUnknown() && !naming && !name.isEmpty()) { + return sema.recoveredType(name).type(); + } + return type.symbolType(); + } + + /** An unresolved type name keeps its written name, as a recovered binding does, so checks can match on the simple name. */ + private void recoverType(IdentifierTreeImpl identifier) { + if (identifier.symbol().isUnknown()) { + JTypeSymbol recovered = sema.recoveredType(identifier.name()); + bind(identifier, recovered); + ascribe(identifier, recovered.type()); + } + } + + /** A duplicate single-type import is an error; recovery keeps the first, which is the type this simple name denotes. */ + private void preferSingleImport(IdentifierTreeImpl identifier) { + String imported = singleImports.get(identifier.name()); + if (imported == null || !sema.declaresType(imported)) { + return; + } + Symbol symbol = identifier.symbol(); + boolean constructor = symbol.isMethodSymbol() && "".equals(symbol.name()); + if (!symbol.isTypeSymbol() && !symbol.isUnknown() && !constructor) { + return; + } + String resolved = identifier.symbolType().erasure().fullyQualifiedName(); + if (!imported.equals(resolved)) { + bindType(identifier, imported); + } + } + + /** The type a simple name stands for when SemSitter left it unresolved: imported, in the package, or in java.lang. */ + @Nullable + private String importedType(String name) { + List candidates = new ArrayList<>(); + if (singleImports.containsKey(name)) { + candidates.add(singleImports.get(name)); + } + candidates.add(packageName.isEmpty() ? name : (packageName + "." + name)); + onDemandImports.forEach(prefix -> candidates.add(prefix + "." + name)); + candidates.add("java.lang." + name); + String found = candidates.stream().filter(sema::declaresType).findFirst().orElse(null); + return found != null ? found : staticMemberType(name); + } + + /** A member type that a static import, single or on demand, brings in. */ + @Nullable + private String staticMemberType(String name) { + List owners = new ArrayList<>(); + if (staticImports.containsKey(name)) { + owners.add(staticImports.get(name)); + } + owners.addAll(staticOnDemandImports); + for (String owner : owners) { + String binary = binaryTypeName(owner); + if (binary != null && sema.declaresType(binary + "$" + name)) { + return binary + "$" + name; + } + } + return null; + } + + /** The binary name of the type a dotted name denotes, trying each dot as a nesting boundary. */ + @Nullable + private String binaryTypeName(String dotted) { + String candidate = dotted; + while (true) { + if (sema.declaresType(candidate)) { + return candidate; + } + int dot = candidate.lastIndexOf('.'); + if (dot < 0) { + return null; + } + candidate = candidate.substring(0, dot) + "$" + candidate.substring(dot + 1); + } + } + + private void resolveQualifiedType(ExpressionTree qualifier, IdentifierTreeImpl identifier) { + Symbol owner = qualifier instanceof MemberSelectExpressionTree select ? select.identifier().symbol() : (qualifier instanceof IdentifierTree name ? name.symbol() : Symbol.UNKNOWN_SYMBOL); + String candidate; + if (owner.isTypeSymbol() && !owner.isUnknown()) { + candidate = ((Symbol.TypeSymbol) owner).type().fullyQualifiedName() + "$" + identifier.name(); + } else if (owner.isUnknown() || owner.isPackageSymbol()) { + String prefix = dottedName(qualifier); + candidate = prefix.isEmpty() ? null : (prefix + "." + identifier.name()); + } else { + candidate = null; + } + if (candidate != null && sema.declaresType(candidate)) { + bindType(identifier, candidate); + } + } + + @Nullable + private String fieldOwner(ExpressionTree qualifier) { + Type receiver = qualifier.symbolType().erasure(); + if (receiver.isClass()) { + return receiver.fullyQualifiedName(); + } + return qualifier instanceof IdentifierTree name ? importedType(name.name()) : null; + } + + /** A name SemSitter left unresolved that a static import brings in as a field. */ + private void importedField(IdentifierTreeImpl identifier) { + List owners = new ArrayList<>(); + if (staticImports.containsKey(identifier.name())) { + owners.add(staticImports.get(identifier.name())); + } + owners.addAll(staticOnDemandImports); + for (String owner : owners) { + Symbol.VariableSymbol field = sema.declaredField(owner, identifier.name()); + if (field != null && field.isStatic()) { + bind(identifier, field); + ascribe(identifier, field.type()); + return; + } + } + } + + /** The method SemSitter left unresolved, looked up in the receiver type, or in the enclosing types and static imports of an unqualified call. */ + @Nullable + private Symbol.MethodSymbol libraryMethod(@Nullable ExpressionTree qualifier, String name, List arguments, Set functions) { + List owners = new ArrayList<>(); + if (qualifier != null) { + Type receiver = qualifier.symbolType().erasure(); + if (receiver.isClass()) { + owners.add(receiver.fullyQualifiedName()); + } else if (receiver.isArray()) { + owners.add("java.lang.Object"); + } else if (qualifier instanceof IdentifierTree typeName) { + String imported = importedType(typeName.name()); + if (imported != null) { + owners.add(imported); + } + } + } else { + types.stream().filter(type -> !type.isUnknown()).forEach(type -> owners.add(type.type().fullyQualifiedName())); + if (staticImports.containsKey(name)) { + owners.add(staticImports.get(name)); + } + owners.addAll(staticOnDemandImports); + } + Symbol.MethodSymbol found = owners.stream().map(owner -> sema.declaredMethod(owner, name, arguments, functions)).filter(Objects::nonNull).findFirst().orElse(null); + if (found == null && qualifier != null && !qualifier.symbolType().isUnknown() && !owners.contains("java.lang.Object")) { + found = sema.declaredMethod("java.lang.Object", name, arguments, functions); + } + return found; + } + + /** Types a lambda, a method reference or an array initializer from the type its context expects. */ + private void ascribeTarget(ExpressionTree expression, Type target) { + boolean targetTyped = expression.is(Tree.Kind.LAMBDA_EXPRESSION, Tree.Kind.METHOD_REFERENCE) || (expression instanceof NewArrayTreeImpl array && array.type() == null); + // an erased type variable (Object) is not a functional interface: wait for the inferred parameter + if (targetTyped && expression.symbolType().isUnknown() && !target.isUnknown() && !target.is("java.lang.Object")) { + ascribe(expression, expression instanceof NewArrayTreeImpl ? target : sema.groundType(target)); + } + if (expression instanceof NewClassTreeImpl newClass) { + inferDiamond(newClass, target); + } + // a switch expression is a poly expression: in an assignment context it has the target type + if (expression.is(Tree.Kind.SWITCH_EXPRESSION) && !target.isUnknown() && !target.isPrimitive() && !expression.symbolType().isPrimitive()) { + ascribe(expression, target); + } + // a reference conditional is a poly expression: in an assignment context it has the target type + if (expression instanceof ConditionalExpressionTree && keepsArguments(target) && sameErasure(target, expression.symbolType())) { + ascribe(expression, target); + } + if (expression instanceof MethodInvocationTreeImpl call && call.methodSymbol() instanceof JMethodSymbol generic && !generic.isUnknown() && !call.symbolType().isParameterized()) { + Type inferred = sema.targetedReturn(generic, target); + if (inferred != null) { + ascribe(call, inferred); + List parameters = sema.targetedParameters(generic, target); + if (parameters != null && parameters.size() == generic.parameterTypes().size()) { + ascribeArguments(generic, parameters, call.arguments()); + } + } + } + if (expression instanceof MethodInvocationTreeImpl call && call.methodSymbol() instanceof JMethodSymbol generic && !generic.isUnknown() && call.symbolType().isParameterized() + && target.isParameterized() && call.arguments().stream().anyMatch(argument -> argument.is(Tree.Kind.METHOD_INVOCATION) && argument.symbolType().is("java.util.stream.Collector"))) { + Type retargeted = sema.retargetedElement(generic, generic.owner().type(), call.symbolType(), target); + if (retargeted != null) { + ascribe(call, retargeted); + } + } + if (expression instanceof LambdaExpressionTreeImpl lambda) { + bindLambdaParameterOwner(lambda, lambda.symbolType()); + } + } + + /** A diamond takes the type arguments its target gives the created class, and its constructor is seen from that type. */ + private void inferDiamond(NewClassTreeImpl tree, Type target) { + if (!(tree.identifier() instanceof JavaTree.ParameterizedTypeTreeImpl generic) || !generic.typeArguments().isEmpty() || !target.isParameterized()) { + return; + } + boolean anonymous = tree.classBody() != null && tree.classBody().symbol() instanceof JTypeSymbol body && !body.isUnknown(); + // an anonymous class keeps its own type; the diamond parameterizes the supertype it names + Type inferred = sema.inferDiamond(anonymous ? generic.symbolType() : tree.symbolType(), sema.groundType(target)); + if (!inferred.isParameterized()) { + return; + } + ascribe(generic, inferred); + if (anonymous) { + ((JTypeSymbol) tree.classBody().symbol()).declaredSupertype(inferred); + return; + } + ascribe(tree, inferred); + if (tree.getConstructorIdentifier() instanceof IdentifierTreeImpl identifier) { + ascribe(identifier, inferred); + if (identifier.symbol() instanceof JMethodSymbol constructor && !constructor.isUnknown()) { + List parameters = sema.invocationParameters(constructor, inferred, argumentTypes(tree.arguments())); + bind(identifier, sema.invocationView(constructor, inferred, parameters, constructor.returnType().type())); + } + } + } + + private void bindLambdaParameterOwner(LambdaExpressionTreeImpl lambda, Type target) { + JMethodSymbol functional = sema.functionalMethod(target); + if (functional == null || functional.parameterTypes().size() != lambda.parameters().size()) { + return; + } + List substituted = sema.invocationParameters(functional, target, List.of()); + List types = new ArrayList<>(); + for (int i = 0; i < lambda.parameters().size(); i++) { + VariableTree parameter = lambda.parameters().get(i); + Type type = parameter.symbol().type(); + if ((type == null || type.isUnknown()) && parameter.symbol() instanceof JVariableSymbol symbol && !substituted.get(i).isUnknown()) { + type = substituted.get(i); + symbol.type(type); + ascribe((IdentifierTreeImpl) parameter.simpleName(), type); + } + if (parameter.type() instanceof InferedTypeTree inferred && inferred.symbolType().isUnknown() && type != null && !type.isUnknown()) { + ascribe(inferred, type); + } + types.add(type == null || type.isUnknown() ? functional.parameterTypes().get(i) : type); + } + JMethodSymbol shared = sema.invocationView(functional, target, types, sema.invocationReturn(functional, target, List.of())); + var arrow = lambda.arrowToken().range().start(); + JMethodSymbol view = shared.lambdaView(functional.id + "$lambda$" + arrow.line() + ":" + arrow.column() + "()"); + lambda.setSymbol(view); + for (VariableTree parameter : lambda.parameters()) { + if (parameter.symbol() instanceof JVariableSymbol symbol) { + symbol.owner(view); + } + } + ascribeLambdaResults(lambda, view.returnType().type()); + lambda.body().accept(new BaseTreeVisitor() { + @Override + public void visitVariable(VariableTree tree) { + if (tree.symbol() instanceof JVariableSymbol symbol && symbol.owner() instanceof JSymbol owner && owner.id != null && owner.id.contains("$lambda$")) { + symbol.owner(view); + } + super.visitVariable(tree); + } + + @Override + public void visitIdentifier(IdentifierTree tree) { + if (tree instanceof IdentifierTreeImpl use && use.symbolType().isUnknown() && use.symbol() instanceof JVariableSymbol variable + && lambda.parameters().stream().anyMatch(parameter -> parameter.symbol().equals(variable)) && variable.type() != null && !variable.type().isUnknown()) { + ascribe(use, variable.type()); + } + } + + @Override + public void visitLambdaExpression(LambdaExpressionTree tree) { + // nested lambdas own their variables + } + + @Override + public void visitClass(ClassTree tree) { + // local and anonymous classes own their variables + } + }); + } + + /** The values a lambda returns take the return type of the functional method as their target. */ + private void ascribeLambdaResults(LambdaExpressionTreeImpl lambda, Type returned) { + if (returned.isUnknown() || returned.isVoid()) { + return; + } + if (lambda.body() instanceof ExpressionTree value) { + ascribeTarget(value, returned); + return; + } + lambda.body().accept(new BaseTreeVisitor() { + @Override + public void visitReturnStatement(ReturnStatementTree tree) { + if (tree.expression() != null) { + ascribeTarget(tree.expression(), returned); + } + } + + @Override + public void visitLambdaExpression(LambdaExpressionTree tree) { + // nested lambdas have their own results + } + + @Override + public void visitClass(ClassTree tree) { + // local and anonymous classes have their own methods + } + }); + } + + private void ascribeArguments(Symbol.MethodSymbol method, List arguments) { + ascribeArguments(method, method.parameterTypes(), arguments); + } + + /** Types the arguments from the declared parameters, substituted for the receiver's type arguments when the call is generic. */ + private void ascribeArguments(Symbol.MethodSymbol method, List parameters, List arguments) { + for (int i = 0; i < arguments.size() && !parameters.isEmpty(); i++) { + Type parameter = parameters.get(Math.min(i, parameters.size() - 1)); + if (method.isVarArgsMethod() && i >= parameters.size() - 1 && parameter.isArray() + && (arguments.size() != parameters.size() || arguments.get(i).is(Tree.Kind.LAMBDA_EXPRESSION, Tree.Kind.METHOD_REFERENCE))) { + parameter = ((Type.ArrayType) parameter).elementType(); + } + if (i < parameters.size() || method.isVarArgsMethod()) { + ascribeTarget(arguments.get(i), parameter); + } + } + } + + private static Set functionArguments(List arguments) { + Set functions = new HashSet<>(); + for (int i = 0; i < arguments.size(); i++) { + if (arguments.get(i).is(Tree.Kind.LAMBDA_EXPRESSION, Tree.Kind.METHOD_REFERENCE)) { + functions.add(i); + } + } + return functions; + } + + private static List argumentTypes(List arguments) { + return arguments.stream().map(ExpressionTree::symbolType).toList(); + } + + private void bindType(IdentifierTreeImpl identifier, String fqn) { + Symbol symbol = sema.resolve(fqn); + bind(identifier, symbol); + ascribe(identifier, symbol.type()); + sema.use(fqn, identifier); + } + + private void bindQualifierPackages(ExpressionTree qualifier, IdentifierTree identifier) { + if (identifier.symbol() instanceof Symbol.TypeSymbol type && !type.isUnknown()) { + Symbol owner = type.owner(); + while (owner != null && !owner.isPackageSymbol()) { + owner = owner.owner(); + } + if (owner != null && dottedName(qualifier).equals(owner.name())) { + bindPackage(qualifier, owner.name()); + } + } + } + + private void bindPackage(ExpressionTree tree, String name) { + ExpressionTree last = tree; + if (tree instanceof MemberSelectExpressionTree select) { + int dot = name.lastIndexOf('.'); + if (dot < 0) { + return; + } + bindPackage(select.expression(), name.substring(0, dot)); + last = select.identifier(); + } + if (last instanceof IdentifierTreeImpl identifier && identifier.symbol().isUnknown()) { + bind(identifier, sema.packageSymbol(name)); + } + } + + private static String dottedName(ExpressionTree tree) { + if (tree instanceof MemberSelectExpressionTree select) { + String qualifier = dottedName(select.expression()); + return qualifier.isEmpty() ? "" : (qualifier + "." + select.identifier().name()); + } + return tree instanceof IdentifierTree identifier ? identifier.name() : ""; + } + + private IdentifierTreeImpl identifier(Node node) { + String text = node.text().isEmpty() ? node.k() : node.text(); + return new IdentifierTreeImpl(tokens.getOrDefault(node.proto, new InternalSyntaxToken(node.line(), node.col(), text, List.of(), false)), unnamedVariables && "_".equals(text)); + } + + private LiteralTreeImpl integerLiteral(Node node) { + String text = node.text(); + boolean isLong = text.endsWith("l") || text.endsWith("L"); + return literal(isLong ? Tree.Kind.LONG_LITERAL : Tree.Kind.INT_LITERAL, token(node), sema.getClassType(isLong ? "long" : "int")); + } + + private LiteralTreeImpl floatingLiteral(Node node) { + String text = node.text(); + boolean isFloat = text.endsWith("f") || text.endsWith("F"); + return literal(isFloat ? Tree.Kind.FLOAT_LITERAL : Tree.Kind.DOUBLE_LITERAL, token(node), sema.getClassType(isFloat ? "float" : "double")); + } + + private LiteralTreeImpl literal(Tree.Kind kind, InternalSyntaxToken token, Type type) { + LiteralTreeImpl tree = new LiteralTreeImpl(kind, token); + ascribe(tree, type); + return tree; + } + + private MemberSelectExpressionTreeImpl memberSelect(Node node) { + Node object = field(node, "object"); + if (object == null) { + object = field(node, "scope"); + } + Node name = field(node, "name"); + if (name == null) { + name = field(node, "field"); + } + Node scope = object == null ? firstNamed(node) : object; + ExpressionTree qualifier = object == null && compoundName(scope) ? typeExpression(scope) : (object == null ? primary(scope) : superQualifier(node, object)); + Node nameNode = name == null ? lastNamed(node) : name; + IdentifierTreeImpl identifier = receiverKeyword(identifier(nameNode)); + bindUse(identifier, name != null || nameNode.proto.getRefsCount() > 0 ? nameNode : node, true); + if (!naming) { + bindQualifiedReceiver(qualifier, identifier); + if (identifier.symbol().isUnknown()) { + resolveQualifiedType(qualifier, identifier); + } + if (identifier.symbol().isUnknown()) { + String owner = fieldOwner(qualifier); + Symbol.VariableSymbol field = owner == null ? null : sema.declaredField(owner, identifier.name()); + if (field != null) { + bind(identifier, field); + ascribe(identifier, field.type()); + } + } + bindQualifierPackages(qualifier, identifier); + if (identifier.symbol() instanceof JVariableSymbol field && !field.isUnknown() && field.type() != null) { + Type read = sema.fieldTypeOn(field, qualifier.symbolType()); + if (read != field.type()) { + ascribe(identifier, read); + } + } + } + List annotations = node.children().stream().filter(SemSitterTranslator::isAnnotation).map(this::annotation).toList(); + if (!annotations.isEmpty()) { + identifier.complete(annotations); + } + MemberSelectExpressionTreeImpl tree = new MemberSelectExpressionTreeImpl(qualifier, token(lastKeyword(node, ".")), identifier); + ascribe(tree, identifier.symbolType()); + return tree; + } + + /** The {@code this} or {@code super} written after a qualifier is a keyword, not a name. */ + private static IdentifierTreeImpl receiverKeyword(IdentifierTreeImpl identifier) { + return switch (identifier.name()) { + case "this" -> new KeywordThis((InternalSyntaxToken) identifier.identifierToken(), Symbol.UNKNOWN_SYMBOL); + case "super" -> new KeywordSuper((InternalSyntaxToken) identifier.identifierToken(), Symbol.UNKNOWN_SYMBOL); + default -> identifier; + }; + } + + private ExpressionTree superQualifier(Node node, Node object) { + ExpressionTree qualifier = expression(object); + Node superNode = keyword(node, "super"); + if (superNode == null || same(superNode, object)) { + return qualifier; + } + IdentifierTreeImpl identifier = new KeywordSuper(token(superNode), Symbol.UNKNOWN_SYMBOL); + bindQualifiedReceiver(qualifier, identifier); + MemberSelectExpressionTreeImpl select = new MemberSelectExpressionTreeImpl(qualifier, token(required(node, ".")), identifier); + ascribe(select, identifier.symbolType()); + return select; + } + + private void bindQualifiedReceiver(ExpressionTree qualifier, IdentifierTreeImpl identifier) { + boolean isThis = "this".equals(identifier.name()); + if (!identifier.symbol().isUnknown() || (!isThis && !"super".equals(identifier.name())) + || !(qualifier.symbolType().symbol() instanceof Symbol.TypeSymbol owner) || owner.isUnknown()) { + return; + } + Type type = isThis || owner.isInterface() || owner.superClass() == null ? owner.type() : owner.superClass(); + bind(identifier, sema.receiverSymbol(owner, identifier.name(), type)); + ascribe(identifier, type); + } + + private static boolean compoundName(Node node) { + return switch (node.k()) { + case "scoped_type_identifier", "scoped_identifier", "generic_type", "field_access" -> true; + default -> false; + }; + } + + private MethodInvocationTreeImpl invocation(Node node) { + Node name = field(node, "name"); + Node object = field(node, "object"); + IdentifierTreeImpl identifier = identifier(name == null ? firstOf(node, "identifier") : name); + bindUse(identifier, name == null ? node : name, object != null); + ExpressionTree select; + ExpressionTree qualifier = null; + if (object == null) { + select = identifier; + } else { + qualifier = superQualifier(node, object); + select = new MemberSelectExpressionTreeImpl(qualifier, token(lastKeyword(node, ".")), identifier); + } + Node typeArguments = field(node, "type_arguments"); + MethodInvocationTreeImpl tree = new MethodInvocationTreeImpl(select, typeArguments == null ? null : typeArguments(typeArguments), arguments(requiredField(node, "arguments", childKind(node, "argument_list")))); + Type receiver = qualifier == null ? currentType() : qualifier.symbolType(); + String target = (name == null ? node : name).valueTarget(); + boolean arityOnly = target != null && ARITY_ONLY.matcher(target).matches(); + List arguments = argumentTypes(tree.arguments()); + if (qualifier == null && staticImports.containsKey(identifier.name())) { + boolean declaredHere = types.stream().filter(type -> !type.isUnknown()) + .anyMatch(type -> sema.declaredMethod(type.type().fullyQualifiedName(), identifier.name(), arguments) != null); + if (!declaredHere) { + Symbol.MethodSymbol imported = sema.declaredMethod(staticImports.get(identifier.name()), identifier.name(), arguments); + if (imported != null) { + bind(identifier, imported); + } + } + } + if (identifier.symbol().isUnknown() || arityOnly) { + Symbol.MethodSymbol method = arityOnly + ? sema.declaredMethod(JSema.erase(target.substring(0, target.indexOf('#'))), identifier.name(), arguments) + : libraryMethod(qualifier, identifier.name(), arguments, functionArguments(tree.arguments())); + if (method != null) { + bind(identifier, method); + } + } else if (identifier.symbol() instanceof Symbol.MethodSymbol bound) { + Set functions = functionArguments(tree.arguments()); + bind(identifier, sema.preferOverload(bound, libraryMethod(qualifier, identifier.name(), arguments, functions), arguments, functions)); + } + if (identifier.symbol() instanceof JMethodSymbol method && !method.isUnknown() && !JSema.arityMatches(method, arguments.size())) { + bind(identifier, Symbol.MethodSymbol.UNKNOWN_METHOD); + } + if (identifier.symbol() instanceof JMethodSymbol chosen && !naming) { + JMethodSymbol specific = sema.mostSpecificVarArgs(chosen, arguments); + if (specific != chosen) { + sema.moveUse(chosen.id, specific.id, identifier); + bind(identifier, specific); + } + } + if (qualifier != null && receiver.isUnknown() && !receiver.symbol().isUnknown() && !naming) { + // a member of a parameterization with an undeclared argument is not bound + bind(identifier, Symbol.MethodSymbol.UNKNOWN_METHOD); + } + if (identifier.symbol() instanceof JMethodSymbol method) { + List explicit = tree.typeArguments() == null ? List.of() : tree.typeArguments().stream().map(argument -> ((TypeTree) argument).symbolType()).toList(); + List parameters = sema.withExplicitTypeArguments(explicit, () -> sema.invocationParameters(method, receiver, arguments)); + ascribeArguments(method, parameters, tree.arguments()); + List typed = new ArrayList<>(arguments); + for (int i = 0; i < typed.size(); i++) { + if (tree.arguments().get(i).is(Tree.Kind.METHOD_INVOCATION)) { + typed.set(i, tree.arguments().get(i).symbolType()); + } else if (tree.arguments().get(i) instanceof MethodReferenceTreeImpl reference && i < parameters.size() && referenceResult(reference, parameters.get(i)) instanceof Type produced) { + Type function = sema.functionProducing(parameters.get(i), produced); + if (function != null) { + typed.set(i, function); + } + } else if (tree.arguments().get(i) instanceof LambdaExpressionTreeImpl lambda && lambda.body() instanceof ExpressionTree value && i < parameters.size()) { + Type function = sema.functionProducing(parameters.get(i), value.symbolType()); + if (function != null) { + typed.set(i, function); + } + } + } + Type returned = sema.withExplicitTypeArguments(explicit, () -> sema.invocationReturn(method, receiver, typed)); + Type erased = qualifier != null && receiver.isRawType() && isWrittenRaw(qualifier) ? sema.rawReturn(method) : null; + if (erased != null) { + // a member of a raw type has the erasure of its declared type + returned = erased; + rawResults.add(tree); + } + if ("getClass".equals(method.name()) && arguments.isEmpty() && method.owner().type().is("java.lang.Object") && !receiver.isUnknown() && receiver.erasure() instanceof JType erasedReceiver) { + // the static type of the call is Class where T is the static type of the receiver + returned = JType.named(sema, "java.lang.Class", List.of(JType.wildcard(sema, erasedReceiver))); + } + List thrownArguments = withCreatedTypes(tree.arguments(), typed); + List thrown = sema.withExplicitTypeArguments(explicit, () -> sema.invocationThrown(method, receiver, thrownArguments)); + JMethodSymbol view = sema.invocationView(method, receiver, parameters, returned, thrown); + bindMethod(tree, view); + bind(identifier, view); + ascribe(identifier, returned); + ascribe(tree, returned); + } else if (tree.methodSymbol().isUnknown()) { + // An unresolved call keeps its written name, as a recovered binding does. + JMethodSymbol unresolved = new JMethodSymbol(sema, null, identifier.name()); + unresolved.unknown(true); + bindMethod(tree, unresolved); + } + return tree; + } + + /** + * The type a method reference yields, or null when it is a constructor reference or the method is generic or unknown. + * An unbound {@code Type::method} returning a class type variable takes it from the function's first parameter. + */ + @Nullable + private Type referenceResult(MethodReferenceTreeImpl reference, Type function) { + if (!(reference.method().symbol() instanceof JMethodSymbol method) || method.isUnknown() || "new".equals(method.name()) || "".equals(method.name())) { + return null; + } + Type returned = method.returnType().type(); + if (sema.returnsClassVariable(method) && namesType(reference.expression())) { + return sema.unboundReferenceResult(method, function); + } + return returned == null || returned.isUnknown() || returned.isTypeVar() || returned.isVoid() ? null : returned; + } + + private static boolean namesType(Tree expression) { + if (expression instanceof IdentifierTree identifier) { + return identifier.symbol().isTypeSymbol(); + } + return expression instanceof MemberSelectExpressionTree select ? select.identifier().symbol().isTypeSymbol() : expression instanceof ParameterizedTypeTree; + } + + /** + * The argument types with each supplier of a created object, {@code Type::new} or {@code () -> new Type(..)}, + * typed as {@code Supplier}: the type a generic throws clause is inferred from. + */ + private List withCreatedTypes(List expressions, List types) { + List result = new ArrayList<>(types); + for (int i = 0; i < result.size(); i++) { + Type created = null; + ExpressionTree argument = expressions.get(i); + if (argument instanceof MethodReferenceTreeImpl reference && "new".equals(reference.method().name()) && reference.expression() instanceof TypeTree qualifier) { + created = qualifier.symbolType(); + } else if (argument instanceof LambdaExpressionTreeImpl lambda && lambda.parameters().isEmpty() && lambda.body() instanceof NewClassTreeImpl creation) { + created = creation.symbolType(); + } + if (created != null && !created.isUnknown() && created.isClass()) { + result.set(i, JType.named(sema, "java.util.function.Supplier", List.of(sema.asJType(created)))); + } + } + return result; + } + + private ExpressionTree typeExpression(Node node) { + TypeTree type = type(node); + return type instanceof ExpressionTree expression ? expression : literal(Tree.Kind.NULL_LITERAL, synthetic("null"), Type.UNKNOWN); + } + + private NewClassTreeImpl creation(Node node) { + Node typeNode = field(node, "type"); + TypeTree type = annotate(recoverQualifiedType(type(Objects.requireNonNull(typeNode == null ? firstType(node) : typeNode))), node); + Node arguments = field(node, "arguments"); + ArgumentListTreeImpl args = arguments == null ? ArgumentListTreeImpl.emptyList().complete(synthetic("("), synthetic(")")) : arguments(arguments); + Node body = field(node, "body"); + if (body == null) { + body = childKind(node, "class_body"); + } + ClassTreeImpl classBody = null; + if (body != null) { + classBody = new ClassTreeImpl(Tree.Kind.CLASS, token(required(body, "{")), membersOf(body), token(required(body, "}"))); + // An anonymous class is declared at its creation expression, whatever its members. + bindType(classBody, node.decl() != null ? node : body); + } + NewClassTreeImpl tree = new NewClassTreeImpl(type, args, classBody).completeWithNewKeyword(token(required(node, "new"))); + Node enclosing = node.children().get(0); + if (!"new".equals(enclosing.text())) { + tree.completeWithEnclosingExpression(expression(enclosing)); + tree.completeWithDotToken(token(required(node, "."))); + } + Node typeArguments = field(node, "type_arguments"); + if (typeArguments != null) { + tree.completeWithTypeArguments(typeArguments(typeArguments)); + } + bindConstructor(tree, typeNode); + ascribe(tree, classBody != null && !classBody.symbol().isUnknown() ? classBody.symbol().type() : type.symbolType()); + return tree; + } + + private void bindConstructor(NewClassTreeImpl tree, @Nullable Node typeNode) { + if (!(tree.getConstructorIdentifier() instanceof IdentifierTreeImpl identifier)) { + return; + } + TypeTree written = tree.identifier() instanceof ParameterizedTypeTree parameterized ? parameterized.type() : tree.identifier(); + String imported = written instanceof MemberSelectExpressionTree ? null : singleImports.get(identifier.name()); + String constructor = typeNode == null ? null : typeNode.valueTarget(); + if (constructor != null) { + Symbol resolved = sema.resolve(constructor); + String owner = resolved.owner() == null || resolved.owner().type() == null ? "" : resolved.owner().type().erasure().fullyQualifiedName(); + boolean importedElsewhere = imported != null && sema.declaresType(imported) && !imported.equals(owner); + if (resolved instanceof Symbol.MethodSymbol method && !importedElsewhere && JSema.arityMatches(method, tree.arguments().size())) { + bind(identifier, resolved); + recordUse(resolved, identifier); + ascribeArguments(method, tree.arguments()); + viewWithInferredParameters(tree, identifier); + return; + } + } + Type type = tree.identifier().symbolType().erasure(); + if (imported != null && sema.declaresType(imported) && !imported.equals(type.fullyQualifiedName())) { + type = sema.getClassType(imported); + bindType(identifier, imported); + } + String owner = tree.classBody() != null && type.symbol().isInterface() ? "java.lang.Object" : type.fullyQualifiedName(); + Symbol.MethodSymbol declared = type.isClass() ? sema.declaredMethod(owner, "", argumentTypes(tree.arguments()), functionArguments(tree.arguments())) : null; + if (declared != null && JSema.arityMatches(declared, tree.arguments().size())) { + bind(identifier, declared); + recordUse(declared, identifier); + ascribeArguments(declared, tree.arguments()); + viewWithInferredParameters(tree, identifier); + } else if (!(identifier.symbol() instanceof Symbol.MethodSymbol)) { + bind(identifier, Symbol.MethodSymbol.UNKNOWN_METHOD); + } + } + + /** A diamond without a target takes the class arguments its constructor arguments fix. */ + private void inferDiamondFromArguments(NewClassTreeImpl tree, JMethodSymbol constructor) { + if (!(tree.identifier() instanceof JavaTree.ParameterizedTypeTreeImpl generic) || !generic.typeArguments().isEmpty()) { + return; + } + Type inferred = sema.inferDiamondFromArguments(constructor, generic.symbolType(), argumentTypes(tree.arguments())); + if (inferred.isParameterized()) { + ascribe(generic, inferred); + } + } + + /** A generic constructor is seen with the type arguments its call infers for the parameters. */ + private void viewWithInferredParameters(NewClassTreeImpl tree, IdentifierTreeImpl identifier) { + if (!(identifier.symbol() instanceof JMethodSymbol constructor) || constructor.isUnknown()) { + return; + } + inferDiamondFromArguments(tree, constructor); + List parameters = sema.invocationParameters(constructor, tree.identifier().symbolType(), argumentTypes(tree.arguments())); + if (!parameters.equals(constructor.parameterTypes())) { + JMethodSymbol view = sema.invocationView(constructor, tree.identifier().symbolType(), parameters, constructor.returnType().type()); + if (view != constructor && !constructor.isParametrizedMethod()) { + // the class arguments written at the call do not make the constructor generic + view.parametrized(false); + } + bind(identifier, view); + } + } + + /** Whether a receiver is raw because of what is written: a variable declared with a raw type, or the erased result of such a call. */ + private boolean isWrittenRaw(ExpressionTree qualifier) { + if (rawResults.contains(qualifier)) { + return true; + } + Symbol symbol = qualifier instanceof IdentifierTree identifier ? identifier.symbol() : Symbol.UNKNOWN_SYMBOL; + return symbol.isVariableSymbol() && symbol.declaration() instanceof VariableTree variable + && variable.type() instanceof IdentifierTree && !"var".equals(((IdentifierTree) variable.type()).name()); + } + + private NewArrayTreeImpl arrayCreation(Node node) { + Node initializer = field(node, "value"); + List dims = new ArrayList<>(); + for (Node child : node.children()) { + // sized dimensions, then unsized ones: new byte[n][] + if ("dimensions_expr".equals(child.k()) || "dimensions".equals(child.k())) { + dims.addAll(dimensions(child)); + } + } + InitializerListTreeImpl initializers = initializer == null ? InitializerListTreeImpl.emptyList() : initializers(initializer); + NewArrayTreeImpl tree = new NewArrayTreeImpl(dims, initializers) + .complete(annotate(type(requiredField(node, "type", firstType(node))), node)) + .completeWithNewKeyword(token(required(node, "new"))); + if (initializer != null) { + tree.completeWithCurlyBraces(token(required(initializer, "{")), token(required(initializer, "}"))); + } + int rank = dims.size(); + if (rank == 0 && initializer != null) { + rank = 1; + } + ascribe(tree, arrayTypeOf(tree.type(), rank)); + return tree; + } + + private NewArrayTreeImpl arrayInitializer(Node node) { + NewArrayTreeImpl tree = new NewArrayTreeImpl(List.of(), initializers(node)).completeWithCurlyBraces(token(required(node, "{")), token(required(node, "}"))); + return tree; + } + + private AssignmentExpressionTreeImpl elementValuePair(Node node) { + Node key = requiredField(node, "key", firstNamed(node)); + IdentifierTreeImpl name = identifier(key); + // An element name is never a local variable or a parameter of the same name. + bindUse(name, key, true); + ExpressionTree value = expression(requiredField(node, "value", lastNamed(node))); + AssignmentExpressionTreeImpl tree = new AssignmentExpressionTreeImpl(Tree.Kind.ASSIGNMENT, name, token(required(node, "=")), value); + ascribe(tree, value.symbolType()); + return tree; + } + + private MemberSelectExpressionTreeImpl classLiteral(Node node) { + ExpressionTree type = (ExpressionTree) recoverQualifiedType(type(firstNamed(node))); + IdentifierTreeImpl className = new IdentifierTreeImpl(token(required(node, "class"))); + MemberSelectExpressionTreeImpl tree = new MemberSelectExpressionTreeImpl(type, token(required(node, ".")), className); + Type literal = type.symbolType().isPrimitive() ? type.symbolType().primitiveWrapperType() : type.symbolType(); + JType argument = literal instanceof JType jType ? jType : JType.unknown(sema); + ascribe(tree, JType.inferred(sema, "java.lang.Class", List.of(argument))); + return tree; + } + + private InitializerListTreeImpl initializers(Node node) { + InitializerListTreeImpl list = InitializerListTreeImpl.emptyList(); + for (Node child : node.children()) { + if ("{".equals(child.text()) || "}".equals(child.text())) { + continue; + } + if (",".equals(child.text())) { + list.separators().add(token(child)); + } else { + list.add(expression(child)); + } + } + return list; + } + + private ArrayAccessExpressionTreeImpl arrayAccess(Node node) { + Node index = field(node, "index"); + ExpressionTree array = expression(requiredField(node, "array", firstNamed(node))); + ArrayDimensionTreeImpl dimension = new ArrayDimensionTreeImpl(token(required(node, "[")), index == null ? null : expression(index), token(required(node, "]"))); + ArrayAccessExpressionTreeImpl tree = new ArrayAccessExpressionTreeImpl(array, dimension); + Type arrayType = array.symbolType(); + ascribe(tree, arrayType.isArray() ? ((Type.ArrayType) arrayType).elementType() : Type.UNKNOWN); + return tree; + } + + private AssignmentExpressionTreeImpl assignment(Node node) { + Node operator = field(node, "operator"); + String text = operator == null ? "=" : operator.text(); + AssignmentExpressionTreeImpl tree = new AssignmentExpressionTreeImpl( + assignmentKind(text), + expression(requiredField(node, "left", firstNamed(node))), + operator == null ? token(required(node, text)) : token(operator), + expression(requiredField(node, "right", lastNamed(node)))); + ascribe(tree, tree.variable().symbolType()); + if (tree.is(Tree.Kind.ASSIGNMENT)) { + ascribeTarget(tree.expression(), tree.variable().symbolType()); + } + return tree; + } + + private BinaryExpressionTreeImpl binary(Node node) { + Node operator = field(node, "operator"); + String text = operator == null ? "+" : operator.text(); + ExpressionTree left = expression(requiredField(node, "left", firstNamed(node))); + ExpressionTree right = expression(requiredField(node, "right", lastNamed(node))); + BinaryExpressionTreeImpl tree = new BinaryExpressionTreeImpl(binaryKind(text), left, operator == null ? synthetic(text) : token(operator), right); + ascribe(tree, binaryType(text, left.symbolType(), right.symbolType())); + return tree; + } + + private ExpressionTree unary(Node node, boolean prefix) { + Node operator = field(node, "operator"); + Node operand = field(node, "operand"); + if (operand == null) { + operand = firstNamed(node); + } + String text = operator == null ? "!" : operator.text(); + ExpressionTree value = expression(operand); + InternalPrefixUnaryExpression tree = new InternalPrefixUnaryExpression(unaryKind(text, true), operator == null ? synthetic(text) : token(operator), value); + ascribe(tree, "!".equals(text) ? sema.getClassType("boolean") : unaryPromoted(text, value.symbolType())); + return tree; + } + + /** {@code +}, {@code -} and {@code ~} promote a byte, short or char operand to int. */ + private Type unaryPromoted(String operator, Type operand) { + Type primitive = unboxed(operand); + boolean promoting = "+".equals(operator) || "-".equals(operator) || "~".equals(operator); + boolean narrow = primitive.is("byte") || primitive.is("short") || primitive.is("char"); + if (!promoting || !primitive.isPrimitive()) { + return operand; + } + return narrow ? sema.getClassType("int") : primitive; + } + + private ExpressionTree update(Node node) { + Node operator = field(node, "operator"); + List children = node.children(); + if (operator == null) { + operator = children.stream().filter(child -> "++".equals(child.text()) || "--".equals(child.text())).findFirst().orElse(null); + } + boolean prefix = !children.isEmpty() && ("++".equals(children.get(0).text()) || "--".equals(children.get(0).text())); + ExpressionTree operand = expression(firstNamed(node)); + String text = operator == null ? "++" : operator.text(); + InternalSyntaxToken token = operator == null ? synthetic(text) : token(operator); + ExpressionTree tree = prefix + ? new InternalPrefixUnaryExpression(unaryKind(text, true), token, operand) + : new InternalPostfixUnaryExpression(unaryKind(text, false), operand, token); + ascribe((AbstractTypedTree) tree, operand.symbolType()); + return tree; + } + + private ParenthesizedTreeImpl parenthesized(Node node) { + Parens parens = parens(node); + ParenthesizedTreeImpl tree = new ParenthesizedTreeImpl(parens.open, parens.expr, parens.close); + ascribe(tree, parens.expr.symbolType()); + return tree; + } + + private ConditionalExpressionTreeImpl ternary(Node node) { + ExpressionTree condition = expression(requiredField(node, "condition", firstNamed(node))); + ExpressionTree then = expression(requiredField(node, "consequence", firstNamed(node))); + ExpressionTree otherwise = expression(requiredField(node, "alternative", lastNamed(node))); + ConditionalExpressionTreeImpl tree = new ConditionalExpressionTreeImpl(condition, token(required(node, "?")), then, token(required(node, ":")), otherwise); + ascribe(tree, conditionalType(then, otherwise)); + return tree; + } + + /** The type of a conditional: operands of numeric or boolean types are unboxed and promoted, others keep the more general operand type. */ + private Type conditionalType(ExpressionTree then, ExpressionTree otherwise) { + Type first = then.symbolType(); + Type second = otherwise.symbolType(); + if (first.isUnknown() || second.isUnknown()) { + return first.isUnknown() ? second : first; + } + if (first.equals(second)) { + return first; + } + Type left = first.isPrimitive() ? first : first.primitiveType(); + Type right = second.isPrimitive() ? second : second.primitiveType(); + boolean oneIsPrimitive = first.isPrimitive() || second.isPrimitive(); + if (left != null && right != null && (oneIsPrimitive || (first.isPrimitiveWrapper() && second.isPrimitiveWrapper() && !left.equals(right)))) { + if (left.equals(right)) { + return left; + } + if (left.is("boolean") || right.is("boolean")) { + return first; + } + return numericPromotion(left, right, then, otherwise); + } + if (first.isNullType() && second.isPrimitive()) { + return second.primitiveWrapperType(); + } + if (second.isNullType() && first.isPrimitive()) { + return first.primitiveWrapperType(); + } + if (first.isNullType()) { + return second; + } + if (second.isNullType()) { + return first; + } + // a type variable is compared by its bound: erasing it would make the variable look like its own bound + if ((first.isTypeVar() || second.isTypeVar()) && !first.isPrimitive() && !second.isPrimitive()) { + if (second.isSubtypeOf(first)) { + return first; + } + if (first.isSubtypeOf(second)) { + return second; + } + Type firstBound = first instanceof JType variable && variable.isTypeVar() ? sema.typeVariableBound(variable.typeVarId) : first; + Type secondBound = second instanceof JType variable && variable.isTypeVar() ? sema.typeVariableBound(variable.typeVarId) : second; + return !secondBound.isSubtypeOf(firstBound.erasure()) && firstBound.isSubtypeOf(secondBound.erasure()) ? secondBound : firstBound; + } + if (!first.isPrimitive() && !second.isPrimitive() && second.isSubtypeOf(first.erasure())) { + return first; + } + if (!first.isPrimitive() && !second.isPrimitive() && first.isSubtypeOf(second.erasure())) { + return second; + } + return first; + } + + private Type numericPromotion(Type left, Type right, ExpressionTree then, ExpressionTree otherwise) { + List order = List.of("byte", "short", "char", "int", "long", "float", "double"); + int a = order.indexOf(left.fullyQualifiedName()); + int b = order.indexOf(right.fullyQualifiedName()); + if (a < 0 || b < 0) { + return left; + } + boolean byteAndShort = (a == 0 && b == 1) || (a == 1 && b == 0); + if (byteAndShort) { + return sema.getClassType("short"); + } + // a constant int that fits the narrower operand keeps that type + if (a < 3 && right.is("int") && otherwise.is(Tree.Kind.INT_LITERAL)) { + return left; + } + if (b < 3 && left.is("int") && then.is(Tree.Kind.INT_LITERAL)) { + return right; + } + return sema.getClassType(order.get(Math.max(3, Math.max(a, b)))); + } + + private TypeCastExpressionTreeImpl cast(Node node) { + List typeNodes = node.children().stream().filter(child -> "type".equals(child.f())).toList(); + TypeTree type = type(typeNodes.isEmpty() ? firstType(node) : typeNodes.get(0)); + List ands = node.children().stream().filter(child -> "&".equals(child.k())).toList(); + QualifiedIdentifierListTreeImpl bounds = QualifiedIdentifierListTreeImpl.emptyList(); + for (int i = 1; i < typeNodes.size(); i++) { + bounds.add(type(typeNodes.get(i))); + if (i < typeNodes.size() - 1 && i < ands.size()) { + bounds.separators().add(token(ands.get(i))); + } + } + ExpressionTree value = expression(requiredField(node, "value", lastNamed(node))); + InternalSyntaxToken andToken = bounds.isEmpty() || ands.isEmpty() ? null : token(ands.get(0)); + TypeCastExpressionTreeImpl tree = new TypeCastExpressionTreeImpl(token(required(node, "(")), type, andToken, bounds, token(required(node, ")")), value); + if (bounds.isEmpty()) { + ascribe(tree, type.symbolType()); + // The cast type is the target of a lambda operand (JLS 15.16). Only its parameters are rebound: typing the lambda itself would make the cast look redundant. + // The rebinding mirrors the ECJ-based analysis, which suppresses S1117 for a lambda parameter whose target is a nested, implicitly static interface. + if (value instanceof LambdaExpressionTreeImpl lambda && !type.symbolType().isUnknown()) { + bindLambdaParameterOwner(lambda, sema.groundType(type.symbolType())); + } + } else { + List parts = new ArrayList<>(); + parts.add(sema.asJType(type.symbolType())); + bounds.forEach(bound -> parts.add(sema.asJType(bound.symbolType()))); + ascribe(tree, JType.intersection(sema, parts)); + } + return tree; + } + + private InstanceOfTreeImpl instanceOf(Node node) { + ExpressionTree left = expression(requiredField(node, "left", firstNamed(node))); + Node name = field(node, "name"); + Node right = field(node, "right"); + Node patternNode = field(node, "pattern"); + InstanceOfTreeImpl tree; + if (patternNode != null) { + tree = new InstanceOfTreeImpl(left, token(required(node, "instanceof")), pattern(patternNode)); + } else if (name != null && right != null) { + VariableTreeImpl variable = new VariableTreeImpl(modifiers(node), type(right), identifier(name)); + bindDeclaration(variable, name, (IdentifierTreeImpl) variable.simpleName()); + TypePatternTreeImpl pattern = new TypePatternTreeImpl(variable, variableType(variable)); + tree = new InstanceOfTreeImpl(left, token(required(node, "instanceof")), pattern); + } else { + tree = new InstanceOfTreeImpl(left, token(required(node, "instanceof")), type(right == null ? firstType(node) : right)); + } + ascribe(tree, sema.getClassType("boolean")); + return tree; + } + + private PatternTree pattern(Node node) { + if ("record_pattern".equals(node.k())) { + return recordPattern(node); + } + Node nested = firstOf(node, "record_pattern", "type_pattern", "pattern", "underscore_pattern"); + if (nested != null && !"type_pattern".equals(node.k())) { + return pattern(nested); + } + if ("underscore_pattern".equals(node.k())) { + return new TypePatternTreeImpl(new VariableTreeImpl(new IdentifierTreeImpl(token(node), true)), Type.UNKNOWN); + } + Node name = lastOf(node, "identifier"); + VariableTreeImpl variable = new VariableTreeImpl(modifiers(node), type(firstType(node)), identifier(name == null ? node : name)); + bindDeclaration(variable, name, (IdentifierTreeImpl) variable.simpleName()); + if (variable.symbol().type() != null && !variable.symbol().type().isUnknown()) { + ascribe(variable.type(), variable.symbol().type()); + } + return new TypePatternTreeImpl(variable, variableType(variable)); + } + + private RecordPatternTreeImpl recordPattern(Node node) { + Node body = required(node, "record_pattern_body"); + List patterns = new ArrayList<>(); + for (Node child : body.children()) { + if ("record_pattern_component".equals(child.k()) || "record_pattern".equals(child.k())) { + patterns.add(pattern(child)); + } + } + TypeTree recordType = type(firstType(node)); + deferred.add(() -> { + if (recordType.symbolType().symbol().declaration() instanceof ClassTree record && record.recordComponents().size() == patterns.size()) { + for (int i = 0; i < patterns.size(); i++) { + if (patterns.get(i) instanceof TypePatternTreeImpl unnamed && unnamed.patternVariable().symbol().isUnknown() && unnamed.patternVariable() instanceof VariableTreeImpl variable) { + patterns.set(i, typeUnnamedPattern(variable, record.recordComponents().get(i).type().symbolType())); + } + } + } + }); + return new RecordPatternTreeImpl(recordType, token(required(body, "(")), patterns, token(required(body, ")"))); + } + + /** An unnamed pattern variable has the type of the record component it stands for. */ + private TypePatternTreeImpl typeUnnamedPattern(VariableTreeImpl variable, Type type) { + var start = ((IdentifierTreeImpl) variable.simpleName()).identifierToken().range().start(); + JVariableSymbol symbol = new JVariableSymbol(sema, "_@" + start.line() + ":" + start.column(), "_", "local"); + symbol.type(type); + sema.declare(symbol.id, variable); + variable.setSymbol(symbol); + ascribe(variable.type(), type); + return new TypePatternTreeImpl(variable, type); + } + + private LambdaExpressionTreeImpl lambda(Node node) { + scopes.addFirst(new HashMap<>()); + returnTargets.push(Type.UNKNOWN); + try { + return lambdaInScope(node); + } finally { + scopes.removeFirst(); + returnTargets.pop(); + } + } + + private LambdaExpressionTreeImpl lambdaInScope(Node node) { + List parameters = new ArrayList<>(); + Node formals = field(node, "parameters"); + InternalSyntaxToken open = null; + InternalSyntaxToken close = null; + if (formals != null && ("formal_parameters".equals(formals.k()) || "inferred_parameters".equals(formals.k()))) { + open = optionalToken(formals, "("); + close = optionalToken(formals, ")"); + if ("formal_parameters".equals(formals.k())) { + parameters.addAll(parameters(formals)); + } else { + VariableTreeImpl previous = null; + for (Node child : formals.children()) { + if ("identifier".equals(child.k())) { + IdentifierTreeImpl name = identifier(child); + previous = new VariableTreeImpl(name); + bindDeclaration(previous, child, name); + parameters.add(previous); + } else if (",".equals(child.text()) && previous != null) { + previous.setEndToken(token(child)); + } + } + } + } else if (formals != null) { + IdentifierTreeImpl name = identifier(formals); + VariableTreeImpl parameter = new VariableTreeImpl(name); + bindDeclaration(parameter, formals, name); + parameters.add(parameter); + } + Node body = field(node, "body"); + Tree lambdaBody = body == null ? block(node) : ("block".equals(body.k()) ? block(body) : expression(body)); + LambdaExpressionTreeImpl tree = new LambdaExpressionTreeImpl(open, parameters, close, token(required(node, "->")), lambdaBody); + deferred.add(() -> parameters.forEach(parameter -> { + if (parameter.type() instanceof InferedTypeTree inferred && inferred.symbolType().isUnknown() && !parameter.symbol().type().isUnknown()) { + ascribe(inferred, parameter.symbol().type()); + } + })); + deferred.add(() -> unbindUntypedParameters(tree)); + for (VariableTree parameter : parameters) { + if (parameter.symbol().owner() instanceof JMethodSymbol method) { + method.lambda(true); + tree.setSymbol(method); + break; + } + } + return tree; + } + + /** The compiler leaves the receivers of a lambda without a target unresolved: its inferred parameters are not bound where they qualify a member. */ + private void unbindUntypedParameters(LambdaExpressionTreeImpl lambda) { + if (naming || !lambda.symbolType().isUnknown()) { + return; + } + Set untyped = new HashSet<>(); + for (VariableTree parameter : lambda.parameters()) { + if (parameter.type() instanceof InferedTypeTree && parameter.symbol().type().isUnknown()) { + untyped.add(parameter.symbol()); + } + } + if (untyped.isEmpty()) { + return; + } + lambda.body().accept(new BaseTreeVisitor() { + @Override + public void visitMemberSelectExpression(MemberSelectExpressionTree select) { + if (select.expression() instanceof IdentifierTreeImpl use && untyped.contains(use.symbol())) { + use.symbol().usages().remove(use); + bind(use, Symbol.UNKNOWN_SYMBOL); + } + super.visitMemberSelectExpression(select); + } + }); + } + + private MethodReferenceTreeImpl methodReference(Node node) { + ExpressionTree qualifier = expression(requiredField(node, "type", node.children().get(0))); + Node nameNode = field(node, "name"); + if (nameNode == null) { + List children = node.children(); + Node last = children.isEmpty() ? null : children.get(children.size() - 1); + nameNode = last != null && "new".equals(last.text()) ? last : lastOf(node, "identifier"); + } + IdentifierTreeImpl name = identifier(nameNode == null ? node : nameNode); + bindUse(name, nameNode == null ? node : nameNode, true); + MethodReferenceTreeImpl tree = new MethodReferenceTreeImpl(qualifier, token(required(node, "::"))); + Node typeArguments = firstOf(node, "type_arguments"); + tree.complete(typeArguments == null ? null : typeArguments(typeArguments), name); + ascribe(tree, Type.UNKNOWN); + return tree; + } + + private TypeTree type(Node node) { + return switch (node.k()) { + case "integral_type", "floating_point_type", "boolean_type", "void_type" -> primitive(node); + case "generic_type" -> generic(node); + case "array_type" -> arrayType(type(requiredField(node, "element", firstType(node))), field(node, "dimensions")); + case "scoped_identifier", "scoped_type_identifier", "field_access" -> memberSelect(node); + case "wildcard" -> wildcard(node); + case "annotated_type" -> annotatedType(node); + case "type_identifier" -> "var".equals(node.text()) ? new VarTypeTreeImpl(token(node)) : (TypeTree) primary(node); + default -> { + ExpressionTree expression = "identifier".equals(node.k()) || "type_identifier".equals(node.k()) ? primary(node) : expression(node); + yield expression instanceof TypeTree typeTree ? typeTree : new VarTypeTreeImpl(synthetic("var")); + } + }; + } + + private TypeTree annotatedType(Node node) { + return annotate(type(firstType(node)), node); + } + + private TypeTree annotate(TypeTree type, Node node) { + List annotations = node.children().stream().filter(SemSitterTranslator::isAnnotation).map(this::annotation).toList(); + TypeTree target = type; + while (true) { + if (target instanceof ParameterizedTypeTree parameterized) { + target = parameterized.type(); + } else if (target instanceof MemberSelectExpressionTree select && select.expression() instanceof TypeTree outer && !(target instanceof ArrayTypeTree)) { + target = outer; + } else { + break; + } + } + if (!annotations.isEmpty() && target instanceof JavaTree.AnnotatedTypeTree annotated) { + annotated.complete(annotations); + } + return type; + } + + private JavaTree.PrimitiveTypeTreeImpl primitive(Node node) { + Node keyword = firstTokenChild(node); + String text = keyword == null ? node.text() : keyword.text(); + if (text.isEmpty()) { + text = node.k().replace("_type", ""); + } + JavaTree.PrimitiveTypeTreeImpl tree = new JavaTree.PrimitiveTypeTreeImpl(keyword == null ? token(node) : token(keyword)); + tree.complete(List.of()); + ascribe(tree, sema.getClassType(text)); + return tree; + } + + private JavaTree.ParameterizedTypeTreeImpl generic(Node node) { + TypeTree raw = type(firstType(node)); + Node arguments = field(node, "type_arguments"); + if (arguments == null) { + arguments = childKind(node, "type_arguments"); + } + JavaTree.ParameterizedTypeTreeImpl tree = new JavaTree.ParameterizedTypeTreeImpl(raw, arguments == null ? new TypeArgumentListTreeImpl(synthetic("<"), synthetic(">")) : typeArguments(arguments)); + List args = new ArrayList<>(); + for (TypeTree argument : tree.typeArguments()) { + if (argument instanceof WildcardTree wildcard) { + Type wildcardType = wildcardType(wildcard); + ascribe(argument, wildcardType); + args.add(wildcardType); + } else { + args.add(argument.symbolType()); + } + } + if (raw.symbolType() instanceof JType) { + List typeArguments = new ArrayList<>(); + for (Type argument : args) { + typeArguments.add(argument instanceof JType jType ? jType : JType.unknown(sema)); + } + JType parameterized = JType.named(sema, raw.symbolType().erasure().fullyQualifiedName(), typeArguments); + ascribe(tree, parameterized); + if (raw instanceof AbstractTypedTree typed) { + ascribe(typed, parameterized); + } + if (raw instanceof IdentifierTreeImpl identifier) { + bind(identifier, parameterized.symbol()); + } + } + return tree; + } + + private TypeTree arrayType(TypeTree element, @Nullable Node dimensions) { + if (dimensions == null) { + return element; + } + TypeTree current = element; + List annotations = new ArrayList<>(); + List children = dimensions.children(); + for (int i = 0; i < children.size(); i++) { + if ("[".equals(children.get(i).text())) { + InternalSyntaxToken close = i + 1 < children.size() ? token(children.get(i + 1)) : synthetic("]"); + JType component = current.symbolType() instanceof JType jType ? jType : JType.unknown(sema); + current = new JavaTree.ArrayTypeTreeImpl(current, annotations, token(children.get(i)), close); + annotations = new ArrayList<>(); + ascribe((AbstractTypedTree) current, JType.array(sema, component)); + } else if (isAnnotation(children.get(i))) { + annotations.add(annotation(children.get(i))); + } + } + return current; + } + + private Type wildcardType(WildcardTree wildcard) { + if (wildcard.is(Tree.Kind.SUPER_WILDCARD) && wildcard.bound() != null && wildcard.bound().symbolType() instanceof JType lower) { + return JType.superWildcard(sema, lower); + } + Type upper = wildcard.is(Tree.Kind.EXTENDS_WILDCARD) && wildcard.bound() != null ? wildcard.bound().symbolType() : sema.getClassType("java.lang.Object"); + return upper instanceof JType bound ? JType.wildcard(sema, bound) : Type.UNKNOWN; + } + + private JavaTree.WildcardTreeImpl wildcard(Node node) { + Node bound = firstType(node); + List annotations = node.children().stream().filter(SemSitterTranslator::isAnnotation).map(this::annotation).toList(); + if (bound == null || same(bound, keyword(node, "?"))) { + JavaTree.WildcardTreeImpl tree = new JavaTree.WildcardTreeImpl(token(required(node, "?"))); + tree.complete(annotations); + return tree; + } + boolean upper = keyword(node, "extends") != null; + JavaTree.WildcardTreeImpl tree = new JavaTree.WildcardTreeImpl( + upper ? Tree.Kind.EXTENDS_WILDCARD : Tree.Kind.SUPER_WILDCARD, + token(required(node, upper ? "extends" : "super")), + type(bound)).complete(token(required(node, "?"))); + tree.complete(annotations); + return tree; + } + + private TypeArgumentListTreeImpl typeArguments(Node node) { + TypeArgumentListTreeImpl list = new TypeArgumentListTreeImpl(token(required(node, "<")), closingAngle(node)); + for (Node child : node.children()) { + if ("<".equals(child.text()) || ">".equals(child.text()) || ">>".equals(child.text()) || ">>>".equals(child.text())) { + continue; + } + if (",".equals(child.text())) { + list.separators().add(token(child)); + } else { + list.add(type(child)); + } + } + return list; + } + + private TypeParameterListTreeImpl typeParameters(Node node) { + TypeParameterListTreeImpl list = new TypeParameterListTreeImpl(token(required(node, "<")), closingAngle(node)); + for (Node child : node.children()) { + if ("<".equals(child.text()) || child.text().startsWith(">")) { + continue; + } + if (",".equals(child.text())) { + list.separators().add(token(child)); + } else if ("type_parameter".equals(child.k())) { + list.add(typeParameter(child)); + } + } + return list; + } + + private TypeParameterTree typeParameter(Node node) { + Node nameNode = firstOf(node, "type_identifier", "identifier"); + IdentifierTreeImpl name = identifier(nameNode); + bindUse(name, nameNode); + Node bound = childKind(node, "type_bound"); + TypeParameterTreeImpl tree; + if (bound == null) { + tree = new TypeParameterTreeImpl(name); + } else { + tree = new TypeParameterTreeImpl(name, token(required(bound, "extends")), separatedTypes(bound)); + } + if (name.symbol().isUnknown()) { + bindDeclaration(tree, nameNode, name); + } + if (name.symbol() instanceof Symbol.TypeSymbol typeSymbol) { + tree.setSymbol(typeSymbol); + } + if (bound != null && name.symbol() instanceof JTypeSymbol parameter && parameter.isTypeParameter()) { + parameter.boundTrees(tree.bounds()); + } + return tree; + } + + private TypeTree catchType(Node node) { + int alternatives = 0; + for (Node child : node.children()) { + if (isTypeKind(child.k())) { + alternatives++; + } + } + if (alternatives <= 1) { + return type(firstType(node)); + } + QualifiedIdentifierListTreeImpl list = QualifiedIdentifierListTreeImpl.emptyList(); + for (Node child : node.children()) { + if (isTypeKind(child.k())) { + list.add(type(child)); + } else if ("|".equals(child.text())) { + list.separators().add(token(child)); + } + } + JavaTree.UnionTypeTreeImpl union = new JavaTree.UnionTypeTreeImpl(list); + ascribe(union, leastUpperBound(list.stream().map(TypeTree::symbolType).toList())); + return union; + } + + /** The closest class every alternative of a multi-catch descends from. */ + private Type leastUpperBound(List alternatives) { + if (alternatives.stream().anyMatch(Type::isUnknown)) { + return Type.UNKNOWN; + } + Type candidate = alternatives.get(0); + while (candidate != null && !candidate.isUnknown()) { + Type current = candidate; + if (alternatives.stream().allMatch(alternative -> alternative.isSubtypeOf(current))) { + return current; + } + candidate = current.symbol().superClass(); + } + return sema.getClassType("java.lang.Object"); + } + + private QualifiedIdentifierListTreeImpl separatedTypes(Node node) { + QualifiedIdentifierListTreeImpl list = QualifiedIdentifierListTreeImpl.emptyList(); + addSeparatedTypes(list, node); + return list; + } + + private void addSeparatedTypes(QualifiedIdentifierListTreeImpl list, Node node) { + for (Node child : node.children()) { + if ("type_list".equals(child.k())) { + addSeparatedTypes(list, child); + } else if (isTypeKind(child.k())) { + list.add(type(child)); + } else if (",".equals(child.text()) || "&".equals(child.text())) { + list.separators().add(token(child)); + } + } + } + + private ArgumentListTreeImpl arguments(Node node) { + if (node == null) { + return ArgumentListTreeImpl.emptyList(); + } + ArgumentListTreeImpl list = ArgumentListTreeImpl.emptyList(); + InternalSyntaxToken open = null; + InternalSyntaxToken close = null; + for (Node child : node.children()) { + if ("(".equals(child.text())) { + open = token(child); + } else if (")".equals(child.text())) { + close = token(child); + } else if (",".equals(child.text())) { + list.separators().add(token(child)); + } else { + list.add(expression(child)); + } + } + return list.complete(open, close); + } + + private List dimensions(Node node) { + List dims = new ArrayList<>(); + List annotations = new ArrayList<>(); + ExpressionTree index = null; + InternalSyntaxToken open = null; + for (Node child : node.children()) { + if ("[".equals(child.text())) { + open = token(child); + index = null; + } else if ("]".equals(child.text()) && open != null) { + dims.add(new ArrayDimensionTreeImpl(open, index, token(child)).completeAnnotations(annotations)); + annotations = new ArrayList<>(); + open = null; + } else if (open != null) { + index = expression(child); + } else if (isAnnotation(child)) { + annotations.add(annotation(child)); + } + } + return dims; + } + + private ModifiersTreeImpl modifiers(Node node) { + Node modifiers = childKind(node, "modifiers"); + List trees = new ArrayList<>(); + if (modifiers != null) { + for (Node child : modifiers.children()) { + ModifierTree modifier = modifier(child); + if (modifier != null) { + trees.add(modifier); + } + } + } + return new ModifiersTreeImpl(trees); + } + + @Nullable + private ModifierTree modifier(Node node) { + if (isAnnotation(node)) { + return annotation(node); + } + Modifier modifier = modifierKeyword(node.text()); + return modifier == null ? null : new ModifierKeywordTreeImpl(modifier, token(node)); + } + + private AnnotationTreeImpl annotation(Node node) { + Node name = field(node, "name"); + TypeTree type = name == null ? (TypeTree) primary(firstOf(node, "identifier", "scoped_identifier", "type_identifier")) : (TypeTree) expression(name); + if (type instanceof IdentifierTreeImpl identifier && !naming) { + recoverType(identifier); + } + ArgumentListTreeImpl arguments = ArgumentListTreeImpl.emptyList(); + Node args = field(node, "arguments"); + if (args != null) { + arguments = arguments(args); + } + AnnotationTreeImpl tree = new AnnotationTreeImpl(token(required(node, "@")), type, arguments); + ascribe(tree, annotationType(type)); + if (!naming && type instanceof MemberSelectExpressionTreeImpl select && select.symbolType().isUnknown()) { + // the written qualified name is the annotation's type; the name tree itself stays unresolved + ascribe(select, JType.unknown(sema)); + } + for (ExpressionTree argument : arguments) { + if (argument instanceof AssignmentExpressionTree assignment && assignment.variable() instanceof IdentifierTreeImpl element && element.symbol().isUnknown() + && type.symbolType().isClass()) { + Symbol.MethodSymbol method = sema.declaredMethod(type.symbolType().fullyQualifiedName(), element.name(), List.of()); + if (method != null) { + bind(element, method); + ascribe(element, method.returnType().type()); + } + } + } + return tree; + } + + private List annotations(Node node) { + Node modifiers = childKind(node, "modifiers"); + List annotations = new ArrayList<>(); + for (Node child : (modifiers == null ? node : modifiers).children()) { + if (isAnnotation(child)) { + annotations.add(annotation(child)); + } + } + return annotations; + } + + private void bindDeclaration(Tree tree, @Nullable Node name, IdentifierTreeImpl identifier) { + if (name == null) { + return; + } + String id = name.decl(); + if (id == null) { + if (tree instanceof VariableTreeImpl variable && "_".equals(identifier.name())) { + bindUnnamedVariable(variable, identifier); + } + return; + } + if (id.contains("#(")) { + id = name.decls().stream().filter(extra -> !extra.contains("(")).findFirst().orElse(id); + } + Symbol symbol = sema.resolve(id); + sema.declare(id, tree); + for (String extra : name.decls()) { + if (!extra.equals(id)) { + sema.declare(extra, tree); + } + } + // The scan records no modifiers for locals and parameters. + if (tree instanceof VariableTreeImpl declared && symbol instanceof JSymbol declaredSymbol && symbol.isVariableSymbol() + && ModifiersUtils.hasModifier(declared.modifiers(), Modifier.FINAL)) { + declaredSymbol.addModifiers(FINAL_MODIFIER); + } + if (tree instanceof VariableTreeImpl variable && symbol instanceof JSymbol variableSymbol && symbol.isVariableSymbol() && variable.type() != null) { + Type declared = variable.type().symbolType(); + if (symbol.type().isUnknown() ? isKnownOrRecovered(declared) : keepsArguments(declared) && sameErasure(declared, symbol.type())) { + variableSymbol.type(declared); + } + } + if (tree instanceof MethodTreeImpl method && symbol instanceof JMethodSymbol methodSymbol && method.returnType() != null + && methodSymbol.returnType().type().isUnknown() && isKnownOrRecovered(method.returnType().symbolType())) { + methodSymbol.returnTypeSymbol(method.returnType().symbolType().symbol()); + } else if (tree instanceof MethodTreeImpl method && symbol instanceof JMethodSymbol methodSymbol && method.returnType() != null + && method.returnType().symbolType().isParameterized() && !methodSymbol.returnType().type().isParameterized() + && sameErasure(method.returnType().symbolType(), methodSymbol.returnType().type())) { + methodSymbol.returnTypeSymbol(method.returnType().symbolType().symbol()); + } + bind(identifier, symbol); + ascribe(identifier, identifierType(symbol)); + if (!scopes.isEmpty() && symbol.isVariableSymbol() && symbol.owner() != null && symbol.owner().isMethodSymbol()) { + scopes.peekFirst().put(symbol.name(), symbol); + } + if (tree instanceof ClassTreeImpl classTree && symbol instanceof Symbol.TypeSymbol typeSymbol) { + classTree.setSymbol(typeSymbol); + if (symbol instanceof JSymbol nested && ModifiersUtils.hasModifier(classTree.modifiers(), Modifier.STATIC) && !nested.isStatic()) { + nested.addModifiers(List.of("static")); + } + } else if (tree instanceof MethodTreeImpl method && symbol instanceof Symbol.MethodSymbol methodSymbol) { + method.setSymbol(methodSymbol); + if (methodSymbol instanceof JMethodSymbol declared) { + declaredParameterTypes(declared, method.parameters()); + } + } else if (tree instanceof VariableTreeImpl variable && symbol instanceof Symbol.VariableSymbol variableSymbol) { + variable.setSymbol(variableSymbol); + } + } + + /** An unnamed variable declares nothing the scan records, so it gets a local symbol of its own. */ + private void bindUnnamedVariable(VariableTreeImpl variable, IdentifierTreeImpl identifier) { + var start = identifier.identifierToken().range().start(); + JVariableSymbol symbol = new JVariableSymbol(sema, "_@" + start.line() + ":" + start.column(), "_", "local"); + Type declared = variable.type() == null ? Type.UNKNOWN : variable.type().symbolType(); + if (isKnownOrRecovered(declared)) { + symbol.type(declared); + } + sema.declare(symbol.id, variable); + variable.setSymbol(symbol); + } + + /** + * The scan records erased return types, so the type arguments of each declared return type are read from the + * syntax before any body is translated: invocations may precede the declaration they call. + */ + private void declareGenericReturns(Node node) { + if ("method_declaration".equals(node.k()) && field(node, "dimensions") == null) { + Node typeNode = field(node, "type"); + Node name = nameNode(node); + String id = name == null ? null : name.decl(); + if (typeNode != null && id != null && sema.resolve(id) instanceof JMethodSymbol method) { + Type declared = syntacticType(typeNode); + if (declared.isParameterized() && sameErasure(declared, method.returnType().type())) { + method.returnTypeSymbol(declared.symbol()); + } + } + } + for (Node child : node.children()) { + declareGenericReturns(child); + } + } + + /** The type a type node denotes, from the references the scan bound, without translating it. */ + private Type syntacticType(Node node) { + switch (node.k()) { + case "type_identifier", "scoped_type_identifier" -> { + String target = node.typeTarget(); + return target != null && sema.resolve(target) instanceof Symbol.TypeSymbol type && !type.isUnknown() ? type.type() : Type.UNKNOWN; + } + case "generic_type" -> { + Node rawNode = firstType(node); + Type raw = rawNode == null ? Type.UNKNOWN : syntacticType(rawNode); + Node arguments = childKind(node, "type_arguments"); + if (raw.isUnknown() || arguments == null) { + return raw; + } + List types = new ArrayList<>(); + for (Node argument : arguments.children()) { + if (isTypeKind(argument.k())) { + types.add(syntacticType(argument) instanceof JType type ? type : JType.unknown(sema)); + } + } + return JType.named(sema, raw.erasure().fullyQualifiedName(), types); + } + case "wildcard" -> { + Node bound = firstType(node); + if (bound == null) { + return JType.wildcard(sema, (JType) sema.getClassType("java.lang.Object")); + } + JType type = syntacticType(bound) instanceof JType known ? known : JType.unknown(sema); + return keyword(node, "super") != null ? JType.superWildcard(sema, type) : JType.wildcard(sema, type); + } + default -> { + return Type.UNKNOWN; + } + } + } + + private static boolean mentionsUnknown(Type type) { + return type.isUnknown() || (type.isParameterized() && type.typeArguments().stream().anyMatch(SemSitterTranslator::mentionsUnknown)); + } + + private static boolean isTypeVariable(Type type) { + Type base = type; + while (base.isArray()) { + base = ((Type.ArrayType) base).elementType(); + } + return base.isTypeVar(); + } + + /** Whether a declared type, or the element type of a declared array, spells type arguments. */ + private static boolean keepsArguments(Type type) { + return type.isParameterized() || (type.isArray() && keepsArguments(((Type.ArrayType) type).elementType())); + } + + private static boolean sameErasure(Type left, Type right) { + return left.erasure().fullyQualifiedName().equals(right.erasure().fullyQualifiedName()); + } + + /** The scan records erased parameter types, while the declared parameters keep their type arguments. */ + private static void declaredParameterTypes(JMethodSymbol method, List parameters) { + List erased = method.parameterTypes(); + if (erased.size() != parameters.size()) { + return; + } + List declared = new ArrayList<>(); + for (int i = 0; i < parameters.size(); i++) { + Type type = parameters.get(i).type().symbolType(); + if (type.isUnknown() || !(isTypeVariable(type) || sameErasure(type, erased.get(i)))) { + return; + } + declared.add(type); + } + method.parameterTypes(declared); + } + + private void bindImplicitClass(ClassTreeImpl tree, List members) { + JTypeSymbol implicitClass = null; + for (Tree member : members) { + if (member instanceof MethodTree method && method.symbol().owner() instanceof JTypeSymbol owner && !owner.isUnknown()) { + implicitClass = owner; + break; + } + } + if (implicitClass == null && !implicitClassName.isEmpty() && sema.resolve(implicitClassName) instanceof JTypeSymbol named) { + implicitClass = named; + } + if (implicitClass == null) { + return; + } + tree.setSymbol(implicitClass); + sema.declare(implicitClass.id, tree); + for (Tree member : members) { + if (member instanceof MethodTree method && method.symbol() instanceof JMethodSymbol symbol && (symbol.owner() == null || symbol.owner().isUnknown())) { + symbol.owner(implicitClass); + } + } + } + + private void bindType(ClassTreeImpl tree, Node node) { + String id = node.decl(); + if (id != null && sema.resolve(id) instanceof Symbol.TypeSymbol typeSymbol) { + tree.setSymbol(typeSymbol); + sema.declare(id, tree); + return; + } + for (Tree member : tree.members()) { + Symbol symbol = member instanceof MethodTree method ? method.symbol() : (member instanceof VariableTree variable ? variable.symbol() : null); + if (symbol != null && !symbol.isUnknown() && symbol.owner() instanceof Symbol.TypeSymbol owner) { + tree.setSymbol(owner); + return; + } + } + } + + private void bindUse(IdentifierTreeImpl identifier, Node node) { + bindUse(identifier, node, false); + } + + private void bindUse(IdentifierTreeImpl identifier, Node node, boolean qualified) { + String target = node.valueTarget(); + if (target == null) { + target = node.typeTarget(); + } + if (target == null) { + if (!qualified) { + Symbol local = scopedVariable(identifier.name()); + if (local != null) { + bind(identifier, local); + ascribe(identifier, identifierType(local)); + sema.use(usageId(local, local.name()), identifier); + } + } + return; + } + Symbol symbol = sema.resolve(target); + String typeTarget = node.typeTarget(); + if (symbol.isMethodSymbol() && "".equals(symbol.name()) && typeTarget != null && !typeTarget.equals(target)) { + target = typeTarget; + symbol = sema.resolve(target); + } + if (symbol.isMethodSymbol() && symbol.isUnknown()) { + symbol = Symbol.MethodSymbol.UNKNOWN_METHOD; + } + symbol = typedField(symbol); + if (!qualified && (symbol.isUnknown() || (symbol.isVariableSymbol() && !isField(symbol)))) { + Symbol local = scopedVariable(identifier.name()); + if (local != null) { + symbol = local; + } + } + bind(identifier, symbol); + ascribe(identifier, identifierType(symbol)); + sema.use(usageId(symbol, target), identifier); + } + + /** A field is not hidden by a local variable of an enclosing method: a local class declares its own members. */ + private static boolean isField(Symbol variable) { + return variable.owner() != null && variable.owner().isTypeSymbol(); + } + + @Nullable + private Symbol scopedVariable(String name) { + for (Map scope : scopes) { + Symbol found = scope.get(name); + if (found != null) { + return found; + } + } + return null; + } + + /** A field the graph typed as void keeps the type its class file declares. */ + private Symbol typedField(Symbol symbol) { + if (!(symbol instanceof JSymbol field) || !field.isVariableSymbol() || field.type() == null || !field.type().isVoid()) { + return symbol; + } + String owner = field.owner().type() != null && !field.owner().type().isUnknown() + ? field.owner().type().erasure().fullyQualifiedName() + : (field.id != null && field.id.indexOf('#') > 0 ? field.id.substring(0, field.id.indexOf('#')) : null); + if (owner == null) { + return symbol; + } + Symbol.VariableSymbol declared = sema.declaredField(JSema.erase(owner), field.name()); + if (declared != null && declared.type() != null && !declared.type().isVoid() && !declared.type().isUnknown()) { + return declared; + } + return symbol; + } + + /** Usages are stored under the symbol's own id, which can differ from the fact key that resolved it. */ + private static String usageId(Symbol symbol, String target) { + if (symbol instanceof JSymbol jSymbol && !jSymbol.isUnknown()) { + String id = jSymbol.toString(); + if (id != null && !id.equals(jSymbol.name())) { + return id; + } + } + return target; + } + + private void recordUse(Symbol symbol, IdentifierTree identifier) { + String id = usageId(symbol, ""); + if (!id.isEmpty()) { + sema.use(id, identifier); + } + } + + @Nullable + private IdentifierTreeImpl labelUse(Node node) { + Node name = firstOf(node, "identifier"); + if (name == null || "break".equals(name.text()) || "continue".equals(name.text())) { + return null; + } + IdentifierTreeImpl identifier = identifier(name); + for (JLabelSymbol label : labels) { + if (label.name().equals(identifier.name())) { + label.addUsage(identifier); + identifier.labelSymbol = label; + break; + } + } + return identifier; + } + + private Parens parens(@Nullable Node node) { + if (node == null) { + return new Parens(synthetic("("), literal(Tree.Kind.BOOLEAN_LITERAL, synthetic("true"), sema.getClassType("boolean")), synthetic(")")); + } + if (!"parenthesized_expression".equals(node.k())) { + return new Parens(synthetic("("), expression(node), synthetic(")")); + } + InternalSyntaxToken open = token(required(node, "(")); + InternalSyntaxToken close = token(required(node, ")")); + ExpressionTree expression = null; + for (Node child : node.children()) { + if (!"(".equals(child.text()) && !")".equals(child.text())) { + expression = expression(child); + } + } + return new Parens(open, expression == null ? literal(Tree.Kind.BOOLEAN_LITERAL, synthetic("true"), sema.getClassType("boolean")) : expression, close); + } + + @Nullable + private Type currentType() { + Symbol.TypeSymbol enclosing = types.isEmpty() ? null : types.peek(); + return enclosing == null ? Type.UNKNOWN : enclosing.type(); + } + + private Type arrayTypeOf(TypeTree element, int dimensions) { + Type type = element.symbolType(); + if (!(type instanceof JType jType)) { + return Type.UNKNOWN; + } + for (int i = 0; i < Math.max(dimensions, 1); i++) { + jType = JType.array(sema, jType); + } + return jType; + } + + private static Type binaryType(String operator, Type left, Type right) { + if (operator.equals("&&") || operator.equals("||") || operator.equals("==") || operator.equals("!=") + || operator.equals("<") || operator.equals(">") || operator.equals("<=") || operator.equals(">=") || operator.equals("instanceof")) { + return left instanceof JType j ? j.sema.getClassType("boolean") : Type.UNKNOWN; + } + if ("+".equals(operator) && (left.is("java.lang.String") || right.is("java.lang.String"))) { + return left instanceof JType j ? j.sema.getClassType("java.lang.String") : Type.UNKNOWN; + } + Type promoted = promotedBinaryType(operator, unboxed(left), unboxed(right)); + if (promoted != null) { + return promoted; + } + if (left.isUnknown()) { + return right; + } + return left; + } + + private static Type unboxed(Type type) { + return type.isPrimitiveWrapper() ? type.primitiveType() : type; + } + + /** The type JLS 5.6 gives an arithmetic, bitwise or shift operation, or null when an operand is not a primitive. */ + @Nullable + private static Type promotedBinaryType(String operator, Type left, Type right) { + if (!(left instanceof JType j) || !left.isPrimitive() || !right.isPrimitive()) { + return null; + } + boolean bitwise = "&".equals(operator) || "|".equals(operator) || "^".equals(operator); + if (left.is("boolean") || right.is("boolean")) { + return bitwise && left.is("boolean") && right.is("boolean") ? left : null; + } + if ("<<".equals(operator) || ">>".equals(operator) || ">>>".equals(operator)) { + return j.sema.getClassType(left.is("long") ? "long" : "int"); + } + for (String name : List.of("double", "float", "long")) { + if (left.is(name) || right.is(name)) { + return j.sema.getClassType(name); + } + } + return j.sema.getClassType("int"); + } + + private static Tree.Kind binaryKind(String operator) { + return switch (operator) { + case "+" -> Tree.Kind.PLUS; + case "-" -> Tree.Kind.MINUS; + case "*" -> Tree.Kind.MULTIPLY; + case "/" -> Tree.Kind.DIVIDE; + case "%" -> Tree.Kind.REMAINDER; + case "<<" -> Tree.Kind.LEFT_SHIFT; + case ">>" -> Tree.Kind.RIGHT_SHIFT; + case ">>>" -> Tree.Kind.UNSIGNED_RIGHT_SHIFT; + case "<" -> Tree.Kind.LESS_THAN; + case ">" -> Tree.Kind.GREATER_THAN; + case "<=" -> Tree.Kind.LESS_THAN_OR_EQUAL_TO; + case ">=" -> Tree.Kind.GREATER_THAN_OR_EQUAL_TO; + case "==" -> Tree.Kind.EQUAL_TO; + case "!=" -> Tree.Kind.NOT_EQUAL_TO; + case "&" -> Tree.Kind.AND; + case "|" -> Tree.Kind.OR; + case "^" -> Tree.Kind.XOR; + case "&&" -> Tree.Kind.CONDITIONAL_AND; + case "||" -> Tree.Kind.CONDITIONAL_OR; + default -> Tree.Kind.PLUS; + }; + } + + private static Tree.Kind assignmentKind(String operator) { + return switch (operator) { + case "+=" -> Tree.Kind.PLUS_ASSIGNMENT; + case "-=" -> Tree.Kind.MINUS_ASSIGNMENT; + case "*=" -> Tree.Kind.MULTIPLY_ASSIGNMENT; + case "/=" -> Tree.Kind.DIVIDE_ASSIGNMENT; + case "%=" -> Tree.Kind.REMAINDER_ASSIGNMENT; + case "&=" -> Tree.Kind.AND_ASSIGNMENT; + case "|=" -> Tree.Kind.OR_ASSIGNMENT; + case "^=" -> Tree.Kind.XOR_ASSIGNMENT; + case "<<=" -> Tree.Kind.LEFT_SHIFT_ASSIGNMENT; + case ">>=" -> Tree.Kind.RIGHT_SHIFT_ASSIGNMENT; + case ">>>=" -> Tree.Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT; + default -> Tree.Kind.ASSIGNMENT; + }; + } + + private static Tree.Kind unaryKind(String operator, boolean prefix) { + return switch (operator) { + case "++" -> prefix ? Tree.Kind.PREFIX_INCREMENT : Tree.Kind.POSTFIX_INCREMENT; + case "--" -> prefix ? Tree.Kind.PREFIX_DECREMENT : Tree.Kind.POSTFIX_DECREMENT; + case "-" -> Tree.Kind.UNARY_MINUS; + case "+" -> Tree.Kind.UNARY_PLUS; + case "~" -> Tree.Kind.BITWISE_COMPLEMENT; + default -> Tree.Kind.LOGICAL_COMPLEMENT; + }; + } + + @Nullable + private static Modifier modifierKeyword(String text) { + return switch (text) { + case "public" -> Modifier.PUBLIC; + case "protected" -> Modifier.PROTECTED; + case "private" -> Modifier.PRIVATE; + case "static" -> Modifier.STATIC; + case "abstract" -> Modifier.ABSTRACT; + case "final" -> Modifier.FINAL; + case "native" -> Modifier.NATIVE; + case "synchronized" -> Modifier.SYNCHRONIZED; + case "transient" -> Modifier.TRANSIENT; + case "volatile" -> Modifier.VOLATILE; + case "strictfp" -> Modifier.STRICTFP; + case "default" -> Modifier.DEFAULT; + case "sealed" -> Modifier.SEALED; + case "non-sealed" -> Modifier.NON_SEALED; + case "transitive" -> Modifier.TRANSITIVE; + default -> null; + }; + } + + private static boolean isTypeKind(String kind) { + return switch (kind) { + case "type_identifier", "identifier", "scoped_identifier", "scoped_type_identifier", "generic_type", "array_type", "integral_type", "floating_point_type", "boolean_type", "void_type", "wildcard", "annotated_type" -> true; + default -> false; + }; + } + + private static boolean isStatementKind(String kind) { + return kind.endsWith("_statement") || "block".equals(kind) || "local_variable_declaration".equals(kind) || "switch_expression".equals(kind); + } + + private static boolean isLiteral(String kind) { + return switch (kind) { + case "string_literal", "character_literal", "text_block", "decimal_integer_literal", "hex_integer_literal", "octal_integer_literal", "binary_integer_literal", "decimal_floating_point_literal", "hex_floating_point_literal" -> true; + default -> false; + }; + } + + private static boolean isComment(Node node) { + return "line_comment".equals(node.k()) || "block_comment".equals(node.k()); + } + + private SyntaxTrivia trivia(Node node) { + String text = node.text(); + if (text.startsWith("//") && text.endsWith("\r")) { + text = text.substring(0, text.length() - 1); + } + SyntaxTrivia.CommentKind kind; + if (markdownComments && text.startsWith("///")) { + kind = SyntaxTrivia.CommentKind.MARKDOWN; + } else if (text.startsWith("/**") && !"/**/".equals(text)) { + kind = SyntaxTrivia.CommentKind.JAVADOC; + } else if (text.startsWith("//")) { + kind = SyntaxTrivia.CommentKind.LINE; + } else { + kind = SyntaxTrivia.CommentKind.BLOCK; + } + return new InternalSyntaxTrivia(kind, text, node.line(), node.col()); + } + + private InternalSyntaxToken token(Node node) { + InternalSyntaxToken found = tokens.get(node.proto); + if (found != null) { + return found; + } + if ("@interface".equals(node.text())) { + return new InternalSyntaxToken(node.line(), node.col(), "@", List.of(), false); + } + if (!node.children().isEmpty()) { + for (Node child : node.children()) { + if (child.children().isEmpty() && !child.text().isEmpty() && !isComment(child)) { + return token(child); + } + } + } + String text = node.text().isEmpty() ? node.k() : node.text(); + if (text.indexOf('_') >= 0) { + text = ""; + } + return new InternalSyntaxToken(node.line(), node.col(), text, List.of(), false); + } + + private InternalSyntaxToken closingAngle(Node node) { + for (int i = node.children().size() - 1; i >= 0; i--) { + Node child = node.children().get(i); + if (">".equals(child.text()) || ">>".equals(child.text()) || ">>>".equals(child.text())) { + return new InternalSyntaxToken(child.line(), child.col() + child.text().length() - 1, ">", List.of(), false); + } + } + return synthetic(">"); + } + + private InternalSyntaxToken synthetic(String text) { + return new InternalSyntaxToken(1, 0, text, List.of(), false); + } + + @Nullable + private InternalSyntaxToken optionalToken(Node node, String text) { + Node found = keyword(node, text); + return found == null ? null : token(found); + } + + private static Type identifierType(Symbol symbol) { + return symbol instanceof Symbol.MethodSymbol method && !method.isUnknown() ? method.returnType().type() : symbol.type(); + } + + /** A resolved type, or an unresolved one that still carries its written name. */ + private static boolean isKnownOrRecovered(Type type) { + return !type.isUnknown() || !"!Unknown!".equals(type.fullyQualifiedName()); + } + + private static Type variableType(VariableTreeImpl variable) { + return variable.symbol().type().isUnknown() ? variable.type().symbolType() : variable.symbol().type(); + } + + private static void ascribe(Tree tree, @Nullable Type type) { + if (tree instanceof AbstractTypedTree typed && type != null) { + typed.setSymbolType(type); + } + } + + private static void bind(IdentifierTreeImpl identifier, @Nullable Symbol symbol) { + identifier.setSymbol(symbol == null ? Symbol.UNKNOWN_SYMBOL : symbol); + } + + private static void bindMethod(MethodInvocationTreeImpl invocation, @Nullable Symbol.MethodSymbol method) { + invocation.setMethodSymbol(method == null ? Symbol.MethodSymbol.UNKNOWN_METHOD : method); + } + + @Nullable + private static Node keyword(Node node, String text) { + for (Node child : node.children()) { + if (text.equals(child.text()) || text.equals(child.k())) { + return child; + } + } + return null; + } + + private static Node lastKeyword(Node node, String text) { + List children = node.children(); + for (int i = children.size() - 1; i >= 0; i--) { + if (text.equals(children.get(i).text())) { + return children.get(i); + } + } + return node; + } + + private static boolean same(@Nullable Node left, @Nullable Node right) { + return left != null && right != null && left.proto == right.proto; + } + + private static Node required(Node node, String text) { + Node found = keyword(node, text); + return found == null ? node : found; + } + + @Nullable + private static Node field(Node node, String name) { + for (Node child : node.children()) { + if (name.equals(child.f())) { + return child; + } + } + return null; + } + + private static Node requiredField(Node node, String name, @Nullable Node fallback) { + Node found = field(node, name); + return found != null ? found : (fallback == null ? node : fallback); + } + + @Nullable + private static Node childKind(Node node, String kind) { + for (Node child : node.children()) { + if (kind.equals(child.k())) { + return child; + } + } + return null; + } + + @Nullable + private static Node firstOf(Node node, String... kinds) { + for (Node child : node.children()) { + for (String kind : kinds) { + if (kind.equals(child.k())) { + return child; + } + } + } + return null; + } + + @Nullable + private static Node lastOf(Node node, String kind) { + Node found = null; + for (Node child : node.children()) { + if (kind.equals(child.k())) { + found = child; + } + } + return found; + } + + @Nullable + private static Node nameNode(Node node) { + Node named = field(node, "name"); + return named != null ? named : firstOf(node, "identifier", "type_identifier"); + } + + @Nullable + private static Node firstNamed(Node node) { + for (Node child : node.children()) { + if (!child.text().equals(child.k()) || child.k().contains("_")) { + if (!child.children().isEmpty() || child.k().contains("_") || "identifier".equals(child.k()) || "type_identifier".equals(child.k())) { + return child; + } + } + } + return node.children().isEmpty() ? node : node.children().get(0); + } + + @Nullable + private static boolean isAnnotation(Node node) { + return "annotation".equals(node.k()) || "marker_annotation".equals(node.k()); + } + + private static Node lastNamed(Node node) { + List children = node.children(); + for (int i = children.size() - 1; i >= 0; i--) { + Node child = children.get(i); + if (child.k().contains("_") || "identifier".equals(child.k())) { + return child; + } + } + return node; + } + + @Nullable + private static Node firstType(Node node) { + for (Node child : node.children()) { + if (isTypeKind(child.k())) { + return child; + } + } + return null; + } + + @Nullable + private static Node firstTokenChild(Node node) { + for (Node child : node.children()) { + if (child.children().isEmpty() && !child.text().isEmpty()) { + return child; + } + } + return null; + } + + private static InternalSyntaxToken firstKeyword(Node node) { + for (Node child : node.children()) { + if (child.children().isEmpty() && !child.text().isEmpty() && !",".equals(child.text())) { + return new InternalSyntaxToken(child.line(), child.col(), child.text(), List.of(), false); + } + } + return new InternalSyntaxToken(node.line(), node.col(), "implements", List.of(), false); + } + + private static void setParents(Tree node) { + if (node instanceof JavaTree javaTree && node.kind() != Tree.Kind.INFERED_TYPE && node.kind() != Tree.Kind.TOKEN) { + for (Tree child : javaTree.getChildren()) { + if (child instanceof JavaTree javaChild) { + javaChild.setParent(node); + setParents(child); + } + } + } + } + + private record Parens(InternalSyntaxToken open, ExpressionTree expr, InternalSyntaxToken close) { + } + + private static final class Node { + private final org.sonarsource.semsitter.wire.Node proto; + + private Node(org.sonarsource.semsitter.wire.Node proto) { + this.proto = proto; + } + + private String k() { + return proto.getKind(); + } + + private String f() { + return proto.getField(); + } + + private String text() { + return proto.getText(); + } + + private boolean missing() { + return proto.getMissing(); + } + + private int line() { + return proto.getStartLine(); + } + + private int col() { + return proto.getStartCol(); + } + + private int endCol() { + return proto.getEndCol(); + } + + private List children() { + List children = new ArrayList<>(); + for (Node child : allChildren()) { + if (!isComment(child)) { + children.add(child); + } + } + return children; + } + + private List allChildren() { + List children = new ArrayList<>(); + for (org.sonarsource.semsitter.wire.Node element : proto.getChildrenList()) { + if (!element.getMissing()) { + children.add(new Node(element)); + } + } + return children; + } + + @Nullable + private String decl() { + return proto.getDeclsCount() == 0 ? null : proto.getDecls(0); + } + + private List decls() { + return proto.getDeclsList(); + } + + private boolean unresolved() { + if (proto.getRefsCount() == 0) { + return "type_identifier".equals(k()); + } + for (Ref ref : proto.getRefsList()) { + if (BOUND.equals(ref.getOutcome())) { + return false; + } + } + return true; + } + + @Nullable + private String valueTarget() { + return target(true); + } + + @Nullable + private String typeTarget() { + return target(false); + } + + @Nullable + private String target(boolean value) { + String fallback = null; + for (Ref ref : proto.getRefsList()) { + if (ref.getTarget().isEmpty() || !BOUND.equals(ref.getOutcome())) { + continue; + } + String access = ref.getAccess(); + boolean isValue = "r".equals(access) || "w".equals(access) || "rw".equals(access); + if (isValue == value) { + return ref.getTarget(); + } + fallback = ref.getTarget(); + } + return value ? null : fallback; + } + } +} 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..44b432bd4bc --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/JSemaTest.java @@ -0,0 +1,127 @@ +/* + * 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 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"); + } + + 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/SemSitterParityTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParityTest.java new file mode 100644 index 00000000000..ea14273d9dd --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParityTest.java @@ -0,0 +1,249 @@ +/* + * 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.sonarsource.scanner.engine.sensor.test.fixtures.TestInputFileBuilder; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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.JavaTree; +import org.sonar.java.model.JavaVersionImpl; +import org.sonar.plugins.java.api.semantic.Symbol; +import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.MethodInvocationTree; +import org.sonar.plugins.java.api.tree.SyntaxToken; +import org.sonar.plugins.java.api.tree.Tree; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Parses the same sources with the default frontend and with a real SemSitter server, and expects the same trees and + * the same semantic information. It runs only when {@value #EXECUTABLE} names a SemSitter server executable. + */ +class SemSitterParityTest { + + private static final String EXECUTABLE = "semsitter.executable"; + + @TempDir + Path project; + + @BeforeAll + static void locateServer() { + String path = System.getProperty(EXECUTABLE); + Assumptions.assumeTrue(path != null && !path.isBlank(), EXECUTABLE + " is not set"); + } + + @Test + void class_with_fields_and_methods() throws Exception { + assertSameTree(""" + package p; + + import java.util.List; + + public class A { + private final int count = 3; + private List names; + + public int twice(int value) { + return value * 2 + count; + } + + String first() { + return names.get(0); + } + } + """); + } + + @Test + void generics_lambdas_and_streams() throws Exception { + assertSameTree(""" + import java.util.List; + import java.util.stream.Collectors; + + class A { + List lengths(List words) { + return words.stream().map(w -> w.length()).filter(n -> n > 2).collect(Collectors.toList()); + } + } + """); + } + + @Test + void lambda_result_types_the_generic_call() throws Exception { + assertSameTree(""" + import java.util.List; + import java.util.stream.Collectors; + + class A { + List lengths(List words) { + return words.stream().map(w -> w.length()).collect(Collectors.toList()); + } + } + """); + } + + @Test + void array_length_has_an_unknown_owner() throws Exception { + assertSameTree(""" + class A { + int size(int[] values) { + return values.length; + } + } + """); + } + + @Test + void enums_records_and_interfaces() throws Exception { + assertSameTree(""" + interface Shape { double area(); } + + record Circle(double radius) implements Shape { + public double area() { return Math.PI * radius * radius; } + } + + enum Color { RED, GREEN; Color next() { return values()[(ordinal() + 1) % values().length]; } } + """); + } + + @Test + void control_flow_and_exceptions() throws Exception { + assertSameTree(""" + class A { + int run(String s) { + try { + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == 'x') { + return i; + } + } + switch (s) { + case "a": return 1; + default: break; + } + } catch (IllegalStateException | IllegalArgumentException e) { + throw new RuntimeException(e); + } finally { + System.out.println("done"); + } + return -1; + } + } + """); + } + + @Test + void syntax_error_is_reported_as_a_parse_failure() throws IOException { + InputFile broken = file("Broken.java", "class Broken { int x = ; }"); + + JParseResult result = parseAll(semSitter(), broken).get(0); + + assertThatThrownBy(result::get).isInstanceOf(com.sonar.sslr.api.RecognitionException.class); + } + + private void assertSameTree(String source) throws Exception { + InputFile input = file("A.java", source); + + List expected = describe(parseAll(JDTParser.create(JParser.Mode.BATCH, new JavaVersionImpl(21), List.of(), false, true), input).get(0)); + List actual = describe(parseAll(semSitter(), input).get(0)); + + int common = Math.min(expected.size(), actual.size()); + int mismatch = 0; + while (mismatch < common && expected.get(mismatch).equals(actual.get(mismatch))) { + mismatch++; + } + assertThat(actual.subList(Math.max(0, mismatch - 2), Math.min(actual.size(), mismatch + 4))) + .as("first difference at node %d of %d", mismatch, expected.size()) + .containsExactlyElementsOf(expected.subList(Math.max(0, mismatch - 2), Math.min(expected.size(), mismatch + 4))); + assertThat(actual).hasSameSizeAs(expected); + } + + private JParser semSitter() { + return new SemSitterParser(JParser.Mode.BATCH, new JavaVersionImpl(21), List.of(), root -> SemSitterClient.start(Path.of(System.getProperty(EXECUTABLE)), root), + () -> { + throw new AssertionError("the server must start"); + }, SemSitterTranslator::translate); + } + + private static List parseAll(JParser parser, InputFile input) { + List results = new ArrayList<>(); + parser.parse(List.of(input), () -> false, new AnalysisProgress(1), (file, result) -> results.add(result)); + return results; + } + + private InputFile file(String name, String source) throws IOException { + Files.writeString(project.resolve(name), source, StandardCharsets.UTF_8); + return new TestInputFileBuilder("module", name) + .setModuleBaseDir(project) + .setCharset(StandardCharsets.UTF_8) + .setLanguage("java") + .setContents(source) + .build(); + } + + private static List describe(JParseResult result) throws Exception { + List lines = new ArrayList<>(); + describe((Tree) result.get(), lines); + return lines; + } + + private static void describe(Tree tree, List lines) { + StringBuilder line = new StringBuilder(tree.kind().name()); + SyntaxToken first = tree.firstToken(); + if (first != null) { + line.append(" @").append(first.range().start().line()).append(':').append(first.range().start().column()); + } + if (tree instanceof IdentifierTree identifier) { + line.append(" id ").append(identifier.name()).append(" : ").append(identifier.symbolType().fullyQualifiedName()).append(' ').append(symbol(identifier.symbol())); + } else if (tree instanceof MethodInvocationTree invocation) { + line.append(" call ").append(symbol(invocation.methodSymbol())).append(" : ").append(invocation.symbolType().fullyQualifiedName()); + } + lines.add(line.toString()); + JavaTree javaTree = (JavaTree) tree; + if (javaTree.isLeaf()) { + return; + } + for (Tree child : javaTree.getChildren()) { + if (child != null) { + describe(child, lines); + } + } + } + + private static String symbol(Symbol symbol) { + if (symbol.isUnknown()) { + return "unknown"; + } + String owner = symbol.owner() == null ? "" : symbol.owner().name() + "."; + String kinds = String.valueOf(symbol.isMethodSymbol()) + symbol.isVariableSymbol() + symbol.isTypeSymbol(); + return owner + symbol.name() + " " + kinds; + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java index d45c4711b0b..a5c7a8c52ec 100644 --- a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java @@ -37,7 +37,10 @@ import org.sonar.java.AnalysisProgress; import org.sonar.java.model.JParseResult; import org.sonar.java.model.JParser; +import org.sonar.java.model.JavaTree; import org.sonar.java.model.JavaVersionImpl; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Node; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -53,8 +56,6 @@ class SemSitterParserTest { private final JParser fallback = (files, canceled, progress, action) -> files.forEach(fallbackFiles::add); - private final DocumentTranslator translator = (document, types, packages, noLibraries, javaVersion) -> JParseResult.failure(new RecognitionException(1, "translated")); - @Test void every_file_is_parsed_against_one_server_started_on_the_common_directory() throws Exception { InputFile b = file("src/p/B.java"); @@ -75,7 +76,7 @@ void every_file_is_parsed_against_one_server_started_on_the_common_directory() t assertThat(server.closed).isTrue(); assertThat(results.keySet()).containsExactly("B.java", "A.java"); for (JParseResult result : results.values()) { - assertThatThrownBy(result::get).isInstanceOf(RecognitionException.class).hasMessage("translated"); + assertThat(result.get()).isInstanceOf(JavaTree.CompilationUnitTreeImpl.class); } assertThat(fallbackFiles).isEmpty(); } @@ -164,7 +165,21 @@ void file_the_server_cannot_answer_fails_alone() throws Exception { assertThatThrownBy(results.get("A.java")::get) .isInstanceOf(RecognitionException.class) .hasMessageContaining("SemSitter: unable to parse file."); - assertThatThrownBy(results.get("B.java")::get).isInstanceOf(RecognitionException.class).hasMessage("translated"); + assertThat(results.get("B.java").get()).isNotNull(); + } + + @Test + void syntax_error_is_reported_as_a_parse_error_at_its_position() { + Node problem = Node.newBuilder().setKind("ERROR").setStartLine(3).setStartCol(4).build(); + server.documents.put("A.java", Document.newBuilder().setPath("A.java").setHasError(true) + .setTree(Node.newBuilder().setKind("program").addChildren(problem)).build()); + + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server) + .parse(List.of(file("A.java")), () -> false, new AnalysisProgress(1), this::collect); + + assertThatThrownBy(results.get("A.java")::get) + .isInstanceOf(RecognitionException.class) + .hasMessage("Parse error at line 3 column 5: Syntax error"); } @Test @@ -216,7 +231,7 @@ void server_stops_when_the_callback_fails() { } private SemSitterParser parser(JParser.Mode mode, JavaVersionImpl version, List classpath, SemSitterParser.Launcher launcher) { - return new SemSitterParser(mode, version, classpath, launcher, () -> fallback, translator, project.resolve("no-jdk")); + return new SemSitterParser(mode, version, classpath, launcher, () -> fallback, SemSitterTranslator::translate, project.resolve("no-jdk")); } private void collect(InputFile file, JParseResult result) { diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterTranslatorTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterTranslatorTest.java new file mode 100644 index 00000000000..c72bd243866 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterTranslatorTest.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 org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.semantic.Symbol; + +import static org.assertj.core.api.Assertions.assertThat; + +class SemSitterTranslatorTest { + + @Test + void an_unresolved_method_is_owned_by_the_unknown_type() { + JMethodSymbol method = new JMethodSymbol(new JSema(), null, "log"); + method.unknown(true); + + assertThat(method.owner()).isSameAs(Symbol.TypeSymbol.UNKNOWN_TYPE); + assertThat(((Symbol.TypeSymbol) method.owner()).memberSymbols()).isEmpty(); + } +} 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; }