Search in sources :

Example 26 with JavaCompiler

use of com.sun.tools.javac.main.JavaCompiler in project ceylon by eclipse.

the class T6358168 method testAnnotationProcessing.

static void testAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);
    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new ListBuffer<File>();
    compilerMain.processArgs(new String[] { "-XprintRounds", "-processorpath", testClasses, "-processor", self, "-d", "." });
    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.initProcessAnnotations(null);
    JavaCompiler compiler2 = compiler.processAnnotations(compiler.enterTrees(compiler.parseFiles(List.of(f))));
    try {
        compiler2.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
Also used : JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Example 27 with JavaCompiler

use of com.sun.tools.javac.main.JavaCompiler in project ceylon-compiler by ceylon.

the class T6358166 method test.

static void test(JavacFileManager fm, JavaFileObject f, String... args) throws Throwable {
    Context context = new Context();
    fm.setContext(context);
    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new ListBuffer<File>();
    compilerMain.processArgs(args);
    JavaCompiler c = JavaCompiler.instance(context);
    c.compile(List.of(f));
    if (c.errorCount() != 0)
        throw new AssertionError("compilation failed");
    long msec = c.elapsed_msec;
    if (// allow test 5 mins to execute, should be more than enough!
    msec < 0 || msec > 5 * 60 * 1000)
        throw new AssertionError("elapsed time is suspect: " + msec);
}
Also used : JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Example 28 with JavaCompiler

use of com.sun.tools.javac.main.JavaCompiler in project ceylon-compiler by ceylon.

the class TestResolveIdent method main.

public static void main(String[] args) throws IOException {
    javax.tools.JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(null, null, null, null, null, null);
    JavaCompiler compiler = JavaCompiler.instance(task.getContext());
    System.out.println(compiler.resolveIdent(getDeprecatedClass().getCanonicalName()));
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Example 29 with JavaCompiler

use of com.sun.tools.javac.main.JavaCompiler in project ceylon-compiler by ceylon.

the class Main method compile.

/**
 * Programmatic interface for main function.
 * @param args The command line parameters.
 */
public int compile(String[] args, Context context, List<JavaFileObject> fileObjects, Iterable<? extends Processor> processors) {
    if (options == null) {
        // creates a new one
        options = Options.instance(context);
    }
    filenames = new ListBuffer<File>();
    classnames = new ListBuffer<String>();
    exitState = null;
    JavaCompiler comp = null;
    /* TODO: Logic below about what is an acceptable command line should be
         * updated to take annotation processing semantics into account. */
    try {
        if (args.length == 0 && fileObjects.isEmpty()) {
            help();
            this.exitState = ExitState.cmderror();
            return EXIT_CMDERR;
        }
        List<File> filenames = processArgs(args);
        if (filenames == null) {
            // null signals an error in options, abort
            this.exitState = ExitState.cmderror();
            return EXIT_CMDERR;
        } else if (filenames.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
            // or version info
            if (options.get("-help") != null || options.get("-jhelp") != null || options.get("-X") != null || options.get("-version") != null || options.get("-fullversion") != null)
                return EXIT_OK;
            error("err.no.source.files");
            this.exitState = ExitState.cmderror();
            return EXIT_CMDERR;
        }
        // Set up the timer *after* we've processed to options
        // because it needs to know if we need logging or not
        timer = Timer.instance(context);
        timer.init();
        boolean forceStdOut = options.get("stdout") != null;
        if (forceStdOut) {
            out.flush();
            out = new PrintWriter(System.out, true);
        }
        context.put(Log.outKey, out);
        fileManager = context.get(JavaFileManager.class);
        comp = LanguageCompiler.instance(context);
        if (comp == null) {
            this.exitState = ExitState.systemError(null, null);
            return EXIT_SYSERR;
        }
        if (!classnames.isEmpty()) {
            filenames = addModuleFiles(filenames);
            classnames.clear();
        }
        if (!filenames.isEmpty()) {
            // add filenames to fileObjects
            List<JavaFileObject> otherFiles = List.nil();
            JavacFileManager dfm = (JavacFileManager) fileManager;
            for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(filenames)) {
                otherFiles = otherFiles.append(fo);
            }
            fileObjects = fileObjects.prependList(otherFiles);
        }
        if (fileObjects.isEmpty()) {
            error("err.no.source.files");
            this.exitState = ExitState.cmderror();
            return EXIT_CMDERR;
        }
        comp.compile(fileObjects, classnames.toList(), processors);
        int errorCount = comp.errorCount();
        // ceylonBackendErrors = comp.log instanceof CeylonLog ? ((CeylonLog)comp.log).ceylonBackendErrors() : false;
        if (errorCount != 0) {
            this.exitState = ExitState.error(comp);
            return EXIT_ERROR;
        }
    } catch (IOException ex) {
        ioMessage(ex);
        this.exitState = ExitState.systemError(null, ex);
        return EXIT_SYSERR;
    } catch (OutOfMemoryError ex) {
        resourceMessage(ex);
        this.exitState = ExitState.systemError(null, ex);
        return EXIT_SYSERR;
    } catch (StackOverflowError ex) {
        resourceMessage(ex);
        this.exitState = ExitState.systemError(null, ex);
        return EXIT_SYSERR;
    } catch (FatalError ex) {
        this.exitState = ExitState.systemError(comp, ex);
        if (this.exitState.javacExitCode == EXIT_SYSERR) {
            feMessage(ex);
        }
        return this.exitState.javacExitCode;
    } catch (AnnotationProcessingError ex) {
        apMessage(ex);
        this.exitState = ExitState.systemError(null, ex);
        return EXIT_SYSERR;
    } catch (ClientCodeException ex) {
        // and javax.tools.JavaCompiler.CompilationTask#call
        throw new RuntimeException(ex.getCause());
    } catch (PropagatedException ex) {
        throw ex.getCause();
    } catch (RepositoryException ex) {
        throw new EnvironmentException(ex);
    } catch (Throwable ex) {
        // exceptions.
        if (comp == null || comp.errorCount() == 0 || options == null || options.get("dev") != null) {
            bugMessage(ex);
        }
        this.exitState = ExitState.abnormal(comp, ex, options);
        return EXIT_ABNORMAL;
    } finally {
        if (comp != null)
            comp.close();
        filenames = null;
        options = null;
        if (timer != null) {
            timer.end();
        }
        timer = null;
    }
    this.exitState = ExitState.ok();
    return EXIT_OK;
}
Also used : JavaFileManager(javax.tools.JavaFileManager) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) PropagatedException(com.sun.tools.javac.util.PropagatedException) RepositoryException(com.redhat.ceylon.model.cmr.RepositoryException) IOException(java.io.IOException) EnvironmentException(com.redhat.ceylon.compiler.EnvironmentException) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) AnnotationProcessingError(com.sun.tools.javac.processing.AnnotationProcessingError) JavaFileObject(javax.tools.JavaFileObject) FatalError(com.sun.tools.javac.util.FatalError) ClientCodeException(com.sun.tools.javac.util.ClientCodeException) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 30 with JavaCompiler

