Java Code Examples for com.sun.tools.javac.file.JavacFileManager#setLocation()

The following examples show how to use com.sun.tools.javac.file.JavacFileManager#setLocation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestInferBinaryName.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
JavaFileManager getFileManager(String classpathProperty,
                               boolean symFileKind,
                               boolean zipFileIndexKind)
        throws IOException {
    Context ctx = new Context();
    Options options = Options.instance(ctx);
    options.put("useOptimizedZip",
            Boolean.toString(zipFileIndexKind == USE_ZIP_FILE_INDEX));

    if (symFileKind == IGNORE_SYMBOL_FILE)
        options.put("ignore.symbol.file", "true");
    JavacFileManager fm = new JavacFileManager(ctx, false, null);
    List<File> path = getPath(System.getProperty(classpathProperty));
    fm.setLocation(CLASS_PATH, path);
    return fm;
}
 
Example 2
Source File: TestInferBinaryName.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
JavaFileManager getFileManager(String classpathProperty,
                               boolean symFileKind,
                               boolean zipFileIndexKind)
        throws IOException {
    Context ctx = new Context();
    Options options = Options.instance(ctx);
    options.put("useOptimizedZip",
            Boolean.toString(zipFileIndexKind == USE_ZIP_FILE_INDEX));

    if (symFileKind == IGNORE_SYMBOL_FILE)
        options.put("ignore.symbol.file", "true");
    JavacFileManager fm = new JavacFileManager(ctx, false, null);
    List<File> path = getPath(System.getProperty(classpathProperty));
    fm.setLocation(CLASS_PATH, path);
    return fm;
}
 
Example 3
Source File: TestInferBinaryName.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
JavaFileManager getFileManager(String classpathProperty,
                               boolean symFileKind,
                               boolean zipFileIndexKind)
        throws IOException {
    Context ctx = new Context();
    Options options = Options.instance(ctx);
    options.put("useOptimizedZip",
            Boolean.toString(zipFileIndexKind == USE_ZIP_FILE_INDEX));

    if (symFileKind == IGNORE_SYMBOL_FILE)
        options.put("ignore.symbol.file", "true");
    JavacFileManager fm = new JavacFileManager(ctx, false, null);
    List<File> path = getPath(System.getProperty(classpathProperty));
    fm.setLocation(CLASS_PATH, path);
    return fm;
}
 
Example 4
Source File: TestInferBinaryName.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
JavaFileManager getFileManager(String classpathProperty,
                               boolean symFileKind,
                               boolean zipFileIndexKind)
        throws IOException {
    Context ctx = new Context();
    Options options = Options.instance(ctx);
    options.put("useOptimizedZip",
            Boolean.toString(zipFileIndexKind == USE_ZIP_FILE_INDEX));

    if (symFileKind == IGNORE_SYMBOL_FILE)
        options.put("ignore.symbol.file", "true");
    JavacFileManager fm = new JavacFileManager(ctx, false, null);
    List<File> path = getPath(System.getProperty(classpathProperty));
    fm.setLocation(CLASS_PATH, path);
    return fm;
}
 
Example 5
Source File: RemoveUnusedImports.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
private static JCCompilationUnit parse(Context context, String javaInput)
    throws FormatterException {
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  context.put(DiagnosticListener.class, diagnostics);
  Options.instance(context).put("--enable-preview", "true");
  Options.instance(context).put("allowStringFolding", "false");
  JCCompilationUnit unit;
  JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
  try {
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.of());
  } catch (IOException e) {
    // impossible
    throw new IOError(e);
  }
  SimpleJavaFileObject source =
      new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
          return javaInput;
        }
      };
  Log.instance(context).useSource(source);
  ParserFactory parserFactory = ParserFactory.instance(context);
  JavacParser parser =
      parserFactory.newParser(
          javaInput, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true);
  unit = parser.parseCompilationUnit();
  unit.sourcefile = source;
  Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
      Iterables.filter(diagnostics.getDiagnostics(), Formatter::errorDiagnostic);
  if (!Iterables.isEmpty(errorDiagnostics)) {
    // error handling is done during formatting
    throw FormatterException.fromJavacDiagnostics(errorDiagnostics);
  }
  return unit;
}
 
