src/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java

Mon, 17 Dec 2012 07:47:05 -0800

author
jjg
date
Mon, 17 Dec 2012 07:47:05 -0800
changeset 1455
75ab654b5cd5
parent 1416
c0f0c41cafa0
child 1569
475eb15dfdad
child 1591
dc8b7aa7cef3
permissions
-rw-r--r--

8004832: Add new doclint package
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.api;
    28 import java.io.File;
    29 import java.io.IOException;
    30 import java.nio.CharBuffer;
    31 import java.util.*;
    32 import java.util.concurrent.atomic.AtomicBoolean;
    34 import javax.annotation.processing.Processor;
    35 import javax.lang.model.element.Element;
    36 import javax.lang.model.element.TypeElement;
    37 import javax.lang.model.type.TypeMirror;
    38 import javax.tools.*;
    40 import com.sun.source.tree.*;
    41 import com.sun.source.util.*;
    42 import com.sun.tools.javac.code.*;
    43 import com.sun.tools.javac.code.Symbol.*;
    44 import com.sun.tools.javac.comp.*;
    45 import com.sun.tools.javac.file.JavacFileManager;
    46 import com.sun.tools.javac.main.*;
    47 import com.sun.tools.javac.main.JavaCompiler;
    48 import com.sun.tools.javac.model.*;
    49 import com.sun.tools.javac.parser.Parser;
    50 import com.sun.tools.javac.parser.ParserFactory;
    51 import com.sun.tools.javac.tree.*;
    52 import com.sun.tools.javac.tree.JCTree.*;
    53 import com.sun.tools.javac.util.*;
    54 import com.sun.tools.javac.util.List;
    56 /**
    57  * Provides access to functionality specific to the JDK Java Compiler, javac.
    58  *
    59  * <p><b>This is NOT part of any supported API.
    60  * If you write code that depends on this, you do so at your own
    61  * risk.  This code and its internal interfaces are subject to change
    62  * or deletion without notice.</b></p>
    63  *
    64  * @author Peter von der Ah&eacute;
    65  * @author Jonathan Gibbons
    66  */
    67 public class JavacTaskImpl extends BasicJavacTask {
    68     private Main compilerMain;
    69     private JavaCompiler compiler;
    70     private Locale locale;
    71     private String[] args;
    72     private String[] classNames;
    73     private List<JavaFileObject> fileObjects;
    74     private Map<JavaFileObject, JCCompilationUnit> notYetEntered;
    75     private ListBuffer<Env<AttrContext>> genList;
    76     private final AtomicBoolean used = new AtomicBoolean();
    77     private Iterable<? extends Processor> processors;
    79     private Main.Result result = null;
    81     JavacTaskImpl(Main compilerMain,
    82                 String[] args,
    83                 String[] classNames,
    84                 Context context,
    85                 List<JavaFileObject> fileObjects) {
    86         super(null, false);
    87         this.compilerMain = compilerMain;
    88         this.args = args;
    89         this.classNames = classNames;
    90         this.context = context;
    91         this.fileObjects = fileObjects;
    92         setLocale(Locale.getDefault());
    93         // null checks
    94         compilerMain.getClass();
    95         args.getClass();
    96         fileObjects.getClass();
    97     }
    99     JavacTaskImpl(Main compilerMain,
   100                 Iterable<String> args,
   101                 Context context,
   102                 Iterable<String> classes,
   103                 Iterable<? extends JavaFileObject> fileObjects) {
   104         this(compilerMain, toArray(args), toArray(classes), context, toList(fileObjects));
   105     }
   107     static private String[] toArray(Iterable<String> iter) {
   108         ListBuffer<String> result = new ListBuffer<String>();
   109         if (iter != null)
   110             for (String s : iter)
   111                 result.append(s);
   112         return result.toArray(new String[result.length()]);
   113     }
   115     static private List<JavaFileObject> toList(Iterable<? extends JavaFileObject> fileObjects) {
   116         if (fileObjects == null)
   117             return List.nil();
   118         ListBuffer<JavaFileObject> result = new ListBuffer<JavaFileObject>();
   119         for (JavaFileObject fo : fileObjects)
   120             result.append(fo);
   121         return result.toList();
   122     }
   124     public Boolean call() {
   125         if (!used.getAndSet(true)) {
   126             initContext();
   127             notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
   128             compilerMain.setAPIMode(true);
   129             result = compilerMain.compile(args, classNames, context, fileObjects, processors);
   130             cleanup();
   131             return result.isOK();
   132         } else {
   133             throw new IllegalStateException("multiple calls to method 'call'");
   134         }
   135     }
   137     public void setProcessors(Iterable<? extends Processor> processors) {
   138         processors.getClass(); // null check
   139         // not mt-safe
   140         if (used.get())
   141             throw new IllegalStateException();
   142         this.processors = processors;
   143     }
   145     public void setLocale(Locale locale) {
   146         if (used.get())
   147             throw new IllegalStateException();
   148         this.locale = locale;
   149     }
   151     private void prepareCompiler() throws IOException {
   152         if (used.getAndSet(true)) {
   153             if (compiler == null)
   154                 throw new IllegalStateException();
   155         } else {
   156             initContext();
   157             compilerMain.setOptions(Options.instance(context));
   158             compilerMain.filenames = new LinkedHashSet<File>();
   159             Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args), classNames);
   160             if (!filenames.isEmpty())
   161                 throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
   162             compiler = JavaCompiler.instance(context);
   163             compiler.keepComments = true;
   164             compiler.genEndPos = true;
   165             // NOTE: this value will be updated after annotation processing
   166             compiler.initProcessAnnotations(processors);
   167             notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
   168             for (JavaFileObject file: fileObjects)
   169                 notYetEntered.put(file, null);
   170             genList = new ListBuffer<Env<AttrContext>>();
   171             // endContext will be called when all classes have been generated
   172             // TODO: should handle the case after each phase if errors have occurred
   173             args = null;
   174             classNames = null;
   175         }
   176     }
   178     <T> String toString(Iterable<T> items, String sep) {
   179         String currSep = "";
   180         StringBuilder sb = new StringBuilder();
   181         for (T item: items) {
   182             sb.append(currSep);
   183             sb.append(item.toString());
   184             currSep = sep;
   185         }
   186         return sb.toString();
   187     }
   189     private void initContext() {
   190         context.put(JavacTask.class, this);
   191         //initialize compiler's default locale
   192         context.put(Locale.class, locale);
   193     }
   195     void cleanup() {
   196         if (compiler != null)
   197             compiler.close();
   198         compiler = null;
   199         compilerMain = null;
   200         args = null;
   201         classNames = null;
   202         context = null;
   203         fileObjects = null;
   204         notYetEntered = null;
   205     }
   207     /**
   208      * Construct a JavaFileObject from the given file.
   209      *
   210      * <p><b>TODO: this method is useless here</b></p>
   211      *
   212      * @param file a file
   213      * @return a JavaFileObject from the standard file manager.
   214      */
   215     public JavaFileObject asJavaFileObject(File file) {
   216         JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
   217         return fm.getRegularFile(file);
   218     }
   220     /**
   221      * Parse the specified files returning a list of abstract syntax trees.
   222      *
   223      * @throws java.io.IOException TODO
   224      * @return a list of abstract syntax trees
   225      */
   226     public Iterable<? extends CompilationUnitTree> parse() throws IOException {
   227         try {
   228             prepareCompiler();
   229             List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
   230             for (JCCompilationUnit unit: units) {
   231                 JavaFileObject file = unit.getSourceFile();
   232                 if (notYetEntered.containsKey(file))
   233                     notYetEntered.put(file, unit);
   234             }
   235             return units;
   236         }
   237         finally {
   238             parsed = true;
   239             if (compiler != null && compiler.log != null)
   240                 compiler.log.flush();
   241         }
   242     }
   244     private boolean parsed = false;
   246     /**
   247      * Translate all the abstract syntax trees to elements.
   248      *
   249      * @throws IOException TODO
   250      * @return a list of elements corresponding to the top level
   251      * classes in the abstract syntax trees
   252      */
   253     public Iterable<? extends TypeElement> enter() throws IOException {
   254         return enter(null);
   255     }
   257     /**
   258      * Translate the given abstract syntax trees to elements.
   259      *
   260      * @param trees a list of abstract syntax trees.
   261      * @throws java.io.IOException TODO
   262      * @return a list of elements corresponding to the top level
   263      * classes in the abstract syntax trees
   264      */
   265     public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
   266         throws IOException
   267     {
   268         if (trees == null && notYetEntered != null && notYetEntered.isEmpty())
   269             return List.nil();
   271         prepareCompiler();
   273         ListBuffer<JCCompilationUnit> roots = null;
   275         if (trees == null) {
   276             // If there are still files which were specified to be compiled
   277             // (i.e. in fileObjects) but which have not yet been entered,
   278             // then we make sure they have been parsed and add them to the
   279             // list to be entered.
   280             if (notYetEntered.size() > 0) {
   281                 if (!parsed)
   282                     parse(); // TODO would be nice to specify files needed to be parsed
   283                 for (JavaFileObject file: fileObjects) {
   284                     JCCompilationUnit unit = notYetEntered.remove(file);
   285                     if (unit != null) {
   286                         if (roots == null)
   287                             roots = new ListBuffer<JCCompilationUnit>();
   288                         roots.append(unit);
   289                     }
   290                 }
   291                 notYetEntered.clear();
   292             }
   293         }
   294         else {
   295             for (CompilationUnitTree cu : trees) {
   296                 if (cu instanceof JCCompilationUnit) {
   297                     if (roots == null)
   298                         roots = new ListBuffer<JCCompilationUnit>();
   299                     roots.append((JCCompilationUnit)cu);
   300                     notYetEntered.remove(cu.getSourceFile());
   301                 }
   302                 else
   303                     throw new IllegalArgumentException(cu.toString());
   304             }
   305         }
   307         if (roots == null)
   308             return List.nil();
   310         try {
   311             List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
   313             if (notYetEntered.isEmpty())
   314                 compiler = compiler.processAnnotations(units);
   316             ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
   317             for (JCCompilationUnit unit : units) {
   318                 for (JCTree node : unit.defs) {
   319                     if (node.hasTag(JCTree.Tag.CLASSDEF)) {
   320                         JCClassDecl cdef = (JCClassDecl) node;
   321                         if (cdef.sym != null) // maybe null if errors in anno processing
   322                             elements.append(cdef.sym);
   323                     }
   324                 }
   325             }
   326             return elements.toList();
   327         }
   328         finally {
   329             compiler.log.flush();
   330         }
   331     }
   333     /**
   334      * Complete all analysis.
   335      * @throws IOException TODO
   336      */
   337     @Override
   338     public Iterable<? extends Element> analyze() throws IOException {
   339         return analyze(null);
   340     }
   342     /**
   343      * Complete all analysis on the given classes.
   344      * This can be used to ensure that all compile time errors are reported.
   345      * The classes must have previously been returned from {@link #enter}.
   346      * If null is specified, all outstanding classes will be analyzed.
   347      *
   348      * @param classes a list of class elements
   349      */
   350     // This implementation requires that we open up privileges on JavaCompiler.
   351     // An alternative implementation would be to move this code to JavaCompiler and
   352     // wrap it here
   353     public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
   354         enter(null);  // ensure all classes have been entered
   356         final ListBuffer<Element> results = new ListBuffer<Element>();
   357         try {
   358             if (classes == null) {
   359                 handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
   360             } else {
   361                 Filter f = new Filter() {
   362                     public void process(Env<AttrContext> env) {
   363                         handleFlowResults(compiler.flow(compiler.attribute(env)), results);
   364                     }
   365                 };
   366                 f.run(compiler.todo, classes);
   367             }
   368         } finally {
   369             compiler.log.flush();
   370         }
   371         return results;
   372     }
   373     // where
   374         private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
   375             for (Env<AttrContext> env: queue) {
   376                 switch (env.tree.getTag()) {
   377                     case CLASSDEF:
   378                         JCClassDecl cdef = (JCClassDecl) env.tree;
   379                         if (cdef.sym != null)
   380                             elems.append(cdef.sym);
   381                         break;
   382                     case TOPLEVEL:
   383                         JCCompilationUnit unit = (JCCompilationUnit) env.tree;
   384                         if (unit.packge != null)
   385                             elems.append(unit.packge);
   386                         break;
   387                 }
   388             }
   389             genList.addAll(queue);
   390         }
   393     /**
   394      * Generate code.
   395      * @throws IOException TODO
   396      */
   397     @Override
   398     public Iterable<? extends JavaFileObject> generate() throws IOException {
   399         return generate(null);
   400     }
   402     /**
   403      * Generate code corresponding to the given classes.
   404      * The classes must have previously been returned from {@link #enter}.
   405      * If there are classes outstanding to be analyzed, that will be done before
   406      * any classes are generated.
   407      * If null is specified, code will be generated for all outstanding classes.
   408      *
   409      * @param classes a list of class elements
   410      */
   411     public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
   412         final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
   413         try {
   414             analyze(null);  // ensure all classes have been parsed, entered, and analyzed
   416             if (classes == null) {
   417                 compiler.generate(compiler.desugar(genList), results);
   418                 genList.clear();
   419             }
   420             else {
   421                 Filter f = new Filter() {
   422                         public void process(Env<AttrContext> env) {
   423                             compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
   424                         }
   425                     };
   426                 f.run(genList, classes);
   427             }
   428             if (genList.isEmpty()) {
   429                 compiler.reportDeferredDiagnostics();
   430                 cleanup();
   431             }
   432         }
   433         finally {
   434             if (compiler != null)
   435                 compiler.log.flush();
   436         }
   437         return results;
   438     }
   440     public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
   441         // TODO: Should complete attribution if necessary
   442         Tree last = null;
   443         for (Tree node : path)
   444             last = node;
   445         return ((JCTree)last).type;
   446     }
   448     public JavacElements getElements() {
   449         if (context == null)
   450             throw new IllegalStateException();
   451         return JavacElements.instance(context);
   452     }
   454     public JavacTypes getTypes() {
   455         if (context == null)
   456             throw new IllegalStateException();
   457         return JavacTypes.instance(context);
   458     }
   460     public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
   461         return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
   462     }
   464     abstract class Filter {
   465         void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
   466             Set<TypeElement> set = new HashSet<TypeElement>();
   467             for (TypeElement item: classes)
   468                 set.add(item);
   470             ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
   471             while (list.peek() != null) {
   472                 Env<AttrContext> env = list.remove();
   473                 ClassSymbol csym = env.enclClass.sym;
   474                 if (csym != null && set.contains(csym.outermostClass()))
   475                     process(env);
   476                 else
   477                     defer = defer.append(env);
   478             }
   480             list.addAll(defer);
   481         }
   483         abstract void process(Env<AttrContext> env);
   484     }
   486     /**
   487      * For internal use only.  This method will be
   488      * removed without warning.
   489      */
   490     public Type parseType(String expr, TypeElement scope) {
   491         if (expr == null || expr.equals(""))
   492             throw new IllegalArgumentException();
   493         compiler = JavaCompiler.instance(context);
   494         JavaFileObject prev = compiler.log.useSource(null);
   495         ParserFactory parserFactory = ParserFactory.instance(context);
   496         Attr attr = Attr.instance(context);
   497         try {
   498             CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
   499             Parser parser = parserFactory.newParser(buf, false, false, false);
   500             JCTree tree = parser.parseType();
   501             return attr.attribType(tree, (Symbol.TypeSymbol)scope);
   502         } finally {
   503             compiler.log.useSource(prev);
   504         }
   505     }
   507 }

mercurial