diff --git a/src/main/java/com/ibm/cldk/CodeAnalyzer.java b/src/main/java/com/ibm/cldk/CodeAnalyzer.java index 698160fd..4ad0166d 100644 --- a/src/main/java/com/ibm/cldk/CodeAnalyzer.java +++ b/src/main/java/com/ibm/cldk/CodeAnalyzer.java @@ -516,6 +516,19 @@ private void analyzeV2() throws Exception { modules = L1Extractor.extractAllForApplication( Paths.get(input), applicationId, dependencyDir, cached, analysisLevel, graphFieldDepth, l3Engine, entrypointReport); + // One qualified name in several files (vendored copies across source roots, #269). The + // output keeps every copy, so this is not a degradation and does not fail --strict; but a + // consumer that keys types by qualified name cannot tell the copies apart, so every run + // says so on stderr, verbose or not. + Map> duplicates = L1Extractor.duplicateTypeNames(modules); + if (!duplicates.isEmpty()) { + Map.Entry> first = duplicates.entrySet().iterator().next(); + System.err.println("warning: " + duplicates.size() + " qualified type name(s) are" + + " declared in more than one file (e.g. " + first.getKey() + " in " + + String.join(", ", first.getValue()) + "). Each copy is kept; a reference" + + " binds to the copy in its own source root when there is one. A consumer" + + " that keys types by qualified name cannot tell the copies apart."); + } // The WALA L3 engine needs the RTA build; --no-rta suppresses it, so a level-3 wala run with // --no-rta would silently carry no overlays. Warn rather than degrade without a signal. if (analysisLevel >= 3 && noRta && "wala".equalsIgnoreCase(l3Engine)) { diff --git a/src/main/java/com/ibm/cldk/neo4j/V2GraphProjector.java b/src/main/java/com/ibm/cldk/neo4j/V2GraphProjector.java index 22094a72..6e14e33a 100644 --- a/src/main/java/com/ibm/cldk/neo4j/V2GraphProjector.java +++ b/src/main/java/com/ibm/cldk/neo4j/V2GraphProjector.java @@ -15,6 +15,7 @@ import com.ibm.cldk.neo4j.GraphRows.NodeRef; import com.ibm.cldk.schema.Analysis; import com.ibm.cldk.schema.CanId; +import com.ibm.cldk.schema.FqnIndex; import com.ibm.cldk.schema.JApplication; import com.ibm.cldk.schema.JArtifact; import com.ibm.cldk.schema.JBodyNode; @@ -117,8 +118,10 @@ public static GraphRows project(Analysis analysis, String appName) { // First pass: an in-project index from a type's qualified (dotted) name to its node id and // owning module id, for resolving extends/implements/import spellings to emitted nodes. - Map typeIdByFqn = new LinkedHashMap<>(); - Map moduleIdByFqn = new LinkedHashMap<>(); + // A name may be declared by several types (vendored copies across source roots, #269): each + // reference resolves to the copy nearest the referring module. + FqnIndex typeIdByFqn = new FqnIndex(); + FqnIndex moduleIdByFqn = new FqnIndex(); for (Map.Entry m : symbolTable.entrySet()) { indexTypes(m.getValue(), m.getValue().getTypes(), null, typeIdByFqn, moduleIdByFqn); } @@ -204,7 +207,7 @@ public static GraphRows project(Analysis analysis, String appName) { // ------------------------------------------------------------------------------------------ private static void indexTypes(JModule module, Map types, String qualifierFqn, - Map typeIdByFqn, Map moduleIdByFqn) { + FqnIndex typeIdByFqn, FqnIndex moduleIdByFqn) { for (Map.Entry e : types.entrySet()) { String fqn = qualifierFqn != null ? qualifierFqn + "." + e.getKey() @@ -221,7 +224,7 @@ private static void indexTypes(JModule module, Map types, String } private static void projectType(RowBuilder b, NodeRef parent, String containmentRel, String name, - JType type, JModule module, String fileKey, Map typeIdByFqn) { + JType type, JModule module, String fileKey, FqnIndex typeIdByFqn) { List labels = type.isEntrypointClass() ? Arrays.asList("JSymbol", "JType", "JEntrypoint") : SYMBOL_TYPE; @@ -245,13 +248,13 @@ private static void projectType(RowBuilder b, NodeRef parent, String containment String pkg = module.getPackageName(); for (String base : type.getBaseTypes()) { - String target = resolveType(base, pkg, typeIdByFqn); + String target = resolveType(base, pkg, typeIdByFqn, module.getId()); if (target != null) { b.edgeToSymbol("J_EXTENDS", ref, target); } } for (String iface : type.getInterfaces()) { - String target = resolveType(iface, pkg, typeIdByFqn); + String target = resolveType(iface, pkg, typeIdByFqn, module.getId()); if (target != null) { b.edgeToSymbol("J_IMPLEMENTS", ref, target); } @@ -320,7 +323,7 @@ private static void projectField(RowBuilder b, NodeRef owner, JField field, Stri // ------------------------------------------------------------------------------------------ private static void projectCallable(RowBuilder b, NodeRef owner, String signature, JCallable c, - JModule module, String fileKey, Map typeIdByFqn) { + JModule module, String fileKey, FqnIndex typeIdByFqn) { List labels = c.isEntrypoint() ? Arrays.asList("JSymbol", "JCallable", "JEntrypoint") : SYMBOL_CALLABLE; @@ -608,7 +611,7 @@ private static boolean isLockArtifact(String path) { // ------------------------------------------------------------------------------------------ private static void projectImports(RowBuilder b, NodeRef mod, JModule module, - Map typeIdByFqn, Map moduleIdByFqn) { + FqnIndex typeIdByFqn, FqnIndex moduleIdByFqn) { // Aggregate per target so one edge carries every spelling importing it. Map> byTarget = new LinkedHashMap<>(); Map refByTarget = new LinkedHashMap<>(); @@ -617,7 +620,7 @@ private static void projectImports(RowBuilder b, NodeRef mod, JModule module, if (path == null || path.isEmpty()) { continue; } - String targetModule = imp.isWildcard() ? null : moduleIdByFqn.get(path); + String targetModule = imp.isWildcard() ? null : moduleIdByFqn.nearest(path, module.getId()); String targetKey; NodeRef target; if (targetModule != null) { @@ -680,16 +683,16 @@ private static void annotate(RowBuilder b, NodeRef owner, List decor * in-project type id, trying the spelling as-is then package-qualified. Unresolved spellings * stay as the string fallback on the node's {@code base_types}/{@code interfaces} props. */ - private static String resolveType(String spelling, String pkg, Map typeIdByFqn) { + private static String resolveType(String spelling, String pkg, FqnIndex typeIdByFqn, String near) { if (spelling == null || spelling.isEmpty()) { return null; } - String direct = typeIdByFqn.get(spelling); + String direct = typeIdByFqn.nearest(spelling, near); if (direct != null) { return direct; } if (pkg != null && !pkg.isEmpty()) { - return typeIdByFqn.get(pkg + "." + spelling); + return typeIdByFqn.nearest(pkg + "." + spelling, near); } return null; } diff --git a/src/main/java/com/ibm/cldk/schema/FqnIndex.java b/src/main/java/com/ibm/cldk/schema/FqnIndex.java new file mode 100644 index 00000000..dd4395f1 --- /dev/null +++ b/src/main/java/com/ibm/cldk/schema/FqnIndex.java @@ -0,0 +1,72 @@ +package com.ibm.cldk.schema; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Node ids by qualified (or binary) type name, where one name may be declared by several types. + * + *

Vendored copies of one library across source roots declare the same name in several files + * (#269). A reference to such a name binds to the copy nearest the referring node: the one whose id + * shares the most leading {@code /}-separated segments with it, which puts the referrer's own source + * root first. Ties, and lookups with no referrer, fall back to id order, so the choice is always + * deterministic rather than an artifact of insertion order. + */ +public final class FqnIndex { + private final Map> ids = new HashMap<>(); + private boolean sorted = true; + + /** Record that {@code id} declares {@code name}. */ + public void put(String name, String id) { + ids.computeIfAbsent(name, k -> new ArrayList<>()).add(id); + sorted = false; + } + + public boolean containsKey(String name) { + return ids.containsKey(name); + } + + /** Every id declaring {@code name}, nearest {@code near} first ({@code near} may be null); read-only. */ + public List ordered(String name, String near) { + sortOnce(); + List found = ids.get(name); + if (found == null) { + return List.of(); + } + if (near == null || found.size() < 2) { + return Collections.unmodifiableList(found); + } + List ordered = new ArrayList<>(found); + ordered.sort(Comparator.comparingInt((String id) -> -commonSegments(id, near)) + .thenComparing(Comparator.naturalOrder())); + return ordered; + } + + /** The id declaring {@code name} nearest {@code near}, or null when none does. */ + public String nearest(String name, String near) { + List ordered = ordered(name, near); + return ordered.isEmpty() ? null : ordered.get(0); + } + + private void sortOnce() { + if (!sorted) { + ids.values().forEach(Collections::sort); + sorted = true; + } + } + + /** How many leading {@code /}-separated segments two ids (or two relative paths) share. */ + public static int commonSegments(String a, String b) { + String[] x = a.split("/"); + String[] y = b.split("/"); + int n = 0; + while (n < x.length && n < y.length && x[n].equals(y[n])) { + n++; + } + return n; + } +} diff --git a/src/main/java/com/ibm/cldk/syntactic_analysis/L1Extractor.java b/src/main/java/com/ibm/cldk/syntactic_analysis/L1Extractor.java index 975d901c..e1ddb03c 100644 --- a/src/main/java/com/ibm/cldk/syntactic_analysis/L1Extractor.java +++ b/src/main/java/com/ibm/cldk/syntactic_analysis/L1Extractor.java @@ -4,6 +4,9 @@ import com.github.javaparser.ParseResult; import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.resolution.TypeSolver; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; +import com.github.javaparser.resolution.model.SymbolReference; import com.github.javaparser.symbolsolver.JavaSymbolSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; @@ -13,6 +16,7 @@ import com.github.javaparser.utils.ProjectRoot; import com.github.javaparser.utils.SourceRoot; import com.ibm.cldk.schema.CanId; +import com.ibm.cldk.schema.FqnIndex; import com.ibm.cldk.schema.JEntrypointReport; import com.ibm.cldk.schema.JModule; import com.ibm.cldk.utils.Log; @@ -142,16 +146,29 @@ public static Map extractAllForApplication( sourceRoots.add(sourceRoot); } } + // ProjectRoot lists roots in hash order of their absolute paths, so the order changed with + // the checkout location. Sorted on the /-separated relative path, the same on every OS and + // the order L2 breaks ties in, since a node id spells that path (#269). + Path keyRoot = projectRoot; + sourceRoots.sort(java.util.Comparator.comparing(sr -> fileKey(keyRoot, sr.getRoot()))); + List rootKeys = new ArrayList<>(); + for (SourceRoot sourceRoot : sourceRoots) { + rootKeys.add(fileKey(keyRoot, sourceRoot.getRoot())); + } - ParserConfiguration config = parserConfiguration() - .setSymbolResolver(new JavaSymbolSolver(typeSolver(sourceRoots, dependencyDir, discovery))); + // One resolution order per source root, its own root first (#269): a type declared in + // several roots (vendored copies of a shared library) then binds each caller to its own + // copy, not to whichever root a single shared solver happened to try first. + Solvers solvers = typeSolvers(sourceRoots, rootKeys, dependencyDir, discovery); // Collect into a sorted map first: directory listings are not ordered, and output must not // depend on traversal order. Map modules = new TreeMap<>(); - JavaParser parser = new JavaParser(config); int reused = 0; - for (SourceRoot sourceRoot : sourceRoots) { + for (int r = 0; r < sourceRoots.size(); r++) { + SourceRoot sourceRoot = sourceRoots.get(r); + JavaParser parser = new JavaParser(parserConfiguration() + .setSymbolResolver(new JavaSymbolSolver(solvers.orderedFor(r)))); for (Path path : javaFilesUnder(sourceRoot.getRoot())) { String fileKey = fileKey(projectRoot, path); // Read the file's own text rather than printing the AST: `span.bytes` must index the @@ -221,19 +238,96 @@ private static ParserConfiguration parserConfiguration() { .setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_21); } - /** JDK + project sources + dependency jars, in that resolution order. */ - private static CombinedTypeSolver typeSolver( - List sourceRoots, Path dependencyDir, ParserConfiguration config) { - CombinedTypeSolver solver = new CombinedTypeSolver(); - // JRE types only. A classpath-wide ReflectionTypeSolver would resolve the *analyzer's* own - // dependencies (WALA, Guava, JavaParser, ...) as if the analysed project depended on them, - // silently inventing qualified names. Project types come from the source roots below, and - // library types from the dependency jars. - solver.add(new ReflectionTypeSolver()); + /** + * The type solvers of an application: one per source root and one per dependency jar, each + * built once, and arranged per source root by {@link #orderedFor}. + */ + private static final class Solvers { + final List roots; + final List rootKeys; + final List jars; + + Solvers(List roots, List rootKeys, List jars) { + this.roots = roots; + this.rootKeys = rootKeys; + this.jars = jars; + // A solver's parent is what it resolves the insides of a found declaration through + // (its supertypes, its members' types). That is the application-wide order; the + // per-root orders below decide only which copy a caller's reference finds (#269). So a + // chained call through a found copy (copy.helper().tag()) resolves helper()'s return type + // application-wide, a known limitation: lifting it needs a parse cache per source root. + CombinedTypeSolver application = new CombinedTypeSolver(); + application.add(new ReflectionTypeSolver()); + roots.forEach(application::add); + jars.forEach(application::add); + } + + /** + * JDK, then source root {@code own}, then the other roots nearest it first (the most leading + * path segments in common, so a sibling of the same service before another service), ties + * in path order, then the jars. That is the rule L2 binds a call by ({@link FqnIndex}), so + * the two levels pick the same copy when the caller's own root has none (#269). + */ + CombinedTypeSolver orderedFor(int own) { + CombinedTypeSolver solver = new CombinedTypeSolver(); + // JRE types only. A classpath-wide ReflectionTypeSolver would resolve the *analyzer's* + // own dependencies (WALA, Guava, JavaParser, ...) as if the analysed project depended + // on them, silently inventing qualified names. + solver.add(new ReflectionTypeSolver()); + solver.add(new SharedTypeSolver(roots.get(own))); + List others = new ArrayList<>(); + for (int r = 0; r < roots.size(); r++) { + if (r != own) { + others.add(r); + } + } + String ownKey = rootKeys.get(own); + // Stable sort over path order: equal nearness keeps the roots in path order. + others.sort(java.util.Comparator.comparingInt( + (Integer r) -> -FqnIndex.commonSegments(rootKeys.get(r), ownKey))); + others.forEach(r -> solver.add(new SharedTypeSolver(roots.get(r)))); + jars.forEach(jar -> solver.add(new SharedTypeSolver(jar))); + return solver; + } + } + + /** + * A solver that answers for a shared one. A {@link TypeSolver} takes a single parent, so the one + * solver per source root (and its parse cache) can sit in every root's order only behind one of + * these: the wrapper takes the order as its parent, the shared solver keeps its own. + */ + private static final class SharedTypeSolver implements TypeSolver { + private final TypeSolver delegate; + private TypeSolver parent; + + SharedTypeSolver(TypeSolver delegate) { + this.delegate = delegate; + } + + @Override + public TypeSolver getParent() { + return parent; + } + + @Override + public void setParent(TypeSolver parent) { + this.parent = parent; + } + + @Override + public SymbolReference tryToSolveType(String name) { + return delegate.tryToSolveType(name); + } + } + + /** Project sources and dependency jars, each solver built once (see {@link Solvers}). */ + private static Solvers typeSolvers(List sourceRoots, List rootKeys, + Path dependencyDir, ParserConfiguration config) { + List roots = new ArrayList<>(); for (SourceRoot sourceRoot : sourceRoots) { - solver.add(new JavaParserTypeSolver(sourceRoot.getRoot(), config)); + roots.add(new JavaParserTypeSolver(sourceRoot.getRoot(), config)); } - int jars = 0; + List jarSolvers = new ArrayList<>(); if (dependencyDir != null && Files.isDirectory(dependencyDir)) { try (Stream entries = Files.walk(dependencyDir)) { List jarFiles = entries @@ -242,8 +336,7 @@ private static CombinedTypeSolver typeSolver( .collect(java.util.stream.Collectors.toList()); for (Path jar : jarFiles) { try { - solver.add(new JarTypeSolver(jar)); - jars++; + jarSolvers.add(new JarTypeSolver(jar)); } catch (IOException e) { // A corrupt or unreadable jar degrades resolution; it must not fail analysis. Log.debug("Skipping unreadable dependency jar " + jar + ": " + e.getMessage()); @@ -253,8 +346,28 @@ private static CombinedTypeSolver typeSolver( Log.warn("Could not scan dependency directory " + dependencyDir + ": " + e.getMessage()); } } - Log.debug("Type solver: " + sourceRoots.size() + " source root(s), " + jars + " dependency jar(s)"); - return solver; + Log.debug("Type solver: " + sourceRoots.size() + " source root(s), " + jarSolvers.size() + + " dependency jar(s)"); + return new Solvers(roots, rootKeys, jarSolvers); + } + + /** + * Top-level qualified type names declared in more than one file, each with its files in sorted + * order (#269). Two source roots that vendor one library are the common case; each caller then + * resolves against its own root's copy first, but the name itself is ambiguous to a consumer. + */ + public static Map> duplicateTypeNames(Map modules) { + Map> files = new TreeMap<>(); + for (Map.Entry e : modules.entrySet()) { + String pkg = e.getValue().getPackageName(); + for (String simple : e.getValue().getTypes().keySet()) { + String fqn = pkg == null || pkg.isEmpty() ? simple : pkg + "." + simple; + files.computeIfAbsent(fqn, k -> new ArrayList<>()).add(e.getKey()); + } + } + files.values().removeIf(f -> f.size() < 2); + files.values().forEach(java.util.Collections::sort); + return files; } /** The {@code symbol_table} key: path relative to the key root, always {@code /}-separated. */ diff --git a/src/main/java/com/ibm/cldk/syntactic_analysis/L2CallGraph.java b/src/main/java/com/ibm/cldk/syntactic_analysis/L2CallGraph.java index 135535c0..aa38c127 100644 --- a/src/main/java/com/ibm/cldk/syntactic_analysis/L2CallGraph.java +++ b/src/main/java/com/ibm/cldk/syntactic_analysis/L2CallGraph.java @@ -1,6 +1,7 @@ package com.ibm.cldk.syntactic_analysis; import com.ibm.cldk.schema.CanId; +import com.ibm.cldk.schema.FqnIndex; import com.ibm.cldk.schema.JBodyNode; import com.ibm.cldk.schema.JCallEdge; import com.ibm.cldk.schema.JCallable; @@ -139,7 +140,9 @@ public static Result build( public static Result buildForApplication(String appName, Map modules, List rtaEdges, boolean includeExternal) { // The type index (named types only) and the set of every callable id in the tree. The latter // turns no-dangling, the signature-miss case, and the RTA drop rules into O(1) membership checks. - Map typeIdByBinaryName = new HashMap<>(); + // A binary name maps to every type declaring it: vendored copies of one library across source + // roots declare one name in several files (#269), and a caller binds to the nearest copy. + FqnIndex typeIdByBinaryName = new FqnIndex(); Set callableIds = new HashSet<>(); for (JModule module : modules.values()) { String pkg = module.getPackageName(); @@ -187,7 +190,7 @@ private static String binaryName(String packageName, String simpleName) { * bodies are skipped — javac numbers those per outer class while L1 numbers them per scope, so they * have no binary name that would join; they are reached only by node identity, not this index. */ - private static void indexNamedTypes(String binaryName, JType type, Map index) { + private static void indexNamedTypes(String binaryName, JType type, FqnIndex index) { index.put(binaryName, type.getId()); for (Map.Entry entry : type.getTypes().entrySet()) { if (!entry.getKey().startsWith("$")) { @@ -213,7 +216,7 @@ private static void collectCallableIds(JType type, Set ids) { private static void backfillTree( JType type, String appName, - Map index, + FqnIndex index, Set callableIds, Map> weightBySrcDst, Map externalSymbols, @@ -230,7 +233,7 @@ private static void backfillTree( private static void backfillCallable( JCallable callable, String appName, - Map index, + FqnIndex index, Set callableIds, Map> weightBySrcDst, Map externalSymbols, @@ -240,7 +243,7 @@ private static void backfillCallable( if (!"call".equals(node.getKind())) { continue; } - String dst = resolveCallee(node, appName, index, callableIds, externalSymbols, includeExternal); + String dst = resolveCallee(node, src, appName, index, callableIds, externalSymbols, includeExternal); if (dst == null) { // Signature-miss, unresolved, or (with external off) a dropped external target. Clear any // prior value so build() is idempotent on a reused tree and no stale callee dangles when @@ -259,8 +262,9 @@ private static void backfillCallable( */ private static String resolveCallee( JBodyNode node, + String caller, String appName, - Map index, + FqnIndex index, Set callableIds, Map externalSymbols, boolean includeExternal) { @@ -278,7 +282,7 @@ private static String resolveCallee( return null; // resolved the type but not a signature to compose } if (index.containsKey(hint)) { - return inProjectId(hint, signature, index, callableIds); // in-project hit (case 2) or signature-miss + return inProjectId(hint, signature, index, callableIds, caller); // in-project hit (case 2) or signature-miss } if (!includeExternal) { return null; // case 4 gated off: match v1's application-only graph @@ -296,7 +300,7 @@ private static String resolveCallee( private static void joinRtaEdge( RtaEndpoint edge, String appName, - Map index, + FqnIndex index, Set callableIds, Map> rtaWeights, Map externalSymbols, @@ -304,13 +308,16 @@ private static void joinRtaEdge( if (!edge.srcAppClass) { return; // a library caller has no in-project node to attribute the edge to } - String src = inProjectId(edge.srcType, edge.srcSignature, index, callableIds); + // WALA loads one class per name, so an RTA source has no caller to be near: it takes the + // first copy in id order that declares the signature, and its destination is then chosen + // near that source. + String src = inProjectId(edge.srcType, edge.srcSignature, index, callableIds, null); if (src == null) { return; // an in-project synthetic (bridge, access$, lambda$) or an identity-join failure } String dst; if (edge.dstAppClass) { - dst = inProjectId(edge.dstType, edge.dstSignature, index, callableIds); + dst = inProjectId(edge.dstType, edge.dstSignature, index, callableIds, src); if (dst == null) { return; // in-project but absent from the tree — drop rather than fabricate } @@ -325,15 +332,21 @@ private static void joinRtaEdge( rtaWeights.computeIfAbsent(src, k -> new TreeMap<>()).merge(dst, 1, Integer::sum); } - /** The in-project callable id for a binary type + signature, or {@code null} if absent from the tree. */ - private static String inProjectId( - String binaryType, String signature, Map index, Set callableIds) { - String typeId = index.get(binaryType); - if (typeId == null) { - return null; + /** + * The in-project callable id for a binary type + signature, or {@code null} if absent from the tree. + * When several types declare the name (#269), the one nearest {@code near} that declares the + * signature wins: the most leading id segments in common (its own source root first), then id + * order. With no {@code near}, id order alone, so the choice is always deterministic. + */ + private static String inProjectId(String binaryType, String signature, FqnIndex index, + Set callableIds, String near) { + for (String typeId : index.ordered(binaryType, near)) { + String composed = CanId.childId(typeId, signature); + if (callableIds.contains(composed)) { + return composed; + } } - String composed = CanId.childId(typeId, signature); - return callableIds.contains(composed) ? composed : null; + return null; } private static JExternalSymbol externalSymbol(String signature, String binaryType, boolean constructor) { diff --git a/src/test/java/com/ibm/cldk/DuplicateTypeResolutionTest.java b/src/test/java/com/ibm/cldk/DuplicateTypeResolutionTest.java new file mode 100644 index 00000000..05532959 --- /dev/null +++ b/src/test/java/com/ibm/cldk/DuplicateTypeResolutionTest.java @@ -0,0 +1,321 @@ +package com.ibm.cldk; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +/** + * One qualified type name declared in several source roots (#269): vendored copies of a shared + * library across services. Each caller binds to its own copy, and the duplication is reported. The + * CLI helpers mirror {@link CodeAnalyzerV2CliTest}'s, including the static-state resets. + */ +class DuplicateTypeResolutionTest { + + private static Path project(Path root) throws IOException { + Path pkg = root.resolve("src/main/java/com/example"); + Files.createDirectories(pkg); + // size() has an in-project call (count()) and an out-of-project call (Math.max), so level-2 + // output carries an in-project edge always and an external edge only under --external-calls. + Files.writeString(pkg.resolve("Widget.java"), + "package com.example;\npublic class Widget {\n" + + " public int size() { return Math.max(count(), 0); }\n" + + " private int count() { return 1; }\n}\n", + StandardCharsets.UTF_8); + return root; + } + + private static int run(String... args) { + return new CommandLine(new CodeAnalyzer()).execute(args); + } + + /** + * The pre-existing CLI options on {@link CodeAnalyzer} are static, so a value set by one test + * would leak into the next. Reset the ones these tests touch so each case starts from defaults — + * and again afterwards, so whichever test happens to run last cannot leak {@code emit=neo4j} or a + * deliberately bad {@code --precision} into another test class that drives the same CLI. + */ + @BeforeEach + @AfterEach + void resetStaticOptions() throws Exception { + set("emit", "json"); + set("analysisLevel", 1); + set("precision", "rta"); + set("output", null); + set("input", null); + set("targetFiles", null); + set("sourceAnalysis", null); + CodeAnalyzer.projectRootPom = null; + CodeAnalyzer.artifactText = true; + CodeAnalyzer.artifactTextMaxBytes = 262144; + } + + private static void set(String field, Object value) throws Exception { + Field f = CodeAnalyzer.class.getDeclaredField(field); + f.setAccessible(true); + f.set(null, value); + } + + /** + * These tests drive the whole CLI, which runs the v1 symbol table and leaves its static + * state populated ({@code javaSymbolSolver}, the resolution caches, the declared-callables table). + * {@link SymbolTable#extractSingle} does not assign that solver field, so it behaves differently + * depending on whether something else ran first — restore the initial state so this class cannot + * change the outcome of tests that run after it. + */ + @AfterEach + void restoreSymbolTableStatics() throws Exception { + Field solver = SymbolTable.class.getDeclaredField("javaSymbolSolver"); + solver.setAccessible(true); + solver.set(null, null); + clearCollection("unresolvedTypes"); + clearCollection("unresolvedExpressions"); + SymbolTable.declaredMethodsAndConstructors.clear(); + // projectRootPom is also reset in @BeforeEach; mirror that here so the last test in this + // class does not leave a stale (possibly deleted temp-dir) path that bleeds into tests in + // other classes that call RtaCallGraph.endpoints directly (which only sets it when null). + CodeAnalyzer.projectRootPom = null; + } + + private static void clearCollection(String field) throws Exception { + Field f = SymbolTable.class.getDeclaredField(field); + f.setAccessible(true); + ((java.util.Collection) f.get(null)).clear(); + } + + /** #269's reproduction: three services, each vendoring {@code com.shared.RunStatsDataBean}. */ + private static Path vendoredServices(Path root) throws IOException { + for (String svc : new String[] {"svc-a", "svc-b", "svc-c"}) { + Path pkg = root.resolve(svc).resolve("src/main/java/com/shared"); + Files.createDirectories(pkg); + Files.writeString(pkg.resolve("RunStatsDataBean.java"), + "package com.shared;\npublic class RunStatsDataBean {\n" + + " public String origin() { return \"" + svc + "\"; }\n}\n", + StandardCharsets.UTF_8); + } + for (String svc : new String[] {"svc-a", "svc-b"}) { + String caller = "Caller" + Character.toUpperCase(svc.charAt(4)); + Files.writeString(root.resolve(svc).resolve("src/main/java/com/shared/" + caller + ".java"), + "package com.shared;\npublic class " + caller + " {\n" + + " public String go() { return new RunStatsDataBean().origin(); }\n}\n", + StandardCharsets.UTF_8); + } + return root; + } + + private static java.util.List callEdges(JsonElement node) { + java.util.List out = new java.util.ArrayList<>(); + if (node.isJsonObject()) { + for (Map.Entry e : node.getAsJsonObject().entrySet()) { + if (e.getKey().equals("call_graph") && e.getValue().isJsonArray()) { + e.getValue().getAsJsonArray().forEach(x -> out.add(x.getAsJsonObject())); + } else { + out.addAll(callEdges(e.getValue())); + } + } + } else if (node.isJsonArray()) { + node.getAsJsonArray().forEach(x -> out.addAll(callEdges(x))); + } + return out; + } + + /** A caller resolves a vendored type against its own copy, not the last source root's (#269). */ + @Test + void vendoredCopiesResolveToTheCallersOwnCopy(@TempDir Path tmp) throws Exception { + Path in = vendoredServices(tmp.resolve("app")); + Path out = tmp.resolve("out"); + assertEquals(0, run("-i", in.toString(), "-o", out.toString(), "-a", "2", "--no-rta", + "--app-name", "dt")); + java.util.List edges = callEdges(JsonParser.parseString( + Files.readString(out.resolve("analysis.json"), StandardCharsets.UTF_8))); + for (String[] want : new String[][] {{"CallerA", "svc-a/"}, {"CallerB", "svc-b/"}}) { + java.util.List targets = edges.stream() + .filter(e -> e.get("src").getAsString().contains(want[0])) + .map(e -> e.get("dst").getAsString()) + .filter(d -> d.contains("origin")) + .collect(Collectors.toList()); + assertEquals(1, targets.size(), want[0] + " -> origin(): " + targets); + assertTrue(targets.get(0).contains(want[1]), want[0] + " bound to " + targets.get(0)); + } + } + + /** Writes {@code text} at {@code root/svc/src/main/java/com/shared/name.java}. */ + private static void shared(Path root, String svc, String name, String text) throws IOException { + Path pkg = root.resolve(svc).resolve("src/main/java/com/shared"); + Files.createDirectories(pkg); + Files.writeString(pkg.resolve(name + ".java"), "package com.shared;\n" + text, + StandardCharsets.UTF_8); + } + + private static java.util.List targets(java.util.List edges, String caller, + String callee) { + return edges.stream() + .filter(e -> e.get("src").getAsString().contains(caller)) + .map(e -> e.get("dst").getAsString()) + .filter(d -> d.contains(callee)) + .collect(Collectors.toList()); + } + + private static java.util.List level2Edges(Path in, Path out) throws IOException { + assertEquals(0, run("-i", in.toString(), "-o", out.toString(), "-a", "2", "--no-rta", + "--app-name", "dt")); + return callEdges(JsonParser.parseString( + Files.readString(out.resolve("analysis.json"), StandardCharsets.UTF_8))); + } + + /** + * Copies whose signatures diverge (#269): each caller's call resolves only against its own + * copy, so the edge exists only if L1 resolved the call through the caller's own source root. + * Level 2's nearest-copy choice cannot recover a call L1 left unresolved. + */ + @Test + void divergedCopiesResolveThroughTheCallersOwnRoot(@TempDir Path tmp) throws Exception { + Path in = tmp.resolve("app"); + shared(in, "svc-a", "RunStatsDataBean", + "public class RunStatsDataBean {\n public String origin(int n) { return \"a\"; }\n}\n"); + shared(in, "svc-b", "RunStatsDataBean", + "public class RunStatsDataBean {\n public String origin(String s) { return s; }\n}\n"); + shared(in, "svc-c", "RunStatsDataBean", + "public class RunStatsDataBean {\n public String origin() { return \"c\"; }\n}\n"); + shared(in, "svc-a", "CallerA", + "public class CallerA {\n public String go() { return new RunStatsDataBean().origin(1); }\n}\n"); + shared(in, "svc-b", "CallerB", + "public class CallerB {\n public String go() { return new RunStatsDataBean().origin(\"x\"); }\n}\n"); + java.util.List edges = level2Edges(in, tmp.resolve("out")); + java.util.List a = targets(edges, "CallerA", "origin"); + java.util.List b = targets(edges, "CallerB", "origin"); + assertEquals(1, a.size(), "CallerA -> origin(int): " + a); + assertTrue(a.get(0).contains("svc-a/") && a.get(0).contains("origin(int)"), a.get(0)); + assertEquals(1, b.size(), "CallerB -> origin(String): " + b); + assertTrue(b.get(0).contains("svc-b/") && b.get(0).contains("origin(java.lang.String)"), b.get(0)); + } + + /** + * A caller whose own root has no copy falls back to the first other root in path order, wherever + * the application is checked out (#269). JavaParser lists source roots in hash order of their + * absolute paths, so without sorting, the fallback copy changed with the checkout location. The + * copies' signatures diverge, so only svc-b's copy can resolve the call. + */ + @Test + void fallbackCopyIsTheFirstRootInPathOrderWhereverCheckedOut(@TempDir Path tmp) throws Exception { + for (int i = 0; i < 8; i++) { + Path in = tmp.resolve("checkout-" + i).resolve("app"); + shared(in, "svc-b", "RunStatsDataBean", + "public class RunStatsDataBean {\n public String origin(int n) { return \"b\"; }\n}\n"); + shared(in, "svc-c", "RunStatsDataBean", + "public class RunStatsDataBean {\n public String origin(String s) { return s; }\n}\n"); + shared(in, "svc-d", "CallerD", + "public class CallerD {\n public String go() { return new RunStatsDataBean().origin(1); }\n}\n"); + java.util.List d = targets(level2Edges(in, tmp.resolve("out-" + i)), "CallerD", "origin"); + assertEquals(1, d.size(), "checkout-" + i + ": CallerD -> origin(int): " + d); + assertTrue(d.get(0).contains("svc-b/"), d.get(0)); + } + } + + private static void write(Path root, String rel, String text) throws IOException { + Path file = root.resolve(rel); + Files.createDirectories(file.getParent()); + Files.writeString(file, text, StandardCharsets.UTF_8); + } + + /** + * With no copy in the caller's own root, both levels fall back to the copy nearest it (#269): + * svc-a/vendor shares {@code svc-a} with the caller's root, lib shares nothing. L1 once fell + * back in path order (lib first) while L2 chose by nearness, so the edges contradicted each + * other: CallerA called svc-a/vendor's {@code get()} and, through lib's copy, {@code A.tag()}. + */ + @Test + void bothLevelsFallBackToTheNearestCopy(@TempDir Path tmp) throws Exception { + Path in = tmp.resolve("app"); + write(in, "lib/src/main/java/com/shared/Bean.java", + "package com.shared;\npublic class Bean {\n public A get() { return new A(); }\n}\n"); + write(in, "lib/src/main/java/com/shared/A.java", + "package com.shared;\npublic class A {\n public String tag() { return \"a\"; }\n}\n"); + write(in, "svc-a/vendor/com/shared/Bean.java", + "package com.shared;\npublic class Bean {\n public B get() { return new B(); }\n}\n"); + write(in, "svc-a/vendor/com/shared/B.java", + "package com.shared;\npublic class B {\n public String tag() { return \"b\"; }\n}\n"); + write(in, "svc-a/src/main/java/com/app/CallerA.java", + "package com.app;\nimport com.shared.Bean;\npublic class CallerA {\n" + + " public String go() { return new Bean().get().tag(); }\n}\n"); + java.util.List edges = level2Edges(in, tmp.resolve("out")); + java.util.List get = targets(edges, "CallerA", "get()"); + assertEquals(1, get.size(), "CallerA -> get(): " + get); + assertTrue(get.get(0).contains("svc-a/vendor/"), get.get(0)); + assertEquals(1, targets(edges, "CallerA", "/B/tag()").size(), "CallerA -> B.tag(): " + edges); + assertEquals(java.util.List.of(), targets(edges, "CallerA", "/A/tag()")); + } + + /** + * Known limitation, pinned (#269): only the caller's reference picks its own copy. What a found + * copy's declarations refer to (here, the return type of {@code Bean.helper()}) resolves in the + * application-wide order, so CallerB reaches svc-a's {@code Helper}, which lacks + * {@code tag(String)}, and that call stays unresolved. Fixing it needs a parse cache per source + * root; if that lands, this test should flip to expect the svc-b edge. + */ + @Test + void knownLimitationMembersOfAFoundCopyResolveApplicationWide(@TempDir Path tmp) throws Exception { + Path in = tmp.resolve("app"); + for (String svc : new String[] {"svc-a", "svc-b"}) { + shared(in, svc, "Bean", + "public class Bean {\n public Helper helper() { return new Helper(); }\n}\n"); + } + shared(in, "svc-a", "Helper", + "public class Helper {\n public String tag(int n) { return \"a\"; }\n}\n"); + shared(in, "svc-b", "Helper", + "public class Helper {\n public String tag(String s) { return s; }\n}\n"); + shared(in, "svc-b", "CallerB", + "public class CallerB {\n public String go() { return new Bean().helper().tag(\"x\"); }\n}\n"); + java.util.List edges = level2Edges(in, tmp.resolve("out")); + java.util.List helper = targets(edges, "CallerB", "helper()"); + assertEquals(1, helper.size(), "CallerB -> helper(): " + helper); + assertTrue(helper.get(0).contains("svc-b/"), helper.get(0)); + assertEquals(java.util.List.of(), targets(edges, "CallerB", "tag(")); + } + + private static String stderrOf(String... args) throws Exception { + java.io.PrintStream original = System.err; + java.io.ByteArrayOutputStream captured = new java.io.ByteArrayOutputStream(); + System.setErr(new java.io.PrintStream(captured, true, "UTF-8")); + try { + assertEquals(0, run(args), String.join(" ", args)); + } finally { + System.setErr(original); + } + return captured.toString(StandardCharsets.UTF_8); + } + + /** + * A duplicated name is warned about on stderr on every run, verbose or not, and is not a + * degradation (#269): the output keeps every copy, so --strict passes. + */ + @Test + void duplicateQualifiedNamesWarnOnStderrAndPassStrict(@TempDir Path tmp) throws Exception { + Path in = vendoredServices(tmp.resolve("app")); + String err = stderrOf("-i", in.toString(), "-o", tmp.resolve("strict").toString(), + "--app-name", "dt", "--strict"); + assertTrue(err.contains("warning: 1 qualified type name(s) are declared in more than one file"), + err); + assertTrue(err.contains("com.shared.RunStatsDataBean in svc-a/src/main/java/com/shared/" + + "RunStatsDataBean.java, svc-b/"), err); + Path single = project(tmp.resolve("single")); + String clean = stderrOf("-i", single.toString(), "-o", tmp.resolve("single-out").toString(), + "--app-name", "widgets", "--strict"); + assertTrue(!clean.contains("warning:"), clean); + } + +} diff --git a/src/test/java/com/ibm/cldk/neo4j/DuplicateTypeProjectionTest.java b/src/test/java/com/ibm/cldk/neo4j/DuplicateTypeProjectionTest.java new file mode 100644 index 00000000..a97ac30f --- /dev/null +++ b/src/test/java/com/ibm/cldk/neo4j/DuplicateTypeProjectionTest.java @@ -0,0 +1,74 @@ +package com.ibm.cldk.neo4j; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ibm.cldk.neo4j.GraphRows.EdgeRow; +import com.ibm.cldk.schema.JModule; +import com.ibm.cldk.schema.V2Emitter; +import com.ibm.cldk.syntactic_analysis.L1Extractor; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The projector resolves a duplicated type name to the copy nearest the referring module (#269): + * extends and import edges from each service reach that service's own {@code com.shared.Base}. + */ +class DuplicateTypeProjectionTest { + + private static void write(Path root, String rel, String text) throws IOException { + Path f = root.resolve(rel); + Files.createDirectories(f.getParent()); + Files.writeString(f, text, StandardCharsets.UTF_8); + } + + private static GraphRows project(Path root) throws IOException { + for (String svc : new String[] {"svc-a", "svc-b"}) { + String src = svc + "/src/main/java/"; + String child = "Child" + Character.toUpperCase(svc.charAt(4)); + write(root, src + "com/shared/Base.java", "package com.shared;\npublic class Base {}\n"); + write(root, src + "com/shared/" + child + ".java", + "package com.shared;\npublic class " + child + " extends Base {}\n"); + write(root, src + "com/other/Uses.java", + "package com.other;\nimport com.shared.Base;\npublic class Uses { Base base; }\n"); + } + Map modules = L1Extractor.extractAll(root, "dt", null, new LinkedHashMap<>(), 1, 3, "ast"); + return V2GraphProjector.project(V2Emitter.emit("dt", 1, modules, "test"), "dt"); + } + + private static List edges(GraphRows rows, String type) { + return rows.edges.stream().filter(e -> e.type.equals(type)).collect(Collectors.toList()); + } + + @Test + void extendsReachesTheSubclassesOwnServicesCopy(@TempDir Path tmp) throws IOException { + List ext = edges(project(tmp), "J_EXTENDS"); + assertEquals(2, ext.size(), ext.toString()); + for (EdgeRow e : ext) { + String svc = e.from.value.contains("/svc-a/") ? "/svc-a/" : "/svc-b/"; + assertTrue(e.to.value.contains(svc + "src/main/java/com/shared/Base.java"), + e.from.value + " extends " + e.to.value); + } + } + + @Test + void importsReachTheImportingServicesOwnCopy(@TempDir Path tmp) throws IOException { + List imports = edges(project(tmp), "J_IMPORTS").stream() + .filter(e -> e.to.value.contains("com/shared/Base.java")) + .collect(Collectors.toList()); + assertEquals(2, imports.size(), imports.toString()); + for (EdgeRow e : imports) { + String svc = e.from.value.contains("svc-a/") ? "svc-a/" : "svc-b/"; + assertTrue(e.to.value.contains(svc + "src/main/java/com/shared/Base.java"), + e.from.value + " imports " + e.to.value); + } + } +} diff --git a/src/test/java/com/ibm/cldk/schema/FqnIndexTest.java b/src/test/java/com/ibm/cldk/schema/FqnIndexTest.java new file mode 100644 index 00000000..38e69b49 --- /dev/null +++ b/src/test/java/com/ibm/cldk/schema/FqnIndexTest.java @@ -0,0 +1,56 @@ +package com.ibm.cldk.schema; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import org.junit.jupiter.api.Test; + +/** One name declared by several types binds to the copy nearest its referrer (#269). */ +class FqnIndexTest { + private static final String A = "can://dt/dt/java/svc-a/src/main/java/com/shared/Bean.java/Bean"; + private static final String B = "can://dt/dt/java/svc-b/src/main/java/com/shared/Bean.java/Bean"; + private static final String C = "can://dt/dt/java/svc-c/src/main/java/com/shared/Bean.java/Bean"; + + private static FqnIndex index() { + FqnIndex index = new FqnIndex(); + index.put("com.shared.Bean", C); // inserted last-first: order must not matter + index.put("com.shared.Bean", A); + index.put("com.shared.Bean", B); + index.put("com.shared.Only", A + "/Only"); + return index; + } + + @Test + void theReferrersOwnCopyWins() { + assertEquals(A, index().nearest("com.shared.Bean", + "can://dt/dt/java/svc-a/src/main/java/com/shared/Caller.java/Caller/go()")); + assertEquals(B, index().nearest("com.shared.Bean", + "can://dt/dt/java/svc-b/src/main/java/com/shared/Caller.java/Caller/go()")); + } + + @Test + void withNoNearerCopyIdOrderDecides() { + assertEquals(A, index().nearest("com.shared.Bean", + "can://dt/dt/java/svc-d/src/main/java/com/shared/Caller.java/Caller/go()")); + assertEquals(A, index().nearest("com.shared.Bean", null)); + assertEquals(List.of(B, A, C), index().ordered("com.shared.Bean", + "can://dt/dt/java/svc-b/src/main/java/x/Y.java/Y")); + } + + @Test + void anUnknownNameHasNone() { + assertNull(index().nearest("com.shared.Missing", A)); + assertEquals(List.of(), index().ordered("com.shared.Missing", null)); + } + + /** A caller cannot reorder or extend the index through a returned list. */ + @Test + void orderedListsAreReadOnly() { + FqnIndex index = index(); + assertThrows(UnsupportedOperationException.class, () -> index.ordered("com.shared.Bean", null).clear()); + assertThrows(UnsupportedOperationException.class, () -> index.ordered("com.shared.Only", A).clear()); + assertEquals(List.of(A, B, C), index.ordered("com.shared.Bean", null)); + } +}