Example 6
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test2() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 7
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test4() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 8
Source File: TestJavacParser.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public void test3() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 9
Source File: TestJavacParser.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public void test4() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 10
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test3() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 11
Source File: StringWrapper.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/** Parses the given Java source. */
private static JCTree.JCCompilationUnit parse(String source, boolean allowStringFolding)
    throws FormatterException {
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  Context context = new Context();
  context.put(DiagnosticListener.class, diagnostics);
  Options.instance(context).put("--enable-preview", "true");
  Options.instance(context).put("allowStringFolding", Boolean.toString(allowStringFolding));
  JCTree.JCCompilationUnit unit;
  JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
  try {
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.of());
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
  SimpleJavaFileObject sjfo =
      new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
          return source;
        }
      };
  Log.instance(context).useSource(sjfo);
  ParserFactory parserFactory = ParserFactory.instance(context);
  JavacParser parser =
      parserFactory.newParser(
          source, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true);
  unit = parser.parseCompilationUnit();
  unit.sourcefile = sjfo;
  Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
      Iterables.filter(diagnostics.getDiagnostics(), Formatter::errorDiagnostic);
  if (!Iterables.isEmpty(errorDiagnostics)) {
    // error handling is done during formatting
    throw FormatterException.fromJavacDiagnostics(errorDiagnostics);
  }
  return unit;
}
 
Example 12
Source File: T6889255.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
void test(String testName, boolean expectNames, String... opts) throws Exception {
    System.err.println("Test " + testName
            + ": expectNames:" + expectNames
            + " javacOpts:" + Arrays.asList(opts));

    File outDir = new File(testName);
    outDir.mkdirs();
    compile(outDir, opts);

    Context ctx = new Context();
    JavacFileManager fm = new JavacFileManager(ctx, true, null);
    fm.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(outDir));
    ClassReader cr = ClassReader.instance(ctx);
    cr.saveParameterNames = true;
    Names names = Names.instance(ctx);

    Set<String> classes = getTopLevelClasses(outDir);
    Deque<String> work = new LinkedList<String>(classes);
    String classname;
    while ((classname = work.poll()) != null) {
        System.err.println("Checking class " + classname);
        ClassSymbol sym = cr.enterClass(names.table.fromString(classname));
        sym.complete();

        if ((sym.flags() & Flags.INTERFACE) != 0 && !testInterfaces)
            continue;

        for (Scope.Entry e = sym.members_field.elems; e != null; e = e.sibling) {
            System.err.println("Checking member " + e.sym);
            switch (e.sym.kind) {
                case Kinds.TYP: {
                    String name = e.sym.flatName().toString();
                    if (!classes.contains(name)) {
                        classes.add(name);
                        work.add(name);
                    }
                    break;
                }
                case Kinds.MTH:
                    verify((MethodSymbol) e.sym, expectNames);
                    break;
            }

        }
    }
}
 
Example 13
Source File: DocLint.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void run(PrintWriter out, String... args) throws BadArgs, IOException {
    env = new Env();
    processArgs(args);

    if (needHelp)
        showHelp(out);

    if (javacFiles.isEmpty()) {
        if (!needHelp)
            out.println(localize("dc.main.no.files.given"));
    }

    JavacTool tool = JavacTool.create();

    JavacFileManager fm = new JavacFileManager(new Context(), false, null);
    fm.setSymbolFileEnabled(false);
    fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, javacBootClassPath);
    fm.setLocation(StandardLocation.CLASS_PATH, javacClassPath);
    fm.setLocation(StandardLocation.SOURCE_PATH, javacSourcePath);

    JavacTask task = tool.getTask(out, fm, null, javacOpts, null,
            fm.getJavaFileObjectsFromFiles(javacFiles));
    Iterable<? extends CompilationUnitTree> units = task.parse();
    ((JavacTaskImpl) task).enter();

    env.init(task);
    checker = new Checker(env);

    DeclScanner ds = new DeclScanner() {
        @Override
        void visitDecl(Tree tree, Name name) {
            TreePath p = getCurrentPath();
            DocCommentTree dc = env.trees.getDocCommentTree(p);

            checker.scan(dc, p);
        }
    };

    ds.scan(units, null);

    reportStats(out);

    Context ctx = ((JavacTaskImpl) task).getContext();
    JavaCompiler c = JavaCompiler.instance(ctx);
    c.printCount("error", c.errorCount());
    c.printCount("warn", c.warningCount());
}
 
Example 14
Source File: Formatter.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link
 * JavaInput} and the corresponding {@link JavaOutput}.
 *
 * @param javaInput  the input, a Java compilation unit
 * @param javaOutput the {@link JavaOutput}
 * @param options    the {@link JavaFormatterOptions}
 */
