package com.ankurm.codesearch; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import com.github.javaparser.JavaParser; import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.CallableDeclaration; import com.github.javaparser.ast.body.TypeDeclaration; import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc; import com.github.javaparser.symbolsolver.JavaSymbolSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; /** * Turns a monorepo into {@link CodeUnit}s with JavaParser. It finds every {@code src/main/java} folder under the * root, parses each {@code .java} file once, and keeps the parsed trees so the usage finder can walk them later. */ public final class CodeIndexer { private final Path root; private final List units = new ArrayList<>(); private final List codeUnits = new ArrayList<>(); private final List parseProblems = new ArrayList<>(); public CodeIndexer(Path root) { this.root = root.toAbsolutePath().normalize(); } /** Parses everything. Call once; the result is read through the accessors. */ public CodeIndexer index() throws IOException { List sourceRoots = findSourceRoots(); // One type solver for the whole monorepo: every module's source folder plus the JDK. CombinedTypeSolver solver = new CombinedTypeSolver(new ReflectionTypeSolver()); for (Path sourceRoot : sourceRoots) { solver.add(new JavaParserTypeSolver(sourceRoot)); } ParserConfiguration config = new ParserConfiguration() .setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_25) .setSymbolResolver(new JavaSymbolSolver(solver)); JavaParser parser = new JavaParser(config); for (Path sourceRoot : sourceRoots) { try (Stream files = Files.walk(sourceRoot)) { for (Path file : files.filter(f -> f.toString().endsWith(".java")).sorted().toList()) { var result = parser.parse(file); if (result.getResult().isEmpty() || !result.isSuccessful()) { parseProblems.add(relative(file) + ": " + result.getProblems().size() + " problem(s)"); } result.getResult().ifPresent(cu -> { cu.setStorage(file); units.add(cu); cu.findAll(TypeDeclaration.class).forEach(t -> addType(cu, t)); }); } } } return this; } private List findSourceRoots() throws IOException { try (Stream walk = Files.walk(root)) { return walk.filter(Files::isDirectory) .filter(p -> p.endsWith(Path.of("src", "main", "java"))) .sorted().toList(); } } private void addType(CompilationUnit cu, TypeDeclaration type) { String qualified = type.getFullyQualifiedName().orElse(type.getNameAsString()); codeUnits.add(new CodeUnit(CodeUnit.Kind.TYPE, qualified, header(type), relative(cu), line(type), javadoc(type), type.getNameAsString() + " (" + type.getMembers().size() + " members)")); for (var member : type.getMembers()) { if (member instanceof CallableDeclaration callable) { codeUnits.add(new CodeUnit(CodeUnit.Kind.METHOD, qualified + "#" + callable.getNameAsString(), callable.getDeclarationAsString(true, false, true), relative(cu), line(callable), javadoc(callable), callable.toString())); } } } private static String header(TypeDeclaration type) { String kind = switch (type) { case com.github.javaparser.ast.body.ClassOrInterfaceDeclaration c -> c.isInterface() ? "interface" : "class"; case com.github.javaparser.ast.body.RecordDeclaration r -> "record"; case com.github.javaparser.ast.body.EnumDeclaration e -> "enum"; default -> "type"; }; return kind + " " + type.getNameAsString(); } private static int line(Node node) { return node.getRange().map(r -> r.begin.line).orElse(0); } private static String javadoc(Node node) { if (node instanceof NodeWithJavadoc documented) { return documented.getJavadoc().map(j -> j.getDescription().toText().replaceAll("\\s+", " ").trim()) .orElse(""); } return ""; } private String relative(CompilationUnit cu) { return relative(cu.getStorage().orElseThrow().getPath()); } private String relative(Path file) { return root.relativize(file.toAbsolutePath().normalize()).toString().replace('\\', '/'); } public Path root() { return root; } public List compilationUnits() { return List.copyOf(units); } public List codeUnits() { return List.copyOf(codeUnits); } public List parseProblems() { return List.copyOf(parseProblems); } }