duke@1: /*
jjg@1210: * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
duke@1: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@1: *
duke@1: * This code is free software; you can redistribute it and/or modify it
duke@1: * under the terms of the GNU General Public License version 2 only, as
ohair@554: * published by the Free Software Foundation. Oracle designates this
duke@1: * particular file as subject to the "Classpath" exception as provided
ohair@554: * by Oracle in the LICENSE file that accompanied this code.
duke@1: *
duke@1: * This code is distributed in the hope that it will be useful, but WITHOUT
duke@1: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@1: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@1: * version 2 for more details (a copy is included in the LICENSE file that
duke@1: * accompanied this code).
duke@1: *
duke@1: * You should have received a copy of the GNU General Public License version
duke@1: * 2 along with this work; if not, write to the Free Software Foundation,
duke@1: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@1: *
ohair@554: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@554: * or visit www.oracle.com if you need additional information or have any
ohair@554: * questions.
duke@1: */
duke@1:
duke@1: package com.sun.tools.javac.processing;
duke@1:
jjg@50: import java.io.Closeable;
jjg@50: import java.io.File;
jjg@50: import java.io.PrintWriter;
jjg@944: import java.io.StringWriter;
jjg@50: import java.net.MalformedURLException;
jjg@1210: import java.net.URL;
jjg@1210: import java.util.*;
jjg@1210: import java.util.regex.*;
duke@1:
duke@1: import javax.annotation.processing.*;
duke@1: import javax.lang.model.SourceVersion;
duke@1: import javax.lang.model.element.AnnotationMirror;
duke@1: import javax.lang.model.element.Element;
jjg@1210: import javax.lang.model.element.PackageElement;
duke@1: import javax.lang.model.element.TypeElement;
duke@1: import javax.lang.model.util.*;
jjg@1210: import javax.tools.DiagnosticListener;
duke@1: import javax.tools.JavaFileManager;
jjg@1210: import javax.tools.JavaFileObject;
duke@1: import javax.tools.StandardJavaFileManager;
jjg@1210: import static javax.tools.StandardLocation.*;
jjg@50:
jjg@1210: import com.sun.source.util.JavacTask;
jjg@50: import com.sun.source.util.TaskEvent;
jjg@1334: import com.sun.tools.javac.api.BasicJavacTask;
jjg@722: import com.sun.tools.javac.api.JavacTrees;
jjg@1210: import com.sun.tools.javac.api.MultiTaskListener;
jjg@50: import com.sun.tools.javac.code.*;
jjg@50: import com.sun.tools.javac.code.Symbol.*;
jjg@872: import com.sun.tools.javac.file.FSInfo;
jjg@50: import com.sun.tools.javac.file.JavacFileManager;
jjg@50: import com.sun.tools.javac.jvm.*;
jjg@952: import com.sun.tools.javac.jvm.ClassReader.BadClassFile;
jjg@50: import com.sun.tools.javac.main.JavaCompiler;
jjg@310: import com.sun.tools.javac.main.JavaCompiler.CompileState;
jjg@50: import com.sun.tools.javac.model.JavacElements;
jjg@50: import com.sun.tools.javac.model.JavacTypes;
jjg@50: import com.sun.tools.javac.parser.*;
jjg@50: import com.sun.tools.javac.tree.*;
jjg@50: import com.sun.tools.javac.tree.JCTree.*;
jjg@50: import com.sun.tools.javac.util.Abort;
jjg@816: import com.sun.tools.javac.util.Assert;
jjg@946: import com.sun.tools.javac.util.ClientCodeException;
jjg@50: import com.sun.tools.javac.util.Context;
jjg@483: import com.sun.tools.javac.util.Convert;
jjg@663: import com.sun.tools.javac.util.JCDiagnostic;
jjg@1210: import com.sun.tools.javac.util.JavacMessages;
jjg@50: import com.sun.tools.javac.util.List;
jjg@50: import com.sun.tools.javac.util.Log;
jjg@50: import com.sun.tools.javac.util.Name;
jjg@113: import com.sun.tools.javac.util.Names;
jjg@50: import com.sun.tools.javac.util.Options;
jjg@1210: import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
jjg@1210: import static com.sun.tools.javac.main.Option.*;
jjg@664: import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
duke@1:
duke@1: /**
duke@1: * Objects of this class hold and manage the state needed to support
duke@1: * annotation processing.
duke@1: *
jjg@581: *
This is NOT part of any supported API.
duke@1: * If you write code that depends on this, you do so at your own risk.
duke@1: * This code and its internal interfaces are subject to change or
duke@1: * deletion without notice.
duke@1: */
duke@1: public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
duke@1: Options options;
duke@1:
duke@1: private final boolean printProcessorInfo;
duke@1: private final boolean printRounds;
duke@1: private final boolean verbose;
duke@1: private final boolean lint;
duke@1: private final boolean fatalErrors;
jjg@614: private final boolean werror;
jjg@664: private final boolean showResolveErrors;
duke@1:
duke@1: private final JavacFiler filer;
duke@1: private final JavacMessager messager;
duke@1: private final JavacElements elementUtils;
duke@1: private final JavacTypes typeUtils;
duke@1:
duke@1: /**
duke@1: * Holds relevant state history of which processors have been
duke@1: * used.
duke@1: */
duke@1: private DiscoveredProcessors discoveredProcs;
duke@1:
duke@1: /**
duke@1: * Map of processor-specific options.
duke@1: */
duke@1: private final Map processorOptions;
duke@1:
duke@1: /**
duke@1: */
duke@1: private final Set unmatchedProcessorOptions;
duke@1:
duke@1: /**
duke@1: * Annotations implicitly processed and claimed by javac.
duke@1: */
duke@1: private final Set platformAnnotations;
duke@1:
duke@1: /**
duke@1: * Set of packages given on command line.
duke@1: */
duke@1: private Set specifiedPackages = Collections.emptySet();
duke@1:
duke@1: /** The log to be used for error reporting.
duke@1: */
duke@1: Log log;
duke@1:
jjg@663: /** Diagnostic factory.
jjg@663: */
jjg@663: JCDiagnostic.Factory diags;
jjg@663:
duke@1: /**
duke@1: * Source level of the compile.
duke@1: */
duke@1: Source source;
duke@1:
jjg@372: private ClassLoader processorClassLoader;
jjg@1416: private SecurityException processorClassLoaderException;
jjg@372:
mcimadamore@136: /**
mcimadamore@136: * JavacMessages object used for localization
mcimadamore@136: */
mcimadamore@136: private JavacMessages messages;
mcimadamore@136:
jjg@1210: private MultiTaskListener taskListener;
jjg@1210:
duke@1: private Context context;
duke@1:
jjg@1416: /** Get the JavacProcessingEnvironment instance for this context. */
jjg@1416: public static JavacProcessingEnvironment instance(Context context) {
jjg@1416: JavacProcessingEnvironment instance = context.get(JavacProcessingEnvironment.class);
jjg@1416: if (instance == null)
jjg@1416: instance = new JavacProcessingEnvironment(context);
jjg@1416: return instance;
jjg@1416: }
jjg@1416:
jjg@1416: protected JavacProcessingEnvironment(Context context) {
duke@1: this.context = context;
duke@1: log = Log.instance(context);
duke@1: source = Source.instance(context);
jjg@663: diags = JCDiagnostic.Factory.instance(context);
jjg@663: options = Options.instance(context);
jjg@700: printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
jjg@700: printRounds = options.isSet(XPRINTROUNDS);
jjg@700: verbose = options.isSet(VERBOSE);
jjg@700: lint = Lint.instance(context).isEnabled(PROCESSING);
jjg@1340: if (options.isSet(PROC, "only") || options.isSet(XPRINT)) {
jjg@1340: JavaCompiler compiler = JavaCompiler.instance(context);
jjg@1340: compiler.shouldStopPolicyIfNoError = CompileState.PROCESS;
jjg@1340: }
jjg@700: fatalErrors = options.isSet("fatalEnterError");
jjg@700: showResolveErrors = options.isSet("showResolveErrors");
jjg@700: werror = options.isSet(WERROR);
duke@1: platformAnnotations = initPlatformAnnotations();
duke@1:
jjg@706: // Initialize services before any processors are initialized
duke@1: // in case processors use them.
duke@1: filer = new JavacFiler(context);
duke@1: messager = new JavacMessager(context, this);
jjg@706: elementUtils = JavacElements.instance(context);
jjg@706: typeUtils = JavacTypes.instance(context);
duke@1: processorOptions = initProcessorOptions(context);
duke@1: unmatchedProcessorOptions = initUnmatchedProcessorOptions();
mcimadamore@136: messages = JavacMessages.instance(context);
jjg@1210: taskListener = MultiTaskListener.instance(context);
jjg@1416: initProcessorClassLoader();
jjg@1416: }
jjg@1416:
jjg@1416: public void setProcessors(Iterable extends Processor> processors) {
jjg@1416: Assert.checkNull(discoveredProcs);
duke@1: initProcessorIterator(context, processors);
duke@1: }
duke@1:
duke@1: private Set initPlatformAnnotations() {
duke@1: Set platformAnnotations = new HashSet();
duke@1: platformAnnotations.add("java.lang.Deprecated");
duke@1: platformAnnotations.add("java.lang.Override");
duke@1: platformAnnotations.add("java.lang.SuppressWarnings");
duke@1: platformAnnotations.add("java.lang.annotation.Documented");
duke@1: platformAnnotations.add("java.lang.annotation.Inherited");
duke@1: platformAnnotations.add("java.lang.annotation.Retention");
duke@1: platformAnnotations.add("java.lang.annotation.Target");
duke@1: return Collections.unmodifiableSet(platformAnnotations);
duke@1: }
duke@1:
jjg@1416: private void initProcessorClassLoader() {
jjg@1416: JavaFileManager fileManager = context.get(JavaFileManager.class);
jjg@1416: try {
jjg@1416: // If processorpath is not explicitly set, use the classpath.
jjg@1416: processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
jjg@1416: ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
jjg@1416: : fileManager.getClassLoader(CLASS_PATH);
jjg@1416:
jjg@1416: if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
jjg@1416: JavaCompiler compiler = JavaCompiler.instance(context);
jjg@1416: compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
jjg@1416: }
jjg@1416: } catch (SecurityException e) {
jjg@1416: processorClassLoaderException = e;
jjg@1416: }
jjg@1416: }
jjg@1416:
duke@1: private void initProcessorIterator(Context context, Iterable extends Processor> processors) {
duke@1: Log log = Log.instance(context);
duke@1: Iterator extends Processor> processorIterator;
duke@1:
jjg@700: if (options.isSet(XPRINT)) {
duke@1: try {
duke@1: Processor processor = PrintingProcessor.class.newInstance();
duke@1: processorIterator = List.of(processor).iterator();
duke@1: } catch (Throwable t) {
duke@1: AssertionError assertError =
duke@1: new AssertionError("Problem instantiating PrintingProcessor.");
duke@1: assertError.initCause(t);
duke@1: throw assertError;
duke@1: }
duke@1: } else if (processors != null) {
duke@1: processorIterator = processors.iterator();
duke@1: } else {
jjg@700: String processorNames = options.get(PROCESSOR);
jjg@1416: if (processorClassLoaderException == null) {
duke@1: /*
duke@1: * If the "-processor" option is used, search the appropriate
duke@1: * path for the named class. Otherwise, use a service
duke@1: * provider mechanism to create the processor iterator.
duke@1: */
duke@1: if (processorNames != null) {
jjg@372: processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
duke@1: } else {
jjg@372: processorIterator = new ServiceIterator(processorClassLoader, log);
duke@1: }
jjg@1416: } else {
duke@1: /*
duke@1: * A security exception will occur if we can't create a classloader.
duke@1: * Ignore the exception if, with hindsight, we didn't need it anyway
duke@1: * (i.e. no processor was specified either explicitly, or implicitly,
duke@1: * in service configuration file.) Otherwise, we cannot continue.
duke@1: */
jjg@1416: processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader",
jjg@1416: processorClassLoaderException);
duke@1: }
duke@1: }
duke@1: discoveredProcs = new DiscoveredProcessors(processorIterator);
duke@1: }
duke@1:
duke@1: /**
duke@1: * Returns an empty processor iterator if no processors are on the
duke@1: * relevant path, otherwise if processors are present, logs an
duke@1: * error. Called when a service loader is unavailable for some
duke@1: * reason, either because a service loader class cannot be found
duke@1: * or because a security policy prevents class loaders from being
duke@1: * created.
duke@1: *
duke@1: * @param key The resource key to use to log an error message
duke@1: * @param e If non-null, pass this exception to Abort
duke@1: */
duke@1: private Iterator handleServiceLoaderUnavailability(String key, Exception e) {
duke@1: JavaFileManager fileManager = context.get(JavaFileManager.class);
duke@1:
duke@1: if (fileManager instanceof JavacFileManager) {
duke@1: StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
duke@1: Iterable extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
duke@1: ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
duke@1: : standardFileManager.getLocation(CLASS_PATH);
duke@1:
jjg@700: if (needClassLoader(options.get(PROCESSOR), workingPath) )
duke@1: handleException(key, e);
duke@1:
duke@1: } else {
duke@1: handleException(key, e);
duke@1: }
duke@1:
duke@1: java.util.List pl = Collections.emptyList();
duke@1: return pl.iterator();
duke@1: }
duke@1:
duke@1: /**
duke@1: * Handle a security exception thrown during initializing the
duke@1: * Processor iterator.
duke@1: */
duke@1: private void handleException(String key, Exception e) {
duke@1: if (e != null) {
duke@1: log.error(key, e.getLocalizedMessage());
duke@1: throw new Abort(e);
duke@1: } else {
duke@1: log.error(key);
duke@1: throw new Abort();
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Use a service loader appropriate for the platform to provide an
darcy@1048: * iterator over annotations processors; fails if a loader is
darcy@1048: * needed but unavailable.
duke@1: */
duke@1: private class ServiceIterator implements Iterator {
darcy@1048: private Iterator iterator;
duke@1: private Log log;
darcy@1048: private ServiceLoader loader;
duke@1:
duke@1: ServiceIterator(ClassLoader classLoader, Log log) {
duke@1: this.log = log;
duke@1: try {
duke@1: try {
darcy@1048: loader = ServiceLoader.load(Processor.class, classLoader);
darcy@1048: this.iterator = loader.iterator();
darcy@1048: } catch (Exception e) {
darcy@1048: // Fail softly if a loader is not actually needed.
darcy@1048: this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
duke@1: }
duke@1: } catch (Throwable t) {
duke@1: log.error("proc.service.problem");
duke@1: throw new Abort(t);
duke@1: }
duke@1: }
duke@1:
duke@1: public boolean hasNext() {
duke@1: try {
duke@1: return iterator.hasNext();
darcy@1048: } catch(ServiceConfigurationError sce) {
darcy@1048: log.error("proc.bad.config.file", sce.getLocalizedMessage());
darcy@1048: throw new Abort(sce);
duke@1: } catch (Throwable t) {
duke@1: throw new Abort(t);
duke@1: }
duke@1: }
duke@1:
duke@1: public Processor next() {
duke@1: try {
darcy@1048: return iterator.next();
darcy@1048: } catch (ServiceConfigurationError sce) {
darcy@1048: log.error("proc.bad.config.file", sce.getLocalizedMessage());
darcy@1048: throw new Abort(sce);
duke@1: } catch (Throwable t) {
duke@1: throw new Abort(t);
duke@1: }
duke@1: }
duke@1:
duke@1: public void remove() {
duke@1: throw new UnsupportedOperationException();
duke@1: }
darcy@382:
darcy@382: public void close() {
darcy@1048: if (loader != null) {
darcy@382: try {
darcy@1048: loader.reload();
darcy@382: } catch(Exception e) {
darcy@382: ; // Ignore problems during a call to reload.
darcy@382: }
darcy@382: }
darcy@382: }
duke@1: }
duke@1:
duke@1:
duke@1: private static class NameProcessIterator implements Iterator {
duke@1: Processor nextProc = null;
duke@1: Iterator names;
duke@1: ClassLoader processorCL;
duke@1: Log log;
duke@1:
duke@1: NameProcessIterator(String names, ClassLoader processorCL, Log log) {
duke@1: this.names = Arrays.asList(names.split(",")).iterator();
duke@1: this.processorCL = processorCL;
duke@1: this.log = log;
duke@1: }
duke@1:
duke@1: public boolean hasNext() {
duke@1: if (nextProc != null)
duke@1: return true;
duke@1: else {
duke@1: if (!names.hasNext())
duke@1: return false;
duke@1: else {
duke@1: String processorName = names.next();
duke@1:
duke@1: Processor processor;
duke@1: try {
duke@1: try {
duke@1: processor =
duke@1: (Processor) (processorCL.loadClass(processorName).newInstance());
duke@1: } catch (ClassNotFoundException cnfe) {
duke@1: log.error("proc.processor.not.found", processorName);
duke@1: return false;
duke@1: } catch (ClassCastException cce) {
duke@1: log.error("proc.processor.wrong.type", processorName);
duke@1: return false;
duke@1: } catch (Exception e ) {
duke@1: log.error("proc.processor.cant.instantiate", processorName);
duke@1: return false;
duke@1: }
jjg@946: } catch(ClientCodeException e) {
jjg@946: throw e;
duke@1: } catch(Throwable t) {
duke@1: throw new AnnotationProcessingError(t);
duke@1: }
duke@1: nextProc = processor;
duke@1: return true;
duke@1: }
duke@1:
duke@1: }
duke@1: }
duke@1:
duke@1: public Processor next() {
duke@1: if (hasNext()) {
duke@1: Processor p = nextProc;
duke@1: nextProc = null;
duke@1: return p;
duke@1: } else
duke@1: throw new NoSuchElementException();
duke@1: }
duke@1:
duke@1: public void remove () {
duke@1: throw new UnsupportedOperationException();
duke@1: }
duke@1: }
duke@1:
duke@1: public boolean atLeastOneProcessor() {
duke@1: return discoveredProcs.iterator().hasNext();
duke@1: }
duke@1:
duke@1: private Map initProcessorOptions(Context context) {
duke@1: Options options = Options.instance(context);
duke@1: Set keySet = options.keySet();
duke@1: Map tempOptions = new LinkedHashMap();
duke@1:
duke@1: for(String key : keySet) {
duke@1: if (key.startsWith("-A") && key.length() > 2) {
duke@1: int sepIndex = key.indexOf('=');
duke@1: String candidateKey = null;
duke@1: String candidateValue = null;
duke@1:
duke@1: if (sepIndex == -1)
duke@1: candidateKey = key.substring(2);
duke@1: else if (sepIndex >= 3) {
duke@1: candidateKey = key.substring(2, sepIndex);
duke@1: candidateValue = (sepIndex < key.length()-1)?
duke@1: key.substring(sepIndex+1) : null;
duke@1: }
duke@1: tempOptions.put(candidateKey, candidateValue);
duke@1: }
duke@1: }
duke@1:
duke@1: return Collections.unmodifiableMap(tempOptions);
duke@1: }
duke@1:
duke@1: private Set initUnmatchedProcessorOptions() {
duke@1: Set unmatchedProcessorOptions = new HashSet();
duke@1: unmatchedProcessorOptions.addAll(processorOptions.keySet());
duke@1: return unmatchedProcessorOptions;
duke@1: }
duke@1:
duke@1: /**
duke@1: * State about how a processor has been used by the tool. If a
duke@1: * processor has been used on a prior round, its process method is
duke@1: * called on all subsequent rounds, perhaps with an empty set of
jjg@1340: * annotations to process. The {@code annotationSupported} method
duke@1: * caches the supported annotation information from the first (and
duke@1: * only) getSupportedAnnotationTypes call to the processor.
duke@1: */
duke@1: static class ProcessorState {
duke@1: public Processor processor;
duke@1: public boolean contributed;
duke@1: private ArrayList supportedAnnotationPatterns;
duke@1: private ArrayList supportedOptionNames;
duke@1:
duke@1: ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
duke@1: processor = p;
duke@1: contributed = false;
duke@1:
duke@1: try {
duke@1: processor.init(env);
duke@1:
duke@1: checkSourceVersionCompatibility(source, log);
duke@1:
duke@1: supportedAnnotationPatterns = new ArrayList();
duke@1: for (String importString : processor.getSupportedAnnotationTypes()) {
duke@1: supportedAnnotationPatterns.add(importStringToPattern(importString,
duke@1: processor,
duke@1: log));
duke@1: }
duke@1:
duke@1: supportedOptionNames = new ArrayList();
duke@1: for (String optionName : processor.getSupportedOptions() ) {
duke@1: if (checkOptionName(optionName, log))
duke@1: supportedOptionNames.add(optionName);
duke@1: }
duke@1:
jjg@946: } catch (ClientCodeException e) {
jjg@946: throw e;
duke@1: } catch (Throwable t) {
duke@1: throw new AnnotationProcessingError(t);
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Checks whether or not a processor's source version is
duke@1: * compatible with the compilation source version. The
duke@1: * processor's source version needs to be greater than or
duke@1: * equal to the source version of the compile.
duke@1: */
duke@1: private void checkSourceVersionCompatibility(Source source, Log log) {
duke@1: SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
duke@1:
duke@1: if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) {
duke@1: log.warning("proc.processor.incompatible.source.version",
duke@1: procSourceVersion,
duke@1: processor.getClass().getName(),
duke@1: source.name);
duke@1: }
duke@1: }
duke@1:
duke@1: private boolean checkOptionName(String optionName, Log log) {
duke@1: boolean valid = isValidOptionName(optionName);
duke@1: if (!valid)
duke@1: log.error("proc.processor.bad.option.name",
duke@1: optionName,
duke@1: processor.getClass().getName());
duke@1: return valid;
duke@1: }
duke@1:
duke@1: public boolean annotationSupported(String annotationName) {
duke@1: for(Pattern p: supportedAnnotationPatterns) {
duke@1: if (p.matcher(annotationName).matches())
duke@1: return true;
duke@1: }
duke@1: return false;
duke@1: }
duke@1:
duke@1: /**
duke@1: * Remove options that are matched by this processor.
duke@1: */
duke@1: public void removeSupportedOptions(Set unmatchedProcessorOptions) {
duke@1: unmatchedProcessorOptions.removeAll(supportedOptionNames);
duke@1: }
duke@1: }
duke@1:
duke@1: // TODO: These two classes can probably be rewritten better...
duke@1: /**
duke@1: * This class holds information about the processors that have
duke@1: * been discoverd so far as well as the means to discover more, if
duke@1: * necessary. A single iterator should be used per round of
duke@1: * annotation processing. The iterator first visits already
darcy@382: * discovered processors then fails over to the service provider
duke@1: * mechanism if additional queries are made.
duke@1: */
duke@1: class DiscoveredProcessors implements Iterable {
duke@1:
duke@1: class ProcessorStateIterator implements Iterator {
duke@1: DiscoveredProcessors psi;
duke@1: Iterator innerIter;
duke@1: boolean onProcInterator;
duke@1:
duke@1: ProcessorStateIterator(DiscoveredProcessors psi) {
duke@1: this.psi = psi;
duke@1: this.innerIter = psi.procStateList.iterator();
duke@1: this.onProcInterator = false;
duke@1: }
duke@1:
duke@1: public ProcessorState next() {
duke@1: if (!onProcInterator) {
duke@1: if (innerIter.hasNext())
duke@1: return innerIter.next();
duke@1: else
duke@1: onProcInterator = true;
duke@1: }
duke@1:
duke@1: if (psi.processorIterator.hasNext()) {
duke@1: ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
duke@1: log, source, JavacProcessingEnvironment.this);
duke@1: psi.procStateList.add(ps);
duke@1: return ps;
duke@1: } else
duke@1: throw new NoSuchElementException();
duke@1: }
duke@1:
duke@1: public boolean hasNext() {
duke@1: if (onProcInterator)
duke@1: return psi.processorIterator.hasNext();
duke@1: else
duke@1: return innerIter.hasNext() || psi.processorIterator.hasNext();
duke@1: }
duke@1:
duke@1: public void remove () {
duke@1: throw new UnsupportedOperationException();
duke@1: }
duke@1:
duke@1: /**
duke@1: * Run all remaining processors on the procStateList that
duke@1: * have not already run this round with an empty set of
duke@1: * annotations.
duke@1: */
duke@1: public void runContributingProcs(RoundEnvironment re) {
duke@1: if (!onProcInterator) {
duke@1: Set emptyTypeElements = Collections.emptySet();
duke@1: while(innerIter.hasNext()) {
duke@1: ProcessorState ps = innerIter.next();
duke@1: if (ps.contributed)
duke@1: callProcessor(ps.processor, emptyTypeElements, re);
duke@1: }
duke@1: }
duke@1: }
duke@1: }
duke@1:
duke@1: Iterator extends Processor> processorIterator;
duke@1: ArrayList procStateList;
duke@1:
duke@1: public ProcessorStateIterator iterator() {
duke@1: return new ProcessorStateIterator(this);
duke@1: }
duke@1:
duke@1: DiscoveredProcessors(Iterator extends Processor> processorIterator) {
duke@1: this.processorIterator = processorIterator;
duke@1: this.procStateList = new ArrayList();
duke@1: }
darcy@382:
darcy@382: /**
darcy@382: * Free jar files, etc. if using a service loader.
darcy@382: */
darcy@382: public void close() {
darcy@382: if (processorIterator != null &&
darcy@382: processorIterator instanceof ServiceIterator) {
darcy@382: ((ServiceIterator) processorIterator).close();
darcy@382: }
darcy@382: }
duke@1: }
duke@1:
duke@1: private void discoverAndRunProcs(Context context,
duke@1: Set annotationsPresent,
duke@1: List topLevelClasses,
duke@1: List packageInfoFiles) {
duke@1: Map unmatchedAnnotations =
duke@1: new HashMap(annotationsPresent.size());
duke@1:
duke@1: for(TypeElement a : annotationsPresent) {
duke@1: unmatchedAnnotations.put(a.getQualifiedName().toString(),
duke@1: a);
duke@1: }
duke@1:
duke@1: // Give "*" processors a chance to match
duke@1: if (unmatchedAnnotations.size() == 0)
duke@1: unmatchedAnnotations.put("", null);
duke@1:
duke@1: DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
duke@1: // TODO: Create proper argument values; need past round
duke@1: // information to fill in this constructor. Note that the 1
duke@1: // st round of processing could be the last round if there
duke@1: // were parse errors on the initial source files; however, we
duke@1: // are not doing processing in that case.
duke@1:
duke@1: Set rootElements = new LinkedHashSet();
duke@1: rootElements.addAll(topLevelClasses);
duke@1: rootElements.addAll(packageInfoFiles);
duke@1: rootElements = Collections.unmodifiableSet(rootElements);
duke@1:
duke@1: RoundEnvironment renv = new JavacRoundEnvironment(false,
duke@1: false,
duke@1: rootElements,
duke@1: JavacProcessingEnvironment.this);
duke@1:
duke@1: while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
duke@1: ProcessorState ps = psi.next();
duke@1: Set matchedNames = new HashSet();
duke@1: Set typeElements = new LinkedHashSet();
darcy@506:
darcy@506: for (Map.Entry entry: unmatchedAnnotations.entrySet()) {
darcy@506: String unmatchedAnnotationName = entry.getKey();
duke@1: if (ps.annotationSupported(unmatchedAnnotationName) ) {
duke@1: matchedNames.add(unmatchedAnnotationName);
darcy@506: TypeElement te = entry.getValue();
duke@1: if (te != null)
duke@1: typeElements.add(te);
duke@1: }
duke@1: }
duke@1:
duke@1: if (matchedNames.size() > 0 || ps.contributed) {
duke@1: boolean processingResult = callProcessor(ps.processor, typeElements, renv);
duke@1: ps.contributed = true;
duke@1: ps.removeSupportedOptions(unmatchedProcessorOptions);
duke@1:
duke@1: if (printProcessorInfo || verbose) {
jjg@1136: log.printLines("x.print.processor.info",
jjg@604: ps.processor.getClass().getName(),
jjg@604: matchedNames.toString(),
jjg@604: processingResult);
duke@1: }
duke@1:
duke@1: if (processingResult) {
duke@1: unmatchedAnnotations.keySet().removeAll(matchedNames);
duke@1: }
duke@1:
duke@1: }
duke@1: }
duke@1: unmatchedAnnotations.remove("");
duke@1:
duke@1: if (lint && unmatchedAnnotations.size() > 0) {
duke@1: // Remove annotations processed by javac
duke@1: unmatchedAnnotations.keySet().removeAll(platformAnnotations);
duke@1: if (unmatchedAnnotations.size() > 0) {
duke@1: log = Log.instance(context);
duke@1: log.warning("proc.annotations.without.processors",
duke@1: unmatchedAnnotations.keySet());
duke@1: }
duke@1: }
duke@1:
duke@1: // Run contributing processors that haven't run yet
duke@1: psi.runContributingProcs(renv);
duke@1:
duke@1: // Debugging
jjg@700: if (options.isSet("displayFilerState"))
duke@1: filer.displayState();
duke@1: }
duke@1:
duke@1: /**
duke@1: * Computes the set of annotations on the symbol in question.
duke@1: * Leave class public for external testing purposes.
duke@1: */
duke@1: public static class ComputeAnnotationSet extends
darcy@1054: ElementScanner8, Set> {
duke@1: final Elements elements;
duke@1:
duke@1: public ComputeAnnotationSet(Elements elements) {
duke@1: super();
duke@1: this.elements = elements;
duke@1: }
duke@1:
duke@1: @Override
duke@1: public Set visitPackage(PackageElement e, Set p) {
duke@1: // Don't scan enclosed elements of a package
duke@1: return p;
duke@1: }
duke@1:
duke@1: @Override
jjg@620: public Set scan(Element e, Set p) {
duke@1: for (AnnotationMirror annotationMirror :
duke@1: elements.getAllAnnotationMirrors(e) ) {
duke@1: Element e2 = annotationMirror.getAnnotationType().asElement();
duke@1: p.add((TypeElement) e2);
duke@1: }
duke@1: return super.scan(e, p);
duke@1: }
duke@1: }
duke@1:
duke@1: private boolean callProcessor(Processor proc,
duke@1: Set extends TypeElement> tes,
duke@1: RoundEnvironment renv) {
duke@1: try {
duke@1: return proc.process(tes, renv);
jjg@952: } catch (BadClassFile ex) {
jjg@952: log.error("proc.cant.access.1", ex.sym, ex.getDetailValue());
jjg@952: return false;
duke@1: } catch (CompletionFailure ex) {
duke@1: StringWriter out = new StringWriter();
duke@1: ex.printStackTrace(new PrintWriter(out));
jjg@12: log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
duke@1: return false;
jjg@946: } catch (ClientCodeException e) {
jjg@946: throw e;
duke@1: } catch (Throwable t) {
duke@1: throw new AnnotationProcessingError(t);
duke@1: }
duke@1: }
duke@1:
jjg@620: /**
jjg@620: * Helper object for a single round of annotation processing.
jjg@620: */
jjg@620: class Round {
jjg@620: /** The round number. */
jjg@620: final int number;
jjg@620: /** The context for the round. */
jjg@620: final Context context;
jjg@620: /** The compiler for the round. */
jjg@620: final JavaCompiler compiler;
jjg@620: /** The log for the round. */
jjg@620: final Log log;
jjg@1406: /** The diagnostic handler for the round. */
jjg@1406: final Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
jjg@642:
jjg@642: /** The ASTs to be compiled. */
jjg@642: List roots;
jjg@642: /** The classes to be compiler that have were generated. */
jjg@642: Map genClassFiles;
jjg@620:
jjg@620: /** The set of annotations to be processed this round. */
jjg@620: Set annotationsPresent;
jjg@620: /** The set of top level classes to be processed this round. */
jjg@620: List topLevelClasses;
jjg@620: /** The set of package-info files to be processed this round. */
jjg@620: List packageInfoFiles;
jjg@620:
jjg@933: /** The number of Messager errors generated in this round. */
jjg@933: int nMessagerErrors;
jjg@933:
jjg@642: /** Create a round (common code). */
jjg@1406: private Round(Context context, int number, int priorErrors, int priorWarnings,
jjg@1406: Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
jjg@620: this.context = context;
jjg@620: this.number = number;
jjg@642:
jjg@620: compiler = JavaCompiler.instance(context);
jjg@620: log = Log.instance(context);
jjg@933: log.nerrors = priorErrors;
jjg@898: log.nwarnings += priorWarnings;
jjg@1406: if (number == 1) {
jjg@1406: Assert.checkNonNull(deferredDiagnosticHandler);
jjg@1406: this.deferredDiagnosticHandler = deferredDiagnosticHandler;
jjg@1406: } else {
jjg@1406: this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
jjg@1406: }
jjg@620:
jjg@620: // the following is for the benefit of JavacProcessingEnvironment.getContext()
jjg@620: JavacProcessingEnvironment.this.context = context;
jjg@620:
jjg@620: // the following will be populated as needed
jjg@620: topLevelClasses = List.nil();
jjg@620: packageInfoFiles = List.nil();
jjg@620: }
jjg@620:
jjg@642: /** Create the first round. */
jjg@1406: Round(Context context, List roots, List classSymbols,
jjg@1406: Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
jjg@1406: this(context, 1, 0, 0, deferredDiagnosticHandler);
jjg@642: this.roots = roots;
jjg@642: genClassFiles = new HashMap();
jjg@642:
jjg@642: compiler.todo.clear(); // free the compiler's resources
jjg@642:
jjg@642: // The reverse() in the following line is to maintain behavioural
jjg@642: // compatibility with the previous revision of the code. Strictly speaking,
jjg@642: // it should not be necessary, but a javah golden file test fails without it.
jjg@642: topLevelClasses =
jjg@642: getTopLevelClasses(roots).prependList(classSymbols.reverse());
jjg@642:
jjg@642: packageInfoFiles = getPackageInfoFiles(roots);
jjg@642:
jjg@642: findAnnotationsPresent();
jjg@642: }
jjg@642:
jjg@642: /** Create a new round. */
jjg@642: private Round(Round prev,
jjg@663: Set newSourceFiles, Map newClassFiles) {
jjg@933: this(prev.nextContext(),
jjg@933: prev.number+1,
jjg@933: prev.nMessagerErrors,
jjg@1406: prev.compiler.log.nwarnings,
jjg@1406: null);
jjg@642: this.genClassFiles = prev.genClassFiles;
jjg@642:
jjg@642: List parsedFiles = compiler.parseFiles(newSourceFiles);
jjg@642: roots = cleanTrees(prev.roots).appendList(parsedFiles);
jjg@642:
jjg@642: // Check for errors after parsing
jjg@642: if (unrecoverableError())
jjg@642: return;
jjg@642:
jjg@642: enterClassFiles(genClassFiles);
jjg@642: List newClasses = enterClassFiles(newClassFiles);
jjg@642: genClassFiles.putAll(newClassFiles);
jjg@642: enterTrees(roots);
jjg@642:
jjg@642: if (unrecoverableError())
jjg@642: return;
jjg@642:
jjg@642: topLevelClasses = join(
jjg@642: getTopLevelClasses(parsedFiles),
jjg@642: getTopLevelClassesFromClasses(newClasses));
jjg@642:
jjg@642: packageInfoFiles = join(
jjg@642: getPackageInfoFiles(parsedFiles),
jjg@642: getPackageInfoFilesFromClasses(newClasses));
jjg@642:
jjg@642: findAnnotationsPresent();
jjg@642: }
jjg@642:
jjg@620: /** Create the next round to be used. */
jjg@663: Round next(Set newSourceFiles, Map newClassFiles) {
jjg@642: try {
jjg@642: return new Round(this, newSourceFiles, newClassFiles);
jjg@642: } finally {
jjg@642: compiler.close(false);
jjg@642: }
jjg@642: }
jjg@642:
jjg@642: /** Create the compiler to be used for the final compilation. */
jjg@642: JavaCompiler finalCompiler(boolean errorStatus) {
jjg@642: try {
jjg@1340: Context nextCtx = nextContext();
jjg@1340: JavacProcessingEnvironment.this.context = nextCtx;
jjg@1340: JavaCompiler c = JavaCompiler.instance(nextCtx);
jjg@898: c.log.nwarnings += compiler.log.nwarnings;
jjg@642: if (errorStatus) {
jjg@642: c.log.nerrors += compiler.log.nerrors;
jjg@642: }
jjg@642: return c;
jjg@642: } finally {
jjg@642: compiler.close(false);
jjg@642: }
jjg@620: }
jjg@620:
jjg@620: /** Return the number of errors found so far in this round.
jjg@620: * This may include uncoverable errors, such as parse errors,
jjg@620: * and transient errors, such as missing symbols. */
jjg@620: int errorCount() {
jjg@620: return compiler.errorCount();
jjg@620: }
jjg@620:
jjg@620: /** Return the number of warnings found so far in this round. */
jjg@620: int warningCount() {
jjg@620: return compiler.warningCount();
jjg@620: }
jjg@620:
jjg@620: /** Return whether or not an unrecoverable error has occurred. */
jjg@620: boolean unrecoverableError() {
jjg@664: if (messager.errorRaised())
jjg@664: return true;
jjg@664:
jjg@1406: for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
jjg@664: switch (d.getKind()) {
jjg@664: case WARNING:
jjg@664: if (werror)
jjg@664: return true;
jjg@664: break;
jjg@664:
jjg@664: case ERROR:
jjg@726: if (fatalErrors || !d.isFlagSet(RECOVERABLE))
jjg@664: return true;
jjg@664: break;
jjg@664: }
jjg@664: }
jjg@664:
jjg@664: return false;
jjg@620: }
jjg@620:
jjg@620: /** Find the set of annotations present in the set of top level
jjg@642: * classes and package info files to be processed this round. */
jjg@642: void findAnnotationsPresent() {
jjg@642: ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
jjg@620: // Use annotation processing to compute the set of annotations present
jjg@620: annotationsPresent = new LinkedHashSet();
jjg@620: for (ClassSymbol classSym : topLevelClasses)
jjg@620: annotationComputer.scan(classSym, annotationsPresent);
jjg@620: for (PackageSymbol pkgSym : packageInfoFiles)
jjg@620: annotationComputer.scan(pkgSym, annotationsPresent);
jjg@620: }
jjg@620:
jjg@642: /** Enter a set of generated class files. */
jjg@664: private List enterClassFiles(Map classFiles) {
jjg@620: ClassReader reader = ClassReader.instance(context);
jjg@620: Names names = Names.instance(context);
jjg@620: List list = List.nil();
jjg@620:
jjg@642: for (Map.Entry entry : classFiles.entrySet()) {
jjg@620: Name name = names.fromString(entry.getKey());
jjg@620: JavaFileObject file = entry.getValue();
jjg@620: if (file.getKind() != JavaFileObject.Kind.CLASS)
jjg@620: throw new AssertionError(file);
jjg@620: ClassSymbol cs;
jjg@620: if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
jjg@620: Name packageName = Convert.packagePart(name);
jjg@620: PackageSymbol p = reader.enterPackage(packageName);
jjg@620: if (p.package_info == null)
jjg@620: p.package_info = reader.enterClass(Convert.shortName(name), p);
jjg@620: cs = p.package_info;
jjg@620: if (cs.classfile == null)
jjg@620: cs.classfile = file;
jjg@620: } else
jjg@620: cs = reader.enterClass(name, file);
jjg@620: list = list.prepend(cs);
jjg@620: }
jjg@620: return list.reverse();
jjg@620: }
jjg@620:
jjg@620: /** Enter a set of syntax trees. */
jjg@664: private void enterTrees(List roots) {
jjg@620: compiler.enterTrees(roots);
jjg@620: }
jjg@620:
jjg@620: /** Run a processing round. */
jjg@620: void run(boolean lastRound, boolean errorStatus) {
jjg@642: printRoundInfo(lastRound);
jjg@620:
jjg@1210: if (!taskListener.isEmpty())
jjg@620: taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
jjg@620:
jjg@620: try {
jjg@620: if (lastRound) {
jjg@620: filer.setLastRound(true);
jjg@620: Set emptyRootElements = Collections.emptySet(); // immutable
jjg@620: RoundEnvironment renv = new JavacRoundEnvironment(true,
jjg@620: errorStatus,
jjg@620: emptyRootElements,
jjg@620: JavacProcessingEnvironment.this);
jjg@620: discoveredProcs.iterator().runContributingProcs(renv);
jjg@620: } else {
jjg@620: discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
jjg@620: }
jjg@620: } finally {
jjg@1210: if (!taskListener.isEmpty())
jjg@620: taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
jjg@620: }
jjg@933:
jjg@933: nMessagerErrors = messager.errorCount();
jjg@620: }
jjg@620:
jjg@664: void showDiagnostics(boolean showAll) {
jjg@664: Set kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
jjg@664: if (!showAll) {
jjg@664: // suppress errors, which are all presumed to be transient resolve errors
jjg@664: kinds.remove(JCDiagnostic.Kind.ERROR);
jjg@664: }
jjg@1406: deferredDiagnosticHandler.reportDeferredDiagnostics(kinds);
jjg@1406: log.popDiagnosticHandler(deferredDiagnosticHandler);
jjg@664: }
jjg@664:
jjg@620: /** Print info about this round. */
jjg@642: private void printRoundInfo(boolean lastRound) {
jjg@620: if (printRounds || verbose) {
jjg@642: List tlc = lastRound ? List.nil() : topLevelClasses;
jjg@642: Set ap = lastRound ? Collections.emptySet() : annotationsPresent;
jjg@1136: log.printLines("x.print.rounds",
jjg@642: number,
jjg@642: "{" + tlc.toString(", ") + "}",
jjg@642: ap,
jjg@620: lastRound);
jjg@620: }
jjg@620: }
jjg@620:
jjg@620: /** Get the context for the next round of processing.
jjg@1340: * Important values are propagated from round to round;
jjg@620: * other values are implicitly reset.
jjg@620: */
jjg@642: private Context nextContext() {
jjg@893: Context next = new Context(context);
jjg@620:
jjg@620: Options options = Options.instance(context);
jjg@816: Assert.checkNonNull(options);
jjg@620: next.put(Options.optionsKey, options);
jjg@620:
jjg@944: Locale locale = context.get(Locale.class);
jjg@944: if (locale != null)
jjg@944: next.put(Locale.class, locale);
jjg@1159:
jjg@944: Assert.checkNonNull(messages);
jjg@944: next.put(JavacMessages.messagesKey, messages);
jjg@620:
jjg@620: final boolean shareNames = true;
jjg@620: if (shareNames) {
jjg@620: Names names = Names.instance(context);
jjg@816: Assert.checkNonNull(names);
jjg@620: next.put(Names.namesKey, names);
jjg@620: }
jjg@620:
jjg@620: DiagnosticListener> dl = context.get(DiagnosticListener.class);
jjg@620: if (dl != null)
jjg@620: next.put(DiagnosticListener.class, dl);
jjg@620:
jjg@1210: MultiTaskListener mtl = context.get(MultiTaskListener.taskListenerKey);
jjg@1210: if (mtl != null)
jjg@1210: next.put(MultiTaskListener.taskListenerKey, mtl);
jjg@620:
jjg@872: FSInfo fsInfo = context.get(FSInfo.class);
jjg@872: if (fsInfo != null)
jjg@872: next.put(FSInfo.class, fsInfo);
jjg@872:
jjg@620: JavaFileManager jfm = context.get(JavaFileManager.class);
jjg@816: Assert.checkNonNull(jfm);
jjg@620: next.put(JavaFileManager.class, jfm);
jjg@620: if (jfm instanceof JavacFileManager) {
jjg@620: ((JavacFileManager)jfm).setContext(next);
jjg@620: }
jjg@620:
jjg@620: Names names = Names.instance(context);
jjg@816: Assert.checkNonNull(names);
jjg@620: next.put(Names.namesKey, names);
jjg@620:
mcimadamore@1113: Tokens tokens = Tokens.instance(context);
mcimadamore@1113: Assert.checkNonNull(tokens);
mcimadamore@1113: next.put(Tokens.tokensKey, tokens);
jjg@620:
jjg@1323: Log nextLog = Log.instance(next);
jjg@1159: // propogate the log's writers directly, instead of going through context
jjg@1323: nextLog.setWriters(log);
jjg@1323: nextLog.setSourceMap(log);
jjg@1159:
jjg@620: JavaCompiler oldCompiler = JavaCompiler.instance(context);
jjg@620: JavaCompiler nextCompiler = JavaCompiler.instance(next);
jjg@620: nextCompiler.initRound(oldCompiler);
jjg@620:
jjg@706: filer.newRound(next);
jjg@706: messager.newRound(next);
jjg@706: elementUtils.setContext(next);
jjg@706: typeUtils.setContext(next);
jjg@706:
jjg@1334: JavacTask task = context.get(JavacTask.class);
jjg@620: if (task != null) {
jjg@1210: next.put(JavacTask.class, task);
jjg@1334: if (task instanceof BasicJavacTask)
jjg@1334: ((BasicJavacTask) task).updateContext(next);
jjg@620: }
jjg@620:
jjg@696: JavacTrees trees = context.get(JavacTrees.class);
jjg@696: if (trees != null) {
jjg@696: next.put(JavacTrees.class, trees);
jjg@696: trees.updateContext(next);
jjg@696: }
jjg@696:
jjg@620: context.clear();
jjg@620: return next;
jjg@620: }
jjg@620: }
jjg@620:
duke@1:
duke@1: // TODO: internal catch clauses?; catch and rethrow an annotation
duke@1: // processing error
duke@1: public JavaCompiler doProcessing(Context context,
duke@1: List roots,
duke@1: List classSymbols,
jjg@1406: Iterable extends PackageSymbol> pckSymbols,
jjg@1406: Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
duke@1: log = Log.instance(context);
duke@1:
duke@1: Set specifiedPackages = new LinkedHashSet();
duke@1: for (PackageSymbol psym : pckSymbols)
duke@1: specifiedPackages.add(psym);
duke@1: this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
duke@1:
jjg@1406: Round round = new Round(context, roots, classSymbols, deferredDiagnosticHandler);
duke@1:
jjg@642: boolean errorStatus;
jjg@642: boolean moreToDo;
jjg@642: do {
jjg@642: // Run processors for round n
jjg@620: round.run(false, false);
duke@1:
jjg@642: // Processors for round n have run to completion.
jjg@642: // Check for errors and whether there is more work to do.
jjg@642: errorStatus = round.unrecoverableError();
jjg@642: moreToDo = moreToDo();
jjg@642:
jjg@664: round.showDiagnostics(errorStatus || showResolveErrors);
jjg@664:
jjg@642: // Set up next round.
jjg@642: // Copy mutable collections returned from filer.
jjg@642: round = round.next(
jjg@642: new LinkedHashSet(filer.getGeneratedSourceFileObjects()),
jjg@642: new LinkedHashMap(filer.getGeneratedClasses()));
jjg@642:
jjg@642: // Check for errors during setup.
jjg@642: if (round.unrecoverableError())
duke@1: errorStatus = true;
duke@1:
jjg@642: } while (moreToDo && !errorStatus);
jjg@620:
jjg@620: // run last round
jjg@620: round.run(true, errorStatus);
jjg@664: round.showDiagnostics(true);
jjg@620:
duke@1: filer.warnIfUnclosedFiles();
duke@1: warnIfUnmatchedOptions();
duke@1:
jjg@642: /*
jjg@642: * If an annotation processor raises an error in a round,
jjg@642: * that round runs to completion and one last round occurs.
jjg@642: * The last round may also occur because no more source or
jjg@642: * class files have been generated. Therefore, if an error
jjg@642: * was raised on either of the last *two* rounds, the compile
jjg@642: * should exit with a nonzero exit code. The current value of
jjg@642: * errorStatus holds whether or not an error was raised on the
jjg@642: * second to last round; errorRaised() gives the error status
jjg@642: * of the last round.
jjg@642: */
jjg@642: if (messager.errorRaised()
jjg@642: || werror && round.warningCount() > 0 && round.errorCount() > 0)
jjg@642: errorStatus = true;
jjg@642:
jjg@642: Set newSourceFiles =
jjg@642: new LinkedHashSet(filer.getGeneratedSourceFileObjects());
jjg@642: roots = cleanTrees(round.roots);
jjg@642:
jjg@642: JavaCompiler compiler = round.finalCompiler(errorStatus);
jjg@642:
jjg@642: if (newSourceFiles.size() > 0)
jjg@642: roots = roots.appendList(compiler.parseFiles(newSourceFiles));
jjg@642:
jjg@642: errorStatus = errorStatus || (compiler.errorCount() > 0);
duke@1:
duke@1: // Free resources
duke@1: this.close();
duke@1:
jjg@1210: if (!taskListener.isEmpty())
duke@1: taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
duke@1:
duke@1: if (errorStatus) {
duke@1: if (compiler.errorCount() == 0)
duke@1: compiler.log.nerrors++;
jjg@642: return compiler;
jjg@642: }
jjg@642:
jjg@1340: compiler.enterTreesIfNeeded(roots);
duke@1:
duke@1: return compiler;
duke@1: }
duke@1:
duke@1: private void warnIfUnmatchedOptions() {
duke@1: if (!unmatchedProcessorOptions.isEmpty()) {
duke@1: log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
duke@1: }
duke@1: }
duke@1:
duke@1: /**
duke@1: * Free resources related to annotation processing.
duke@1: */
jjg@663: public void close() {
duke@1: filer.close();
darcy@382: if (discoveredProcs != null) // Make calling close idempotent
darcy@382: discoveredProcs.close();
duke@1: discoveredProcs = null;
duke@1: }
duke@1:
duke@1: private List getTopLevelClasses(List extends JCCompilationUnit> units) {
duke@1: List classes = List.nil();
duke@1: for (JCCompilationUnit unit : units) {
duke@1: for (JCTree node : unit.defs) {
jjg@1127: if (node.hasTag(JCTree.Tag.CLASSDEF)) {
jjg@642: ClassSymbol sym = ((JCClassDecl) node).sym;
jjg@816: Assert.checkNonNull(sym);
jjg@642: classes = classes.prepend(sym);
duke@1: }
duke@1: }
duke@1: }
duke@1: return classes.reverse();
duke@1: }
duke@1:
jjg@483: private List getTopLevelClassesFromClasses(List extends ClassSymbol> syms) {
jjg@483: List classes = List.nil();
jjg@483: for (ClassSymbol sym : syms) {
jjg@483: if (!isPkgInfo(sym)) {
jjg@483: classes = classes.prepend(sym);
jjg@483: }
jjg@483: }
jjg@483: return classes.reverse();
jjg@483: }
jjg@483:
duke@1: private List getPackageInfoFiles(List extends JCCompilationUnit> units) {
duke@1: List packages = List.nil();
duke@1: for (JCCompilationUnit unit : units) {
jjg@483: if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
duke@1: packages = packages.prepend(unit.packge);
duke@1: }
duke@1: }
duke@1: return packages.reverse();
duke@1: }
duke@1:
jjg@483: private List getPackageInfoFilesFromClasses(List extends ClassSymbol> syms) {
jjg@483: List packages = List.nil();
jjg@483: for (ClassSymbol sym : syms) {
jjg@483: if (isPkgInfo(sym)) {
jjg@483: packages = packages.prepend((PackageSymbol) sym.owner);
jjg@483: }
jjg@483: }
jjg@483: return packages.reverse();
jjg@483: }
jjg@483:
jjg@620: // avoid unchecked warning from use of varargs
jjg@620: private static List join(List list1, List list2) {
jjg@620: return list1.appendList(list2);
jjg@620: }
jjg@620:
jjg@483: private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
jjg@483: return fo.isNameCompatible("package-info", kind);
jjg@483: }
jjg@483:
jjg@483: private boolean isPkgInfo(ClassSymbol sym) {
jjg@483: return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
jjg@483: }
jjg@483:
duke@1: /*
duke@1: * Called retroactively to determine if a class loader was required,
duke@1: * after we have failed to create one.
duke@1: */
duke@1: private boolean needClassLoader(String procNames, Iterable extends File> workingpath) {
duke@1: if (procNames != null)
duke@1: return true;
duke@1:
duke@1: String procPath;
duke@1: URL[] urls = new URL[1];
duke@1: for(File pathElement : workingpath) {
duke@1: try {
duke@1: urls[0] = pathElement.toURI().toURL();
duke@1: if (ServiceProxy.hasService(Processor.class, urls))
duke@1: return true;
duke@1: } catch (MalformedURLException ex) {
duke@1: throw new AssertionError(ex);
duke@1: }
duke@1: catch (ServiceProxy.ServiceConfigurationError e) {
duke@1: log.error("proc.bad.config.file", e.getLocalizedMessage());
duke@1: return true;
duke@1: }
duke@1: }
duke@1:
duke@1: return false;
duke@1: }
duke@1:
duke@1: private static List cleanTrees(List nodes) {
duke@1: for (T node : nodes)
duke@1: treeCleaner.scan(node);
duke@1: return nodes;
duke@1: }
duke@1:
vromero@1442: private static final TreeScanner treeCleaner = new TreeScanner() {
duke@1: public void scan(JCTree node) {
duke@1: super.scan(node);
duke@1: if (node != null)
duke@1: node.type = null;
duke@1: }
duke@1: public void visitTopLevel(JCCompilationUnit node) {
duke@1: node.packge = null;
duke@1: super.visitTopLevel(node);
duke@1: }
duke@1: public void visitClassDef(JCClassDecl node) {
duke@1: node.sym = null;
duke@1: super.visitClassDef(node);
duke@1: }
duke@1: public void visitMethodDef(JCMethodDecl node) {
duke@1: node.sym = null;
duke@1: super.visitMethodDef(node);
duke@1: }
duke@1: public void visitVarDef(JCVariableDecl node) {
duke@1: node.sym = null;
duke@1: super.visitVarDef(node);
duke@1: }
duke@1: public void visitNewClass(JCNewClass node) {
duke@1: node.constructor = null;
duke@1: super.visitNewClass(node);
duke@1: }
duke@1: public void visitAssignop(JCAssignOp node) {
duke@1: node.operator = null;
duke@1: super.visitAssignop(node);
duke@1: }
duke@1: public void visitUnary(JCUnary node) {
duke@1: node.operator = null;
duke@1: super.visitUnary(node);
duke@1: }
duke@1: public void visitBinary(JCBinary node) {
duke@1: node.operator = null;
duke@1: super.visitBinary(node);
duke@1: }
duke@1: public void visitSelect(JCFieldAccess node) {
duke@1: node.sym = null;
duke@1: super.visitSelect(node);
duke@1: }
duke@1: public void visitIdent(JCIdent node) {
duke@1: node.sym = null;
duke@1: super.visitIdent(node);
duke@1: }
duke@1: };
duke@1:
duke@1:
duke@1: private boolean moreToDo() {
duke@1: return filer.newFiles();
duke@1: }
duke@1:
duke@1: /**
duke@1: * {@inheritdoc}
duke@1: *
duke@1: * Command line options suitable for presenting to annotation
jjg@1326: * processors.
jjg@1326: * {@literal "-Afoo=bar"} should be {@literal "-Afoo" => "bar"}.
duke@1: */
duke@1: public Map getOptions() {
duke@1: return processorOptions;
duke@1: }
duke@1:
duke@1: public Messager getMessager() {
duke@1: return messager;
duke@1: }
duke@1:
duke@1: public Filer getFiler() {
duke@1: return filer;
duke@1: }
duke@1:
duke@1: public JavacElements getElementUtils() {
duke@1: return elementUtils;
duke@1: }
duke@1:
duke@1: public JavacTypes getTypeUtils() {
duke@1: return typeUtils;
duke@1: }
duke@1:
duke@1: public SourceVersion getSourceVersion() {
duke@1: return Source.toSourceVersion(source);
duke@1: }
duke@1:
duke@1: public Locale getLocale() {
mcimadamore@136: return messages.getCurrentLocale();
duke@1: }
duke@1:
duke@1: public Set getSpecifiedPackages() {
duke@1: return specifiedPackages;
duke@1: }
duke@1:
darcy@497: private static final Pattern allMatches = Pattern.compile(".*");
darcy@497: public static final Pattern noMatches = Pattern.compile("(\\P{all})+");
darcy@497:
duke@1: /**
darcy@497: * Convert import-style string for supported annotations into a
darcy@497: * regex matching that string. If the string is a valid
darcy@497: * import-style string, return a regex that won't match anything.
duke@1: */
darcy@497: private static Pattern importStringToPattern(String s, Processor p, Log log) {
darcy@497: if (isValidImportString(s)) {
darcy@497: return validImportStringToPattern(s);
darcy@497: } else {
darcy@497: log.warning("proc.malformed.supported.string", s, p.getClass().getName());
darcy@497: return noMatches; // won't match any valid identifier
duke@1: }
duke@1: }
duke@1:
duke@1: /**
darcy@497: * Return true if the argument string is a valid import-style
darcy@497: * string specifying claimed annotations; return false otherwise.
duke@1: */
darcy@497: public static boolean isValidImportString(String s) {
darcy@497: if (s.equals("*"))
darcy@497: return true;
darcy@497:
darcy@497: boolean valid = true;
darcy@497: String t = s;
darcy@497: int index = t.indexOf('*');
darcy@497:
darcy@497: if (index != -1) {
darcy@497: // '*' must be last character...
darcy@497: if (index == t.length() -1) {
darcy@497: // ... any and preceding character must be '.'
darcy@497: if ( index-1 >= 0 ) {
darcy@497: valid = t.charAt(index-1) == '.';
darcy@497: // Strip off ".*$" for identifier checks
darcy@497: t = t.substring(0, t.length()-2);
darcy@497: }
darcy@497: } else
darcy@497: return false;
duke@1: }
darcy@497:
darcy@497: // Verify string is off the form (javaId \.)+ or javaId
darcy@497: if (valid) {
darcy@497: String[] javaIds = t.split("\\.", t.length()+2);
darcy@497: for(String javaId: javaIds)
darcy@497: valid &= SourceVersion.isIdentifier(javaId);
duke@1: }
darcy@497: return valid;
duke@1: }
duke@1:
darcy@497: public static Pattern validImportStringToPattern(String s) {
duke@1: if (s.equals("*")) {
duke@1: return allMatches;
duke@1: } else {
darcy@497: String s_prime = s.replace(".", "\\.");
duke@1:
duke@1: if (s_prime.endsWith("*")) {
duke@1: s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+";
duke@1: }
duke@1:
duke@1: return Pattern.compile(s_prime);
duke@1: }
duke@1: }
duke@1:
duke@1: /**
jjg@1416: * For internal use only. This method may be removed without warning.
duke@1: */
duke@1: public Context getContext() {
duke@1: return context;
duke@1: }
duke@1:
jjg@1416: /**
jjg@1416: * For internal use only. This method may be removed without warning.
jjg@1416: */
jjg@1416: public ClassLoader getProcessorClassLoader() {
jjg@1416: return processorClassLoader;
jjg@1416: }
jjg@1416:
duke@1: public String toString() {
duke@1: return "javac ProcessingEnvironment";
duke@1: }
duke@1:
duke@1: public static boolean isValidOptionName(String optionName) {
duke@1: for(String s : optionName.split("\\.", -1)) {
duke@1: if (!SourceVersion.isIdentifier(s))
duke@1: return false;
duke@1: }
duke@1: return true;
duke@1: }
duke@1: }