static void format(
        final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options) {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return javaInput.getText();
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    javaInput.getText(),
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;

    javaInput.setCompilationUnit(unit);
    Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
            Iterables.filter(diagnostics.getDiagnostics(), ERROR_DIAGNOSTIC);
    if (!Iterables.isEmpty(errorDiagnostics)) {
        throw FormattingError.fromJavacDiagnostics(errorDiagnostics);
    }
    OpsBuilder builder = new OpsBuilder(javaInput, javaOutput);
    // Output the compilation unit.
    new JavaInputAstVisitor(builder, options.indentationMultiplier()).scan(unit, null);
    builder.sync(javaInput.getText().length());
    builder.drain();
    Doc doc = new DocBuilder().withOps(builder.build()).build();
    doc.computeBreaks(
            javaOutput.getCommentsHelper(), options.maxLineLength(), new Doc.State(+0, 0));
    doc.write(javaOutput);
    javaOutput.flush();
}
 
Example 15
Source File: ParserTest.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public void test1() {
    final String src = "package com.duy;\n" +
            "\n" +
            "import java.util.ArrayList;\n" +
            "/** * Created by Duy on 17-Jul-17. */\n" +
            "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        ArrayList list = new ArrayList();\n" +
            "        for (int i = 0; i < 1000; i++) {\n" +
            "            list.add(i);\n" +
            "        }\n" +
            "    }\n" +
            "\n";
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    System.out.println(unit.getImports());

}
 
Example 16
Source File: T6889255.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
void test(String testName, boolean expectNames, String... opts) throws Exception {
    System.err.println("Test " + testName
            + ": expectNames:" + expectNames
            + " javacOpts:" + Arrays.asList(opts));

    File outDir = new File(testName);
    outDir.mkdirs();
    compile(outDir, opts);

    Context ctx = new Context();
    JavacFileManager fm = new JavacFileManager(ctx, true, null);
    fm.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(outDir));
    ClassReader cr = ClassReader.instance(ctx);
    cr.saveParameterNames = true;
    Names names = Names.instance(ctx);

    Set<String> classes = getTopLevelClasses(outDir);
    Deque<String> work = new LinkedList<String>(classes);
    String classname;
    while ((classname = work.poll()) != null) {
        System.err.println("Checking class " + classname);
        ClassSymbol sym = cr.enterClass(names.table.fromString(classname));
        sym.complete();

        if ((sym.flags() & Flags.INTERFACE) != 0 && !testInterfaces)
            continue;

        for (Scope.Entry e = sym.members_field.elems; e != null; e = e.sibling) {
            System.err.println("Checking member " + e.sym);
            switch (e.sym.kind) {
                case Kinds.TYP: {
                    String name = e.sym.flatName().toString();
                    if (!classes.contains(name)) {
                        classes.add(name);
                        work.add(name);
                    }
                    break;
                }
                case Kinds.MTH:
                    verify((MethodSymbol) e.sym, expectNames);
                    break;
            }

        }
    }
}
 
Example 17
Source File: DocLint.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void run(PrintWriter out, String... args) throws BadArgs, IOException {
    env = new Env();
    processArgs(args);

    if (needHelp)
        showHelp(out);

    if (javacFiles.isEmpty()) {
        if (!needHelp)
            out.println(localize("dc.main.no.files.given"));
    }

    JavacTool tool = JavacTool.create();

    JavacFileManager fm = new JavacFileManager(new Context(), false, null);
    fm.setSymbolFileEnabled(false);
    fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, javacBootClassPath);
    fm.setLocation(StandardLocation.CLASS_PATH, javacClassPath);
    fm.setLocation(StandardLocation.SOURCE_PATH, javacSourcePath);

    JavacTask task = tool.getTask(out, fm, null, javacOpts, null,
            fm.getJavaFileObjectsFromFiles(javacFiles));
    Iterable<? extends CompilationUnitTree> units = task.parse();
    ((JavacTaskImpl) task).enter();

    env.init(task);
    checker = new Checker(env);

    DeclScanner ds = new DeclScanner() {
        @Override
        void visitDecl(Tree tree, Name name) {
            TreePath p = getCurrentPath();
            DocCommentTree dc = env.trees.getDocCommentTree(p);

            checker.scan(dc, p);
        }
    };

    ds.scan(units, null);

    reportStats(out);

    Context ctx = ((JavacTaskImpl) task).getContext();
    JavaCompiler c = JavaCompiler.instance(ctx);
    c.printCount("error", c.errorCount());
    c.printCount("warn", c.warningCount());
}
 
