0N/A/*
929N/A * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
553N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
553N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
553N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
553N/A * or visit www.oracle.com if you need additional information or have any
553N/A * questions.
0N/A */
0N/A
0N/Apackage com.sun.tools.javac.api;
0N/A
0N/Aimport java.io.File;
0N/Aimport java.io.IOException;
110N/Aimport java.nio.CharBuffer;
0N/Aimport java.util.*;
0N/Aimport java.util.concurrent.atomic.AtomicBoolean;
0N/A
0N/Aimport javax.annotation.processing.Processor;
0N/Aimport javax.lang.model.element.Element;
0N/Aimport javax.lang.model.element.TypeElement;
0N/Aimport javax.lang.model.type.TypeMirror;
0N/Aimport javax.tools.*;
0N/A
0N/Aimport com.sun.source.tree.*;
0N/Aimport com.sun.source.util.*;
0N/Aimport com.sun.tools.javac.code.*;
0N/Aimport com.sun.tools.javac.code.Symbol.*;
0N/Aimport com.sun.tools.javac.comp.*;
49N/Aimport com.sun.tools.javac.file.JavacFileManager;
0N/Aimport com.sun.tools.javac.main.*;
0N/Aimport com.sun.tools.javac.model.*;
0N/Aimport com.sun.tools.javac.parser.Parser;
110N/Aimport com.sun.tools.javac.parser.ParserFactory;
0N/Aimport com.sun.tools.javac.tree.*;
0N/Aimport com.sun.tools.javac.tree.JCTree.*;
0N/Aimport com.sun.tools.javac.util.*;
0N/Aimport com.sun.tools.javac.util.List;
0N/Aimport com.sun.tools.javac.main.JavaCompiler;
0N/A
0N/A/**
581N/A * Provides access to functionality specific to the JDK Java Compiler, javac.
0N/A *
580N/A * <p><b>This is NOT part of any supported API.
0N/A * If you write code that depends on this, you do so at your own
0N/A * risk. This code and its internal interfaces are subject to change
0N/A * or deletion without notice.</b></p>
0N/A *
0N/A * @author Peter von der Ah&eacute;
0N/A * @author Jonathan Gibbons
0N/A */
0N/Apublic class JavacTaskImpl extends JavacTask {
945N/A private ClientCodeWrapper ccw;
0N/A private Main compilerMain;
0N/A private JavaCompiler compiler;
135N/A private Locale locale;
0N/A private String[] args;
1137N/A private String[] classNames;
0N/A private Context context;
0N/A private List<JavaFileObject> fileObjects;
0N/A private Map<JavaFileObject, JCCompilationUnit> notYetEntered;
0N/A private ListBuffer<Env<AttrContext>> genList;
0N/A private TaskListener taskListener;
0N/A private AtomicBoolean used = new AtomicBoolean();
0N/A private Iterable<? extends Processor> processors;
0N/A
0N/A private Integer result = null;
0N/A
945N/A JavacTaskImpl(Main compilerMain,
0N/A String[] args,
1137N/A String[] classNames,
0N/A Context context,
0N/A List<JavaFileObject> fileObjects) {
945N/A this.ccw = ClientCodeWrapper.instance(context);
0N/A this.compilerMain = compilerMain;
0N/A this.args = args;
1137N/A this.classNames = classNames;
0N/A this.context = context;
0N/A this.fileObjects = fileObjects;
135N/A setLocale(Locale.getDefault());
0N/A // null checks
0N/A compilerMain.getClass();
0N/A args.getClass();
0N/A fileObjects.getClass();
0N/A }
0N/A
945N/A JavacTaskImpl(Main compilerMain,
0N/A Iterable<String> flags,
0N/A Context context,
0N/A Iterable<String> classes,
0N/A Iterable<? extends JavaFileObject> fileObjects) {
1137N/A this(compilerMain, toArray(flags), toArray(classes), context, toList(fileObjects));
0N/A }
0N/A
1137N/A static private String[] toArray(Iterable<String> iter) {
0N/A ListBuffer<String> result = new ListBuffer<String>();
1137N/A if (iter != null)
1137N/A for (String s : iter)
1137N/A result.append(s);
0N/A return result.toArray(new String[result.length()]);
0N/A }
0N/A
0N/A static private List<JavaFileObject> toList(Iterable<? extends JavaFileObject> fileObjects) {
0N/A if (fileObjects == null)
0N/A return List.nil();
0N/A ListBuffer<JavaFileObject> result = new ListBuffer<JavaFileObject>();
0N/A for (JavaFileObject fo : fileObjects)
0N/A result.append(fo);
0N/A return result.toList();
0N/A }
0N/A
0N/A public Boolean call() {
0N/A if (!used.getAndSet(true)) {
929N/A initContext();
307N/A notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
945N/A compilerMain.setAPIMode(true);
1137N/A result = compilerMain.compile(args, classNames, context, fileObjects, processors);
929N/A cleanup();
0N/A return result == 0;
0N/A } else {
0N/A throw new IllegalStateException("multiple calls to method 'call'");
0N/A }
0N/A }
0N/A
0N/A public void setProcessors(Iterable<? extends Processor> processors) {
0N/A processors.getClass(); // null check
0N/A // not mt-safe
0N/A if (used.get())
0N/A throw new IllegalStateException();
0N/A this.processors = processors;
0N/A }
0N/A
0N/A public void setLocale(Locale locale) {
0N/A if (used.get())
0N/A throw new IllegalStateException();
135N/A this.locale = locale;
0N/A }
0N/A
0N/A private void prepareCompiler() throws IOException {
929N/A if (used.getAndSet(true)) {
929N/A if (compiler == null)
929N/A throw new IllegalStateException();
929N/A } else {
929N/A initContext();
0N/A compilerMain.setOptions(Options.instance(context));
1039N/A compilerMain.filenames = new LinkedHashSet<File>();
1137N/A Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args), classNames);
0N/A if (!filenames.isEmpty())
1039N/A throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
0N/A compiler = JavaCompiler.instance(context);
0N/A compiler.keepComments = true;
0N/A compiler.genEndPos = true;
0N/A // NOTE: this value will be updated after annotation processing
0N/A compiler.initProcessAnnotations(processors);
0N/A notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
0N/A for (JavaFileObject file: fileObjects)
0N/A notYetEntered.put(file, null);
0N/A genList = new ListBuffer<Env<AttrContext>>();
0N/A // endContext will be called when all classes have been generated
0N/A // TODO: should handle the case after each phase if errors have occurred
0N/A args = null;
1137N/A classNames = null;
0N/A }
0N/A }
0N/A
1039N/A <T> String toString(Iterable<T> items, String sep) {
1039N/A String currSep = "";
1039N/A StringBuilder sb = new StringBuilder();
1039N/A for (T item: items) {
1039N/A sb.append(currSep);
1039N/A sb.append(item.toString());
1039N/A currSep = sep;
1039N/A }
1039N/A return sb.toString();
1039N/A }
1039N/A
929N/A private void initContext() {
0N/A context.put(JavacTaskImpl.class, this);
0N/A if (context.get(TaskListener.class) != null)
0N/A context.put(TaskListener.class, (TaskListener)null);
0N/A if (taskListener != null)
945N/A context.put(TaskListener.class, ccw.wrap(taskListener));
135N/A //initialize compiler's default locale
943N/A context.put(Locale.class, locale);
0N/A }
0N/A
929N/A void cleanup() {
929N/A if (compiler != null)
929N/A compiler.close();
929N/A compiler = null;
929N/A compilerMain = null;
929N/A args = null;
1137N/A classNames = null;
929N/A context = null;
929N/A fileObjects = null;
929N/A notYetEntered = null;
0N/A }
0N/A
0N/A /**
0N/A * Construct a JavaFileObject from the given file.
0N/A *
0N/A * <p><b>TODO: this method is useless here</b></p>
0N/A *
0N/A * @param file a file
0N/A * @return a JavaFileObject from the standard file manager.
0N/A */
0N/A public JavaFileObject asJavaFileObject(File file) {
0N/A JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
0N/A return fm.getRegularFile(file);
0N/A }
0N/A
0N/A public void setTaskListener(TaskListener taskListener) {
0N/A this.taskListener = taskListener;
0N/A }
0N/A
0N/A /**
0N/A * Parse the specified files returning a list of abstract syntax trees.
0N/A *
0N/A * @throws java.io.IOException TODO
0N/A * @return a list of abstract syntax trees
0N/A */
0N/A public Iterable<? extends CompilationUnitTree> parse() throws IOException {
0N/A try {
0N/A prepareCompiler();
0N/A List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
0N/A for (JCCompilationUnit unit: units) {
0N/A JavaFileObject file = unit.getSourceFile();
0N/A if (notYetEntered.containsKey(file))
0N/A notYetEntered.put(file, unit);
0N/A }
0N/A return units;
0N/A }
0N/A finally {
0N/A parsed = true;
0N/A if (compiler != null && compiler.log != null)
0N/A compiler.log.flush();
0N/A }
0N/A }
0N/A
0N/A private boolean parsed = false;
0N/A
0N/A /**
0N/A * Translate all the abstract syntax trees to elements.
0N/A *
0N/A * @throws IOException TODO
0N/A * @return a list of elements corresponding to the top level
0N/A * classes in the abstract syntax trees
0N/A */
0N/A public Iterable<? extends TypeElement> enter() throws IOException {
0N/A return enter(null);
0N/A }
0N/A
0N/A /**
0N/A * Translate the given abstract syntax trees to elements.
0N/A *
0N/A * @param trees a list of abstract syntax trees.
0N/A * @throws java.io.IOException TODO
0N/A * @return a list of elements corresponding to the top level
0N/A * classes in the abstract syntax trees
0N/A */
0N/A public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
0N/A throws IOException
0N/A {
0N/A prepareCompiler();
0N/A
0N/A ListBuffer<JCCompilationUnit> roots = null;
0N/A
0N/A if (trees == null) {
0N/A // If there are still files which were specified to be compiled
0N/A // (i.e. in fileObjects) but which have not yet been entered,
0N/A // then we make sure they have been parsed and add them to the
0N/A // list to be entered.
0N/A if (notYetEntered.size() > 0) {
0N/A if (!parsed)
0N/A parse(); // TODO would be nice to specify files needed to be parsed
0N/A for (JavaFileObject file: fileObjects) {
0N/A JCCompilationUnit unit = notYetEntered.remove(file);
0N/A if (unit != null) {
0N/A if (roots == null)
0N/A roots = new ListBuffer<JCCompilationUnit>();
0N/A roots.append(unit);
0N/A }
0N/A }
0N/A notYetEntered.clear();
0N/A }
0N/A }
0N/A else {
0N/A for (CompilationUnitTree cu : trees) {
0N/A if (cu instanceof JCCompilationUnit) {
0N/A if (roots == null)
0N/A roots = new ListBuffer<JCCompilationUnit>();
0N/A roots.append((JCCompilationUnit)cu);
0N/A notYetEntered.remove(cu.getSourceFile());
0N/A }
0N/A else
0N/A throw new IllegalArgumentException(cu.toString());
0N/A }
0N/A }
0N/A
0N/A if (roots == null)
0N/A return List.nil();
0N/A
0N/A try {
0N/A List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
0N/A
0N/A if (notYetEntered.isEmpty())
0N/A compiler = compiler.processAnnotations(units);
0N/A
0N/A ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
0N/A for (JCCompilationUnit unit : units) {
694N/A for (JCTree node : unit.defs) {
694N/A if (node.getTag() == JCTree.CLASSDEF) {
694N/A JCClassDecl cdef = (JCClassDecl) node;
694N/A if (cdef.sym != null) // maybe null if errors in anno processing
694N/A elements.append(cdef.sym);
694N/A }
694N/A }
0N/A }
0N/A return elements.toList();
0N/A }
0N/A finally {
0N/A compiler.log.flush();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Complete all analysis.
0N/A * @throws IOException TODO
0N/A */
0N/A @Override
0N/A public Iterable<? extends Element> analyze() throws IOException {
0N/A return analyze(null);
0N/A }
0N/A
0N/A /**
0N/A * Complete all analysis on the given classes.
0N/A * This can be used to ensure that all compile time errors are reported.
0N/A * The classes must have previously been returned from {@link #enter}.
0N/A * If null is specified, all outstanding classes will be analyzed.
0N/A *
0N/A * @param classes a list of class elements
0N/A */
0N/A // This implementation requires that we open up privileges on JavaCompiler.
0N/A // An alternative implementation would be to move this code to JavaCompiler and
0N/A // wrap it here
0N/A public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
0N/A enter(null); // ensure all classes have been entered
0N/A
0N/A final ListBuffer<Element> results = new ListBuffer<Element>();
0N/A try {
0N/A if (classes == null) {
0N/A handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
0N/A } else {
0N/A Filter f = new Filter() {
0N/A public void process(Env<AttrContext> env) {
0N/A handleFlowResults(compiler.flow(compiler.attribute(env)), results);
0N/A }
0N/A };
0N/A f.run(compiler.todo, classes);
0N/A }
0N/A } finally {
0N/A compiler.log.flush();
0N/A }
0N/A return results;
0N/A }
0N/A // where
69N/A private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
69N/A for (Env<AttrContext> env: queue) {
0N/A switch (env.tree.getTag()) {
0N/A case JCTree.CLASSDEF:
0N/A JCClassDecl cdef = (JCClassDecl) env.tree;
0N/A if (cdef.sym != null)
0N/A elems.append(cdef.sym);
0N/A break;
0N/A case JCTree.TOPLEVEL:
0N/A JCCompilationUnit unit = (JCCompilationUnit) env.tree;
0N/A if (unit.packge != null)
0N/A elems.append(unit.packge);
0N/A break;
0N/A }
0N/A }
69N/A genList.addAll(queue);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Generate code.
0N/A * @throws IOException TODO
0N/A */
0N/A @Override
0N/A public Iterable<? extends JavaFileObject> generate() throws IOException {
0N/A return generate(null);
0N/A }
0N/A
0N/A /**
0N/A * Generate code corresponding to the given classes.
0N/A * The classes must have previously been returned from {@link #enter}.
0N/A * If there are classes outstanding to be analyzed, that will be done before
0N/A * any classes are generated.
0N/A * If null is specified, code will be generated for all outstanding classes.
0N/A *
0N/A * @param classes a list of class elements
0N/A */
0N/A public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
0N/A final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
0N/A try {
0N/A analyze(null); // ensure all classes have been parsed, entered, and analyzed
0N/A
0N/A if (classes == null) {
69N/A compiler.generate(compiler.desugar(genList), results);
0N/A genList.clear();
0N/A }
0N/A else {
0N/A Filter f = new Filter() {
0N/A public void process(Env<AttrContext> env) {
69N/A compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
0N/A }
0N/A };
0N/A f.run(genList, classes);
0N/A }
0N/A if (genList.isEmpty()) {
0N/A compiler.reportDeferredDiagnostics();
929N/A cleanup();
0N/A }
0N/A }
0N/A finally {
929N/A if (compiler != null)
929N/A compiler.log.flush();
0N/A }
0N/A return results;
0N/A }
0N/A
0N/A public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
0N/A // TODO: Should complete attribution if necessary
0N/A Tree last = null;
0N/A for (Tree node : path)
0N/A last = node;
0N/A return ((JCTree)last).type;
0N/A }
0N/A
0N/A public JavacElements getElements() {
0N/A if (context == null)
0N/A throw new IllegalStateException();
0N/A return JavacElements.instance(context);
0N/A }
0N/A
0N/A public JavacTypes getTypes() {
0N/A if (context == null)
0N/A throw new IllegalStateException();
0N/A return JavacTypes.instance(context);
0N/A }
0N/A
0N/A public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
0N/A return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
0N/A }
0N/A
0N/A abstract class Filter {
118N/A void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
0N/A Set<TypeElement> set = new HashSet<TypeElement>();
0N/A for (TypeElement item: classes)
0N/A set.add(item);
0N/A
118N/A ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
118N/A while (list.peek() != null) {
118N/A Env<AttrContext> env = list.remove();
0N/A ClassSymbol csym = env.enclClass.sym;
0N/A if (csym != null && set.contains(csym.outermostClass()))
0N/A process(env);
0N/A else
118N/A defer = defer.append(env);
0N/A }
0N/A
118N/A list.addAll(defer);
0N/A }
0N/A
0N/A abstract void process(Env<AttrContext> env);
0N/A }
0N/A
0N/A /**
580N/A * For internal use only. This method will be
0N/A * removed without warning.
0N/A */
0N/A public Context getContext() {
0N/A return context;
0N/A }
0N/A
0N/A /**
580N/A * For internal use only. This method will be
0N/A * removed without warning.
0N/A */
0N/A public void updateContext(Context newContext) {
0N/A context = newContext;
0N/A }
0N/A
0N/A /**
580N/A * For internal use only. This method will be
0N/A * removed without warning.
0N/A */
0N/A public Type parseType(String expr, TypeElement scope) {
0N/A if (expr == null || expr.equals(""))
0N/A throw new IllegalArgumentException();
0N/A compiler = JavaCompiler.instance(context);
0N/A JavaFileObject prev = compiler.log.useSource(null);
110N/A ParserFactory parserFactory = ParserFactory.instance(context);
0N/A Attr attr = Attr.instance(context);
0N/A try {
110N/A CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
110N/A Parser parser = parserFactory.newParser(buf, false, false, false);
110N/A JCTree tree = parser.parseType();
0N/A return attr.attribType(tree, (Symbol.TypeSymbol)scope);
0N/A } finally {
0N/A compiler.log.useSource(prev);
0N/A }
0N/A }
0N/A
0N/A}