Search in sources :

Example 1 with Arguments

use of com.sun.tools.javac.main.Arguments in project error-prone by google.

the class SuggestedFixes method compilesWithFix.

/**
 * Returns true if the current compilation would succeed with the given fix applied. Note that
 * calling this method is very expensive as it requires rerunning the entire compile, so it should
 * be used with restraint.
 */
public static boolean compilesWithFix(Fix fix, VisitorState state) {
    if (fix.isEmpty()) {
        return true;
    }
    JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit();
    JavaFileObject modifiedFile = compilationUnit.getSourceFile();
    JavacTaskImpl javacTask = (JavacTaskImpl) state.context.get(JavacTask.class);
    if (javacTask == null) {
        throw new IllegalArgumentException("No JavacTask in context.");
    }
    Arguments arguments = Arguments.instance(javacTask.getContext());
    List<JavaFileObject> fileObjects = new ArrayList<>(arguments.getFileObjects());
    for (int i = 0; i < fileObjects.size(); i++) {
        final JavaFileObject oldFile = fileObjects.get(i);
        if (modifiedFile.toUri().equals(oldFile.toUri())) {
            DescriptionBasedDiff diff = DescriptionBasedDiff.create(compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER);
            diff.handleFix(fix);
            SourceFile fixSource;
            try {
                fixSource = new SourceFile(modifiedFile.getName(), modifiedFile.getCharContent(false));
            } catch (IOException e) {
                return false;
            }
            diff.applyDifferences(fixSource);
            fileObjects.set(i, new SimpleJavaFileObject(modifiedFile.toUri(), Kind.SOURCE) {

                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return fixSource.getAsSequence();
                }
            });
            break;
        }
    }
    DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>();
    Context context = new Context();
    Options.instance(context).putAll(Options.instance(javacTask.getContext()));
    context.put(Arguments.class, arguments);
    JavacTask newTask = JavacTool.create().getTask(CharStreams.nullWriter(), state.context.get(JavaFileManager.class), diagnosticListener, ImmutableList.of(), arguments.getClassNames(), fileObjects, context);
    try {
        newTask.analyze();
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return countErrors(diagnosticListener) == 0;
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) Context(com.sun.tools.javac.util.Context) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JavaFileManager(javax.tools.JavaFileManager) Arguments(com.sun.tools.javac.main.Arguments) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector) SourceFile(com.google.errorprone.apply.SourceFile) JavacTask(com.sun.source.util.JavacTask)

Example 2 with Arguments

use of com.sun.tools.javac.main.Arguments in project lombok by rzwitserloot.

the class Delombok method delombok.

