summaryrefslogtreecommitdiff
path: root/src/main/java/org/javacs/JavaCompilerService.java
blob: b66f5bee9d26acf01c7ca0b53849ab99640f3900 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package org.javacs;

import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.lang.model.element.*;
import javax.tools.*;

// TODO eliminate uses of URI in favor of Path
public class JavaCompilerService {
    // Not modifiable! If you want to edit these, you need to create a new instance
    final Set<Path> sourcePath, classPath, docPath;
    final JavaCompiler compiler = ServiceLoader.load(JavaCompiler.class).iterator().next();
    final Docs docs;
    final ClassSource jdkClasses = Classes.jdkTopLevelClasses(), classPathClasses;
    // Diagnostics from the last compilation task
    final List<Diagnostic<? extends JavaFileObject>> diags = new ArrayList<>();
    // Use the same file manager for multiple tasks, so we don't repeatedly re-compile the same files
    final StandardJavaFileManager fileManager =
            new FileManagerWrapper(compiler.getStandardFileManager(diags::add, null, Charset.defaultCharset()));

    public JavaCompilerService(Set<Path> sourcePath, Set<Path> classPath, Set<Path> docPath) {
        System.err.println("Source path:");
        for (var p : sourcePath) {
            System.err.println("  " + p);
        }
        System.err.println("Class path:");
        for (var p : classPath) {
            System.err.println("  " + p);
        }
        System.err.println("Doc path:");
        for (var p : docPath) {
            System.err.println("  " + p);
        }
        // sourcePath and classPath can't actually be modified, because JavaCompiler remembers them from task to task
        this.sourcePath = Collections.unmodifiableSet(sourcePath);
        this.classPath = Collections.unmodifiableSet(classPath);
        this.docPath = Collections.unmodifiableSet(docPath);
        var docSourcePath = new HashSet<Path>();
        docSourcePath.addAll(sourcePath);
        docSourcePath.addAll(docPath);
        this.docs = new Docs(docSourcePath);
        this.classPathClasses = Classes.classPathTopLevelClasses(classPath);
    }

    /** Combine source path or class path entries using the system separator, for example ':' in unix */
    private static String joinPath(Collection<Path> classOrSourcePath) {
        return classOrSourcePath.stream().map(p -> p.toString()).collect(Collectors.joining(File.pathSeparator));
    }

    static List<String> options(Set<Path> sourcePath, Set<Path> classPath) {
        var list = new ArrayList<String>();

        Collections.addAll(list, "-classpath", joinPath(classPath));
        Collections.addAll(list, "-sourcepath", joinPath(sourcePath));
        // Collections.addAll(list, "-verbose");
        Collections.addAll(list, "-proc:none");
        Collections.addAll(list, "-g");
        // You would think we could do -Xlint:all,
        // but some lints trigger fatal errors in the presence of parse errors
        Collections.addAll(
                list,
                "-Xlint:cast",
                "-Xlint:deprecation",
                "-Xlint:empty",
                "-Xlint:fallthrough",
                "-Xlint:finally",
                "-Xlint:path",
                "-Xlint:unchecked",
                "-Xlint:varargs",
                "-Xlint:static");

        return list;
    }

    private Collection<Path> removeModuleInfo(Collection<Path> files) {
        var result = new ArrayList<Path>();
        for (var f : files) {
            if (f.getFileName().endsWith("module-info.java")) LOG.info("Skip " + f);
            else result.add(f);
        }
        return result;
    }

