Package com.sun.tools.javac.main

Examples of com.sun.tools.javac.main.JavaCompiler


        }

        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()) {
                // it is allowed to compile nothing if just asking for help
                // 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) {
            // as specified by javax.tools.JavaCompiler#getTask
            // 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) {
            // Nasty. If we've already reported an error, compensate
            // for buggy compiler error recovery by swallowing thrown
            // 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();
            }
View Full Code Here


        options.put("-Xprefer", "source");
        // make sure it's registered
        CeylonLog.instance(context);
        CeylonEnter.instance(context);
        CeylonClassWriter.instance(context);
        JavaCompiler instance = context.get(compilerKey);
        if (instance == null)
            instance = new LanguageCompiler(context);
        return instance;
    }
View Full Code Here

        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 (msec < 0 || msec > 5 * 60 * 1000) // allow test 5 mins to execute, should be more than enough!
            throw new AssertionError("elapsed time is suspect: " + msec);
View Full Code Here

        TaskListener taskListener = context.get(TaskListener.class);


        AnnotationCollector collector = new AnnotationCollector();

        JavaCompiler compiler = JavaCompiler.instance(context);
        compiler.todo.clear(); // free the compiler's resources

        int round = 0;

        // List<JCAnnotation> annotationsPresentInSource = collector.findAnnotations(roots);
        List<ClassSymbol> topLevelClasses = getTopLevelClasses(roots);

        for (ClassSymbol classSym : classSymbols)
            topLevelClasses = topLevelClasses.prepend(classSym);
        List<PackageSymbol> packageInfoFiles =
      getPackageInfoFiles(roots);
     
        DEBUG.P("topLevelClasses ="+topLevelClasses);
      DEBUG.P("packageInfoFiles="+packageInfoFiles);

        Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
        for (PackageSymbol psym : pckSymbols)
            specifiedPackages.add(psym);
        this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
       
        DEBUG.P("this.specifiedPackages="+this.specifiedPackages);
       
        // Use annotation processing to compute the set of annotations present
        Set<TypeElement> annotationsPresent = new LinkedHashSet<TypeElement>();
        ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
        for (ClassSymbol classSym : topLevelClasses)
            annotationComputer.scan(classSym, annotationsPresent);
  for (PackageSymbol pkgSym : packageInfoFiles)
      annotationComputer.scan(pkgSym, annotationsPresent);
       
        DEBUG.P("annotationsPresent="+annotationsPresent);

        Context currentContext = context;

        int roundNumber = 0;
        boolean errorStatus = false;

        runAround:
        while(true) {
            DEBUG.P("roundNumber="+roundNumber);
            DEBUG.P("fatalErrors="+fatalErrors);
            DEBUG.P("compiler.errorCount()="+compiler.errorCount());
           
            if (fatalErrors && compiler.errorCount() != 0) {
                errorStatus = true;
                break runAround;
            }

            this.context = currentContext;
            roundNumber++;
            printRoundInfo(xout, roundNumber, topLevelClasses, annotationsPresent, false);

            if (taskListener != null)
                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));

            try {
    discoverAndRunProcs(currentContext, annotationsPresent, topLevelClasses, packageInfoFiles);
            } finally {
                if (taskListener != null)
                    taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
            }

            /*
             * Processors for round n have run to completion.  Prepare
             * for round (n+1) by checked for errors raised by
             * annotation processors and then checking for syntax
             * errors on any generated source files.
             */
            DEBUG.P("messager.errorRaised()="+messager.errorRaised());
            DEBUG.P("moreToDo()="+moreToDo());
            if (messager.errorRaised()) {
                errorStatus = true;
                break runAround;
            } else {
                if (moreToDo()) {
                    // <editor-fold defaultstate="collapsed">
                   
                    // annotationsPresentInSource = List.nil();
                    annotationsPresent = new LinkedHashSet<TypeElement>();
                    topLevelClasses  = List.nil();
        packageInfoFiles = List.nil();

                    compiler.close();
                    currentContext = contextForNextRound(currentContext, true);

                    JavaFileManager fileManager = currentContext.get(JavaFileManager.class);

                    List<JavaFileObject> fileObjects = List.nil();
                    for (JavaFileObject jfo : filer.getGeneratedSourceFileObjects() ) {
                        fileObjects = fileObjects.prepend(jfo);
                    }


                    compiler = JavaCompiler.instance(currentContext);
                    List<JCCompilationUnit> parsedFiles = compiler.parseFiles(fileObjects);
                    roots = cleanTrees(roots).reverse();


                    for (JCCompilationUnit unit : parsedFiles)
                        roots = roots.prepend(unit);
                    roots = roots.reverse();

                    // Check for errors after parsing
                    if (compiler.parseErrors()) {
                        errorStatus = true;
                        break runAround;
                    } else {
                        ListBuffer<ClassSymbol> classes = enterNewClassFiles(currentContext);
                        compiler.enterTrees(roots);

                        // annotationsPresentInSource =
                        // collector.findAnnotations(parsedFiles);
                        classes.appendList(getTopLevelClasses(parsedFiles));
                        topLevelClasses  = classes.toList();
                        packageInfoFiles = getPackageInfoFiles(parsedFiles);

                        annotationsPresent = new LinkedHashSet<TypeElement>();
                        for (ClassSymbol classSym : topLevelClasses)
                            annotationComputer.scan(classSym, annotationsPresent);
      for (PackageSymbol pkgSym : packageInfoFiles)
          annotationComputer.scan(pkgSym, annotationsPresent);

                        updateProcessingState(currentContext, false);
                    }
                    // </editor-fold>
                } else
                    break runAround; // No new files
            }
        }
        runLastRound(xout, roundNumber, errorStatus, taskListener);

        compiler.close();
        currentContext = contextForNextRound(currentContext, true);
        compiler = JavaCompiler.instance(currentContext);
        filer.newRound(currentContext, 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.
        */
       errorStatus = errorStatus || messager.errorRaised();


        // Free resources
        this.close();

        if (taskListener != null)
            taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));

        if (errorStatus) {
            compiler.log.nerrors += messager.errorCount();
            if (compiler.errorCount() == 0)
                compiler.log.nerrors++;
        } else if (procOnly) {
            compiler.todo.clear();
        } else { // Final compilation
            compiler.close();
            currentContext = contextForNextRound(currentContext, true);
            compiler = JavaCompiler.instance(currentContext);

            if (true) {
                compiler.enterTrees(cleanTrees(roots));
            } else {
                List<JavaFileObject> fileObjects = List.nil();
                for (JCCompilationUnit unit : roots)
                    fileObjects = fileObjects.prepend(unit.getSourceFile());
                roots = null;
                compiler.enterTrees(compiler.parseFiles(fileObjects.reverse()));
            }
        }
       
        DEBUG.P(0,this,"doProcessing(4)");
        return compiler;