public boolean delombok() throws IOException {
    LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);
    options.deleteLombokAnnotations();
    options.putJavacOption("ENCODING", charset.name());
    if (classpath != null)
        options.putJavacOption("CLASSPATH", unpackClasspath(classpath));
    if (sourcepath != null)
        options.putJavacOption("SOURCEPATH", sourcepath);
    if (bootclasspath != null)
        options.putJavacOption("BOOTCLASSPATH", unpackClasspath(bootclasspath));
    options.setFormatPreferences(new FormatPreferences(formatPrefs));
    options.put("compilePolicy", "check");
    if (Javac.getJavaCompilerVersion() >= 9) {
        Arguments args = Arguments.instance(context);
        List<String> argsList = new ArrayList<String>();
        if (classpath != null) {
            argsList.add("--class-path");
            argsList.add(options.get("--class-path"));
        }
        if (sourcepath != null) {
            argsList.add("--source-path");
            argsList.add(options.get("--source-path"));
        }
        if (bootclasspath != null) {
            argsList.add("--boot-class-path");
            argsList.add(options.get("--boot-class-path"));
        }
        if (charset != null) {
            argsList.add("-encoding");
            argsList.add(charset.name());
        }
        String[] argv = argsList.toArray(new String[0]);
        args.init("javac", argv);
    }
    CommentCatcher catcher = CommentCatcher.create(context);
    JavaCompiler compiler = catcher.getCompiler();
    List<JCCompilationUnit> roots = new ArrayList<JCCompilationUnit>();
    Map<JCCompilationUnit, File> baseMap = new IdentityHashMap<JCCompilationUnit, File>();
    Set<LombokProcessor> processors = Collections.singleton(new lombok.javac.apt.LombokProcessor());
    if (Javac.getJavaCompilerVersion() >= 9) {
        JavaFileManager jfm_ = context.get(JavaFileManager.class);
        if (jfm_ instanceof BaseFileManager) {
            Arguments args = Arguments.instance(context);
            // reinit with options
            ((BaseFileManager) jfm_).setContext(context);
            ((BaseFileManager) jfm_).handleOptions(args.getDeferredFileManagerOptions());
        }
    }
    if (Javac.getJavaCompilerVersion() < 9) {
        compiler.initProcessAnnotations(processors);
    } else {
        compiler.initProcessAnnotations(processors, Collections.<JavaFileObject>emptySet(), Collections.<String>emptySet());
    }
    Object unnamedModule = null;
    if (Javac.getJavaCompilerVersion() >= 9)
        unnamedModule = Symtab.instance(context).unnamedModule;
    for (File fileToParse : filesToParse) {
        JCCompilationUnit unit = compiler.parse(fileToParse.getAbsolutePath());
        if (Javac.getJavaCompilerVersion() >= 9)
            try {
                MODULE_FIELD.set(unit, unnamedModule);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        baseMap.put(unit, fileToBase.get(fileToParse));
        roots.add(unit);
    }
    if (compiler.errorCount() > 0) {
        // At least one parse error. No point continuing (a real javac run doesn't either).
        return false;
    }
    for (JCCompilationUnit unit : roots) {
        catcher.setComments(unit, new DocCommentIntegrator().integrate(catcher.getComments(unit), unit));
    }
    if (Javac.getJavaCompilerVersion() >= 9) {
        compiler.initModules(com.sun.tools.javac.util.List.from(roots.toArray(new JCCompilationUnit[0])));
    }
    com.sun.tools.javac.util.List<JCCompilationUnit> trees = compiler.enterTrees(toJavacList(roots));
    JavaCompiler delegate;
    if (Javac.getJavaCompilerVersion() < 9) {
        delegate = compiler.processAnnotations(trees, com.sun.tools.javac.util.List.<String>nil());
    } else {
        delegate = compiler;
        Collection<String> c = com.sun.tools.javac.util.List.nil();
        compiler.processAnnotations(trees, c);
    }
    Object care = callAttributeMethodOnJavaCompiler(delegate, delegate.todo);
    callFlowMethodOnJavaCompiler(delegate, care);
    FormatPreferences fps = new FormatPreferences(formatPrefs);
    for (JCCompilationUnit unit : roots) {
        DelombokResult result = new DelombokResult(catcher.getComments(unit), unit, force || options.isChanged(unit), fps);
        if (verbose)
            feedback.printf("File: %s [%s%s]\n", unit.sourcefile.getName(), result.isChanged() ? "delomboked" : "unchanged", force && !options.isChanged(unit) ? " (forced)" : "");
        Writer rawWriter;
        if (presetWriter != null)
            rawWriter = createUnicodeEscapeWriter(presetWriter);
        else if (output == null)
            rawWriter = createStandardOutWriter();
        else
            rawWriter = createFileWriter(output, baseMap.get(unit), unit.sourcefile.toUri());
        BufferedWriter writer = new BufferedWriter(rawWriter);
        try {
            result.print(writer);
        } finally {
            if (output != null) {
                writer.close();
            } else {
                writer.flush();
            }
        }
    }
    delegate.close();
    return true;
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) IdentityHashMap(java.util.IdentityHashMap) ArrayList(java.util.ArrayList) CommentCatcher(lombok.javac.CommentCatcher) BaseFileManager(com.sun.tools.javac.file.BaseFileManager) BufferedWriter(java.io.BufferedWriter) LombokOptions(lombok.javac.LombokOptions) JavaFileManager(javax.tools.JavaFileManager) Arguments(com.sun.tools.javac.main.Arguments) LombokProcessor(lombok.javac.apt.LombokProcessor) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) LombokProcessor(lombok.javac.apt.LombokProcessor) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter)

Aggregations

Arguments (com.sun.tools.javac.main.Arguments)2 JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)2 ArrayList (java.util.ArrayList)2 JavaFileManager (javax.tools.JavaFileManager)2 JavaFileObject (javax.tools.JavaFileObject)2 DescriptionBasedDiff (com.google.errorprone.apply.DescriptionBasedDiff)1 SourceFile (com.google.errorprone.apply.SourceFile)1 JavacTask (com.sun.source.util.JavacTask)1 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)1 BaseFileManager (com.sun.tools.javac.file.BaseFileManager)1 JavaCompiler (com.sun.tools.javac.main.JavaCompiler)1 Context (com.sun.tools.javac.util.Context)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1 IdentityHashMap (java.util.IdentityHashMap)1 DiagnosticCollector (javax.tools.DiagnosticCollector)1 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)1