Example 18
Source File: JavacParser.java    From j2cl with Apache License 2.0 4 votes vote down vote up
/** Returns a map from file paths to compilation units after Javac parsing. */
public List<CompilationUnit> parseFiles(List<FileInfo> filePaths, boolean useTargetPath) {

  if (filePaths.isEmpty()) {
    return ImmutableList.of();
  }

  // The map must be ordered because it will be iterated over later and if it was not ordered then
  // our output would be unstable
  final Map<String, String> targetPathBySourcePath =
      filePaths.stream().collect(Collectors.toMap(FileInfo::sourcePath, FileInfo::targetPath));

  try {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    JavacFileManager fileManager =
        (JavacFileManager)
            compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8);
    List<File> searchpath = classpathEntries.stream().map(File::new).collect(toList());
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, searchpath);
    fileManager.setLocation(StandardLocation.CLASS_PATH, searchpath);
    JavacTaskImpl task =
        (JavacTaskImpl)
            compiler.getTask(
                null,
                fileManager,
                diagnostics,
                // TODO(b/143213486): Remove -source 8 and figure out how to configure
                // SYSTEM_MODULES and MODULE_PATH to prevent searching for modules.
                ImmutableList.of("-source", "8"),
                null,
                fileManager.getJavaFileObjectsFromFiles(
                    targetPathBySourcePath.keySet().stream().map(File::new).collect(toList())));
    List<CompilationUnitTree> javacCompilationUnits = Lists.newArrayList(task.parse());
    task.analyze();
    if (hasErrors(diagnostics, javacCompilationUnits)) {
      return ImmutableList.of();
    }

    JavaEnvironment javaEnvironment =
        new JavaEnvironment(task.getContext(), FrontendConstants.WELL_KNOWN_CLASS_NAMES);
    List<CompilationUnit> compilationUnits =
        CompilationUnitBuilder.build(javacCompilationUnits, javaEnvironment);

    return compilationUnits;
  } catch (IOException e) {
    problems.fatal(FatalError.valueOf(e.getMessage()));
    return null;
  }
}
 
Example 19
Source File: DocLint.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public void run(PrintWriter out, String... args) throws BadArgs, IOException {
    env = new Env();
    processArgs(args);

    if (needHelp)
        showHelp(out);

    if (javacFiles.isEmpty()) {
        if (!needHelp)
            out.println(localize("dc.main.no.files.given"));
    }

    JavacTool tool = JavacTool.create();

    JavacFileManager fm = new JavacFileManager(new Context(), false, null);
    fm.setSymbolFileEnabled(false);
    fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, javacBootClassPath);
    fm.setLocation(StandardLocation.CLASS_PATH, javacClassPath);
    fm.setLocation(StandardLocation.SOURCE_PATH, javacSourcePath);

    JavacTask task = tool.getTask(out, fm, null, javacOpts, null,
            fm.getJavaFileObjectsFromFiles(javacFiles));
    Iterable<? extends CompilationUnitTree> units = task.parse();
    ((JavacTaskImpl) task).enter();

    env.init(task);
    checker = new Checker(env);

    DeclScanner ds = new DeclScanner() {
        @Override
        void visitDecl(Tree tree, Name name) {
            TreePath p = getCurrentPath();
            DocCommentTree dc = env.trees.getDocCommentTree(p);

            checker.scan(dc, p);
        }
    };

    ds.scan(units, null);

    reportStats(out);

    Context ctx = ((JavacTaskImpl) task).getContext();
    JavaCompiler c = JavaCompiler.instance(ctx);
    c.printCount("error", c.errorCount());
    c.printCount("warn", c.warningCount());
}
 
Example 20
Source File: DocLint.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public void run(PrintWriter out, String... args) throws BadArgs, IOException {
    env = new Env();
    processArgs(args);

    if (needHelp)
        showHelp(out);

    if (javacFiles.isEmpty()) {
        if (!needHelp)
            out.println(localize("dc.main.no.files.given"));
    }

    JavacTool tool = JavacTool.create();

    JavacFileManager fm = new JavacFileManager(new Context(), false, null);
    fm.setSymbolFileEnabled(false);
    fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, javacBootClassPath);
    fm.setLocation(StandardLocation.CLASS_PATH, javacClassPath);
    fm.setLocation(StandardLocation.SOURCE_PATH, javacSourcePath);

    JavacTask task = tool.getTask(out, fm, null, javacOpts, null,
            fm.getJavaFileObjectsFromFiles(javacFiles));
    Iterable<? extends CompilationUnitTree> units = task.parse();
    ((JavacTaskImpl) task).enter();

    env.init(task);
    checker = new Checker(env);

    DeclScanner ds = new DeclScanner() {
        @Override
        void visitDecl(Tree tree, Name name) {
            TreePath p = getCurrentPath();
            DocCommentTree dc = env.trees.getDocCommentTree(p);

            checker.scan(dc, p);
        }
    };

    ds.scan(units, null);

    reportStats(out);

    Context ctx = ((JavacTaskImpl) task).getContext();
    JavaCompiler c = JavaCompiler.instance(ctx);
    c.printCount("error", c.errorCount());
    c.printCount("warn", c.warningCount());
}