    static Iterable<Path> javaSourcesInDir(Path dir) {
        var match = FileSystems.getDefault().getPathMatcher("glob:*.java");

        try {
            // TODO instead of looking at EVERY file, once you see a few files with the same source directory,
            // ignore all subsequent files in the directory
            return Files.walk(dir).filter(java -> match.matches(java.getFileName()))::iterator;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Docs docs() {
        return docs;
    }

    public ParseFile parseFile(URI file, String contents) {
        return new ParseFile(this, file, contents);
    }

    public CompileFocus compileFocus(URI file, String contents, int line, int character) {
        return new CompileFocus(this, file, contents, line, character);
    }

    public CompileFile compileFile(URI file, String contents) {
        return new CompileFile(this, file, contents);
    }

    public CompileBatch compileBatch(Collection<URI> files) {
        return new CompileBatch(this, files);
    }

    private boolean containsWord(String toPackage, String toClass, String name, Path file) {
        if (!name.matches("\\w*")) throw new RuntimeException(String.format("`%s` is not a word", name));
        var samePackage = Pattern.compile("^package +" + toPackage + ";");
        var importClass = Pattern.compile("^import +" + toPackage + "\\." + toClass + ";");
        var importStar = Pattern.compile("^import +" + toPackage + "\\.\\*;");
        var importStatic = Pattern.compile("^import +static +" + toPackage + "\\.");
        var startOfClass = Pattern.compile("class +\\w+");
        var word = Pattern.compile("\\b" + name + "\\b");
        var foundImport = toPackage.isEmpty(); // If package is empty, everyone imports it
        var foundWord = false;
        try (var read = Files.newBufferedReader(file)) {
            while (true) {
                var line = read.readLine();
                if (line == null) break;
                if (!foundImport && startOfClass.matcher(line).find()) break;
                if (samePackage.matcher(line).find()) foundImport = true;
                if (importClass.matcher(line).find()) foundImport = true;
                if (importStar.matcher(line).find()) foundImport = true;
                if (importStatic.matcher(line).find()) foundImport = true;
                if (importClass.matcher(line).find()) foundImport = true;
                if (word.matcher(line).find()) foundWord = true;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return foundImport && foundWord;
    }

    private boolean importsAnyClass(String toPackage, List<String> toClasses, Path file) {
        if (toPackage.isEmpty()) return true; // If package is empty, everyone imports it
        var toClass = toClasses.stream().collect(Collectors.joining("|"));
        var samePackage = Pattern.compile("^package +" + toPackage + ";");
        var importClass = Pattern.compile("^import +" + toPackage + "\\.(" + toClass + ");");
        var importStar = Pattern.compile("^import +" + toPackage + "\\.\\*;");
        var importStatic = Pattern.compile("^import +static +" + toPackage + "\\.");
        var startOfClass = Pattern.compile("class +\\w+");
        try (var read = Files.newBufferedReader(file)) {
            while (true) {
                var line = read.readLine();
                if (line == null) break;
                if (startOfClass.matcher(line).find()) break;
                if (samePackage.matcher(line).find()) return true;
                if (importClass.matcher(line).find()) return true;
                if (importStar.matcher(line).find()) return true;
                if (importStatic.matcher(line).find()) return true;
                if (importClass.matcher(line).find()) return true;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    private List<Path> allJavaSources() {
        var allFiles = new ArrayList<Path>();
        for (var dir : sourcePath) {
            for (var file : javaSourcesInDir(dir)) {
                allFiles.add(file);
            }
        }
        return allFiles;
    }

    // TODO should probably cache this
    public List<URI> potentialReferences(Element to) {
        LOG.info(String.format("Find potential references to `%s`...", to));

        // Find files that import toPackage.toClass and contain the word el
        var toPackage = packageName(to);
        var toClass = className(to);
        var name = to.getSimpleName().toString();
        if (name.equals("<init>")) name = to.getEnclosingElement().getSimpleName().toString();
        LOG.info(String.format("...look for the word `%s` in files that import %s.%s", name, toPackage, toClass));

        // Check all files on source path
        var allFiles = allJavaSources();
        LOG.info(String.format("...check %d files on the source path", allFiles.size()));

        // Check files, one at a time
        var result = new ArrayList<URI>();
        int nScanned = 0;
        for (var file : allFiles) {
            if (containsWord(toPackage, toClass, name, file)) result.add(file.toUri());
        }
        LOG.info(String.format("...%d files might have references to `%s`", result.size(), to));

        return result;
    }

    public static String packageName(Element e) {
        while (e != null) {
            if (e instanceof PackageElement) {
                var pkg = (PackageElement) e;
                return pkg.getQualifiedName().toString();
            }
            e = e.getEnclosingElement();
        }
        return "";
    }

    public static String className(Element e) {
        while (e != null) {
            if (e instanceof TypeElement) {
                var type = (TypeElement) e;
                return type.getSimpleName().toString();
            }
            e = e.getEnclosingElement();
        }
        return "";
    }

    public static String className(TreePath t) {
        while (t != null) {
            if (t.getLeaf() instanceof ClassTree) {
                var cls = (ClassTree) t.getLeaf();
                return cls.getSimpleName().toString();
            }
            t = t.getParentPath();
        }
        return "";
    }

    public static Optional<String> memberName(TreePath t) {
        while (t != null) {
            if (t.getLeaf() instanceof ClassTree) {
                return Optional.empty();
            } else if (t.getLeaf() instanceof MethodTree) {
                var method = (MethodTree) t.getLeaf();
                var name = method.getName().toString();
                return Optional.of(name);
            } else if (t.getLeaf() instanceof VariableTree) {
                var field = (VariableTree) t.getLeaf();
                var name = field.getName().toString();
                return Optional.of(name);
            }
            t = t.getParentPath();
        }
        return Optional.empty();
    }

    // TODO should probably cache this
    private Collection<URI> potentialReferencesToClasses(String toPackage, List<String> toClasses) {
        // Filter for files that import toPackage.toClass
        var result = new LinkedHashSet<URI>();
        for (var dir : sourcePath) {
            for (var file : javaSourcesInDir(dir)) {
                if (importsAnyClass(toPackage, toClasses, file)) {
                    result.add(file.toUri());
                }
            }
        }
        return result;
    }

    private List<String> allClassNames(CompilationUnitTree root) {
        var result = new ArrayList<String>();
        class FindClasses extends TreeScanner<Void, Void> {
            @Override
            public Void visitClass(ClassTree classTree, Void __) {
                var className = Objects.toString(classTree.getSimpleName(), "");
                result.add(className);
                return null;
            }
        }
        root.accept(new FindClasses(), null);
        return result;
    }

    private Map<URI, Index> index = new HashMap<>();

    private void updateIndex(Collection<URI> possible) {
        LOG.info(String.format("Check %d files for modifications compared to index...", possible.size()));
        var outOfDate = new ArrayList<URI>();
        for (var p : possible) {
            var i = index.getOrDefault(p, Index.EMPTY);
            var modified = Instant.ofEpochMilli(new File(p).lastModified());
            if (modified.isAfter(i.created)) {
                outOfDate.add(p);
            }
        }
        LOG.info(String.format("... %d files are out-of-date", outOfDate.size()));
        // If there's nothing to update, return
        if (outOfDate.isEmpty()) return;
        // Reindex
        var counts = compileBatch(outOfDate).countReferences();
        index.putAll(counts);
    }

    public Map<Ptr, Integer> countReferences(URI file, String contents) {
        var root = Parser.parse(new StringFileObject(contents, file));
        // List all files that import file
        var toPackage = Objects.toString(root.getPackageName(), "");
        var toClasses = allClassNames(root);
        var possible = potentialReferencesToClasses(toPackage, toClasses);
        if (possible.isEmpty()) {
            LOG.info("No potential references to " + file);
            return Map.of();
        }
        // Reindex only files that are out-of-date
        updateIndex(possible);
        // Assemble results
        var result = new HashMap<Ptr, Integer>();
        for (var p : possible) {
            var i = index.get(p);
            for (var r : i.refs) {
                var count = result.getOrDefault(r, 0);
                result.put(r, count + 1);
            }
        }
        return result;
    }

    public Stream<TreePath> findSymbols(String query) {
        return sourcePath.stream().flatMap(dir -> Parser.findSymbols(dir, query));
    }

    private static final Logger LOG = Logger.getLogger("main");
}