View Full Code Here

        Keywords keywords = Keywords.instance(context);
        assert(keywords != null);
        next.put(Keywords.keywordsKey, keywords);

        JavaCompiler oldCompiler = JavaCompiler.instance(context);
        JavaCompiler nextCompiler = JavaCompiler.instance(next);
        nextCompiler.initRound(oldCompiler);

        JavacTaskImpl task = context.get(JavacTaskImpl.class);
        if (task != null) {
            next.put(JavacTaskImpl.class, task);
            task.updateContext(next);
View Full Code Here

    }
    Context context = new Context();
   
    Options.instance(context).put(OptionName.ENCODING, "UTF-8");
   
    JavaCompiler compiler = new JavaCompiler(context);
    compiler.genEndPos = true;
    compiler.keepComments = true;
   
    @SuppressWarnings("deprecation") JCCompilationUnit cu = compiler.parse(args[0]);
    JcTreePrinter printer = new JcTreePrinter(true);
    printer.visit(cu);
    System.out.println(printer);
  }
View Full Code Here

        TaskListener taskListener = context.get(TaskListener.class);


        AnnotationCollector collector = new AnnotationCollector();

        JavaCompiler compiler = JavaCompiler.instance(context);
        compiler.todo.clear(); // free the compiler's resources

        int round = 0;

        // List<JCAnnotation> annotationsPresentInSource = collector.findAnnotations(roots);
        List<ClassSymbol> topLevelClasses = getTopLevelClasses(roots);

        for (ClassSymbol classSym : classSymbols)
            topLevelClasses = topLevelClasses.prepend(classSym);
        List<PackageSymbol> packageInfoFiles =
      getPackageInfoFiles(roots);

        Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
        for (PackageSymbol psym : pckSymbols)
            specifiedPackages.add(psym);
        this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);

        // Use annotation processing to compute the set of annotations present
        Set<TypeElement> annotationsPresent = new LinkedHashSet<TypeElement>();
        ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
        for (ClassSymbol classSym : topLevelClasses)
            annotationComputer.scan(classSym, annotationsPresent);
  for (PackageSymbol pkgSym : packageInfoFiles)
      annotationComputer.scan(pkgSym, annotationsPresent);

        Context currentContext = context;

        int roundNumber = 0;
        boolean errorStatus = false;

        runAround:
        while(true) {
            if (fatalErrors && compiler.errorCount() != 0) {
                errorStatus = true;
                break runAround;
            }

            this.context = currentContext;
            roundNumber++;
            printRoundInfo(xout, roundNumber, topLevelClasses, annotationsPresent, false);

            if (taskListener != null)
                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));

            try {
    discoverAndRunProcs(currentContext, annotationsPresent, topLevelClasses, packageInfoFiles);
            } finally {
                if (taskListener != null)
                    taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
            }

            /*
             * Processors for round n have run to completion.  Prepare
             * for round (n+1) by checked for errors raised by
             * annotation processors and then checking for syntax
             * errors on any generated source files.
             */
            if (messager.errorRaised()) {
                errorStatus = true;
                break runAround;
            } else {
                if (moreToDo()) {
                    // annotationsPresentInSource = List.nil();
                    annotationsPresent = new LinkedHashSet<TypeElement>();
                    topLevelClasses  = List.nil();
        packageInfoFiles = List.nil();

                    compiler.close();
                    currentContext = contextForNextRound(currentContext, true);

                    JavaFileManager fileManager = currentContext.get(JavaFileManager.class);

                    List<JavaFileObject> fileObjects = List.nil();
                    for (JavaFileObject jfo : filer.getGeneratedSourceFileObjects() ) {
                        fileObjects = fileObjects.prepend(jfo);
                    }


                    compiler = JavaCompiler.instance(currentContext);
                    List<JCCompilationUnit> parsedFiles = compiler.parseFiles(fileObjects);
                    roots = cleanTrees(roots).reverse();


                    for (JCCompilationUnit unit : parsedFiles)
                        roots = roots.prepend(unit);
                    roots = roots.reverse();

                    // Check for errors after parsing
                    if (compiler.parseErrors()) {
                        errorStatus = true;
                        break runAround;
                    } else {
                        ListBuffer<ClassSymbol> classes = enterNewClassFiles(currentContext);
                        compiler.enterTrees(roots);

                        // annotationsPresentInSource =
                        // collector.findAnnotations(parsedFiles);
                        classes.appendList(getTopLevelClasses(parsedFiles));
                        topLevelClasses  = classes.toList();
                        packageInfoFiles = getPackageInfoFiles(parsedFiles);

                        annotationsPresent = new LinkedHashSet<TypeElement>();
                        for (ClassSymbol classSym : topLevelClasses)
                            annotationComputer.scan(classSym, annotationsPresent);
      for (PackageSymbol pkgSym : packageInfoFiles)
          annotationComputer.scan(pkgSym, annotationsPresent);

                        updateProcessingState(currentContext, false);
                    }
                } else
                    break runAround; // No new files
            }
        }
        runLastRound(xout, roundNumber, errorStatus, taskListener);

        compiler.close();
        currentContext = contextForNextRound(currentContext, true);
        compiler = JavaCompiler.instance(currentContext);
        filer.newRound(currentContext, 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.
        */
       errorStatus = errorStatus || messager.errorRaised();


        // Free resources
        this.close();

        if (taskListener != null)
            taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));

        if (errorStatus) {
            compiler.log.nerrors += messager.errorCount();
            if (compiler.errorCount() == 0)
                compiler.log.nerrors++;
        } else if (procOnly) {
            compiler.todo.clear();
        } else { // Final compilation
            compiler.close();
            currentContext = contextForNextRound(currentContext, true);
            compiler = JavaCompiler.instance(currentContext);

            if (true) {
                compiler.enterTrees(cleanTrees(roots));
            } else {
                List<JavaFileObject> fileObjects = List.nil();
                for (JCCompilationUnit unit : roots)
                    fileObjects = fileObjects.prepend(unit.getSourceFile());
                roots = null;
                compiler.enterTrees(compiler.parseFiles(fileObjects.reverse()));
            }
        }

        return compiler;
    }