use of com.sun.tools.javac.main.JavaCompiler in project ceylon-compiler by ceylon.

the class JavacProcessingEnvironment method doProcessing.

// TODO: internal catch clauses?; catch and rethrow an annotation
// processing error
public JavaCompiler doProcessing(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols, Iterable<? extends PackageSymbol> pckSymbols) {
    TaskListener taskListener = context.get(TaskListener.class);
    log = Log.instance(context);
    Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
    for (PackageSymbol psym : pckSymbols) specifiedPackages.add(psym);
    this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
    Round round = new Round(context, roots, classSymbols);
    boolean errorStatus;
    boolean moreToDo;
    do {
        // Run processors for round n
        round.run(false, false);
        // Processors for round n have run to completion.
        // Check for errors and whether there is more work to do.
        errorStatus = round.unrecoverableError();
        moreToDo = moreToDo();
        round.showDiagnostics(errorStatus || showResolveErrors);
        // Set up next round.
        // Copy mutable collections returned from filer.
        round = round.next(new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()), new LinkedHashMap<String, JavaFileObject>(filer.getGeneratedClasses()));
        // Check for errors during setup.
        if (round.unrecoverableError())
            errorStatus = true;
    } while (moreToDo && !errorStatus);
    // run last round
    round.run(true, errorStatus);
    round.showDiagnostics(true);
    filer.warnIfUnclosedFiles();
    warnIfUnmatchedOptions();
    /*
         * If an annotation processor raises an error in a round,
         * that round runs to completion and one last round occurs.
         * The last round may also occur because no more source or
         * class files have been generated.  Therefore, if an error
         * was raised on either of the last *two* rounds, the compile
         * should exit with a nonzero exit code.  The current value of
         * errorStatus holds whether or not an error was raised on the
         * second to last round; errorRaised() gives the error status
         * of the last round.
         */
    if (messager.errorRaised() || werror && round.warningCount() > 0 && round.errorCount() > 0)
        errorStatus = true;
    Set<JavaFileObject> newSourceFiles = new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
    roots = cleanTrees(round.roots);
    JavaCompiler compiler = round.finalCompiler(errorStatus);
    if (newSourceFiles.size() > 0)
        roots = roots.appendList(compiler.parseFiles(newSourceFiles));
    errorStatus = errorStatus || (compiler.errorCount() > 0);
    // Free resources
    this.close();
    if (taskListener != null)
        taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
    if (errorStatus) {
        if (compiler.errorCount() == 0)
            compiler.log.nerrors++;
        return compiler;
    }
    if (procOnly && !foundTypeProcessors) {
        compiler.todo.clear();
    } else {
        if (procOnly && foundTypeProcessors)
            compiler.shouldStopPolicy = CompileState.FLOW;
        compiler.enterTrees(roots);
    }
    return compiler;
}
Also used : JavaFileObject(javax.tools.JavaFileObject) TaskListener(com.sun.source.util.TaskListener) TaskEvent(com.sun.source.util.TaskEvent) JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Aggregations

JavaCompiler (com.sun.tools.javac.main.JavaCompiler)32 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)8 Context (com.sun.tools.javac.util.Context)7 Field (java.lang.reflect.Field)6 JavaFileObject (javax.tools.JavaFileObject)6 JavaFileManager (javax.tools.JavaFileManager)5 JavacFileManager (com.sun.tools.javac.file.JavacFileManager)4 BadClassFile (com.sun.tools.javac.jvm.ClassReader.BadClassFile)4 CompletionFailure (com.sun.tools.javac.code.Symbol.CompletionFailure)3 JavacProcessingEnvironment (com.sun.tools.javac.processing.JavacProcessingEnvironment)3 OutputStream (java.io.OutputStream)3 PrintStream (java.io.PrintStream)3 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2 MethodTree (com.sun.source.tree.MethodTree)2 TreePathScanner (com.sun.source.util.TreePathScanner)2 Options (com.sun.tools.javac.util.Options)2 File (java.io.File)2 IOException (java.io.IOException)2 EnvironmentException (com.redhat.ceylon.compiler.EnvironmentException)1 RepositoryException (com.redhat.ceylon.model.cmr.RepositoryException)1