Search in sources :

Example 11 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 12 with JavaCompiler

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

the class T6400303 method main.

public static void main(String... args) {
    javax.tools.JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(null, null, null, null, null, null);
    JavaCompiler compiler = JavaCompiler.instance(task.getContext());
    try {
        compiler.resolveIdent("Test$1").complete();
    } catch (CompletionFailure ex) {
        System.err.println("Got expected completion failure: " + ex.getLocalizedMessage());
        return;
    }
    throw new AssertionError("No error reported");
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) CompletionFailure(com.sun.tools.javac.code.Symbol.CompletionFailure) JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Example 13 with JavaCompiler

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

the class VisitorState method getTypeFromStringInternal.

private Type getTypeFromStringInternal(String typeStr) {
    validateTypeStr(typeStr);
    if (isPrimitiveType(typeStr)) {
        return getPrimitiveType(typeStr);
    }
    Name typeName = getName(typeStr);
    try {
        ClassSymbol typeSymbol = getSymtab().classes.get(typeName);
        if (typeSymbol == null) {
            JavaCompiler compiler = JavaCompiler.instance(context);
            Symbol sym = compiler.resolveIdent(typeStr);
            if (!(sym instanceof ClassSymbol)) {
                return null;
            }
            typeSymbol = (ClassSymbol) sym;
        }
        Type type = typeSymbol.asType();
        // Throws CompletionFailure if the source/class file for this type is not available.
        // This is hacky but the best way I can think of to handle this case.
        type.complete();
        if (type.isErroneous()) {
            return null;
        }
        return type;
    } catch (CompletionFailure failure) {
        return null;
    }
}
Also used : ClassType(com.sun.tools.javac.code.Type.ClassType) ArrayType(com.sun.tools.javac.code.Type.ArrayType) Type(com.sun.tools.javac.code.Type) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) Symbol(com.sun.tools.javac.code.Symbol) CompletionFailure(com.sun.tools.javac.code.Symbol.CompletionFailure) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) Name(com.sun.tools.javac.util.Name)

Example 14 with JavaCompiler

use of com.sun.tools.javac.main.JavaCompiler 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", classpath);
    if (sourcepath != null)
        options.putJavacOption("SOURCEPATH", sourcepath);
    if (bootclasspath != null)
        options.putJavacOption("BOOTCLASSPATH", bootclasspath);
    options.setFormatPreferences(new FormatPreferences(formatPrefs));
    options.put("compilePolicy", "check");
    CommentCatcher catcher = CommentCatcher.create(context);
    JavaCompiler compiler = catcher.getCompiler();
    List<JCCompilationUnit> roots = new ArrayList<JCCompilationUnit>();
    Map<JCCompilationUnit, File> baseMap = new IdentityHashMap<JCCompilationUnit, File>();
    compiler.initProcessAnnotations(Collections.singleton(new lombok.javac.apt.LombokProcessor()));
    for (File fileToParse : filesToParse) {
        @SuppressWarnings("deprecation") JCCompilationUnit unit = compiler.parse(fileToParse.getAbsolutePath());
        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));
    }
    com.sun.tools.javac.util.List<JCCompilationUnit> trees = compiler.enterTrees(toJavacList(roots));
    JavaCompiler delegate = compiler.processAnnotations(trees);
    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) CommentCatcher(lombok.javac.CommentCatcher) ArrayList(java.util.ArrayList) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) BufferedWriter(java.io.BufferedWriter) LombokOptions(lombok.javac.LombokOptions) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer)

Example 15 with JavaCompiler

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

the class CommentCollectingParserFactory method setInCompiler.

public static void setInCompiler(JavaCompiler compiler, Context context) {
    context.put(CommentCollectingParserFactory.key(), (ParserFactory) null);
    Field field;
    try {
        field = JavaCompiler.class.getDeclaredField("parserFactory");
        field.setAccessible(true);
        field.set(compiler, new CommentCollectingParserFactory(context));
    } catch (Exception e) {
        throw new IllegalStateException("Could not set comment sensitive parser in the compiler", e);
    }
}
Also used : Field(java.lang.reflect.Field) JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Aggregations

JavaCompiler (com.sun.tools.javac.main.JavaCompiler)18 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)4 JavaFileObject (javax.tools.JavaFileObject)4 Field (java.lang.reflect.Field)3 CompletionFailure (com.sun.tools.javac.code.Symbol.CompletionFailure)2 JavacFileManager (com.sun.tools.javac.file.JavacFileManager)2 BadClassFile (com.sun.tools.javac.jvm.ClassReader.BadClassFile)2 Context (com.sun.tools.javac.util.Context)2 File (java.io.File)2 JavaFileManager (javax.tools.JavaFileManager)2 EnvironmentException (com.redhat.ceylon.compiler.EnvironmentException)1 RepositoryException (com.redhat.ceylon.model.cmr.RepositoryException)1 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)1 MethodTree (com.sun.source.tree.MethodTree)1 TaskEvent (com.sun.source.util.TaskEvent)1 TaskListener (com.sun.source.util.TaskListener)1 TreePathScanner (com.sun.source.util.TreePathScanner)1 Symbol (com.sun.tools.javac.code.Symbol)1 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)1 Type (com.sun.tools.javac.code.Type)1