View Full Code Here

        Keywords keywords = Keywords.instance(context);
        assert(keywords != null);
        next.put(Keywords.keywordsKey, keywords);

        JavaCompiler oldCompiler = JavaCompiler.instance(context);
        JavaCompiler nextCompiler = JavaCompiler.instance(next);
        nextCompiler.initRound(oldCompiler);

        JavacTaskImpl task = context.get(JavacTaskImpl.class);
        if (task != null) {
            next.put(JavacTaskImpl.class, task);
            task.updateContext(next);
View Full Code Here

    }
  }
 
  private void parseWithJavac(Source source) {
    Context context = new Context();
    JavaCompiler compiler = new JavaCompiler(context);
    compiler.genEndPos = true;
    compiler.parse(new ContentBasedJavaFileObject(source.getName(), source.getRawInput()));
  }
View Full Code Here

    Context context = new Context();
   
    Options.instance(context).put(OptionName.ENCODING, "UTF-8");
   
    CommentCatcher catcher = CommentCatcher.create(context);
    JavaCompiler compiler = catcher.getCompiler();
   
    JCCompilationUnit cu = compiler.parse(new ContentBasedJavaFileObject(source.getName(), source.getRawInput()));
    JcTreeConverter converter = new JcTreeConverter();
    converter.visit(cu);
    return converter.getResultWithJavadoc(catcher.getComments(cu));
  }
View Full Code Here

TOP

Related Classes of com.sun.tools.javac.main.JavaCompiler

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.