JavacProcessingEnvironment.java revision 2601:8e638f046bf0
1/*
2 * Copyright (c) 2005, 2014, 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 */
25
26package com.sun.tools.javac.processing;
27
28import java.io.Closeable;
29import java.io.File;
30import java.io.PrintWriter;
31import java.io.StringWriter;
32import java.net.MalformedURLException;
33import java.net.URL;
34import java.util.*;
35import java.util.regex.*;
36
37import javax.annotation.processing.*;
38import javax.lang.model.SourceVersion;
39import javax.lang.model.element.*;
40import javax.lang.model.util.*;
41import javax.tools.JavaFileManager;
42import javax.tools.JavaFileObject;
43import javax.tools.StandardJavaFileManager;
44import static javax.tools.StandardLocation.*;
45
46import com.sun.source.util.TaskEvent;
47import com.sun.tools.javac.api.MultiTaskListener;
48import com.sun.tools.javac.code.*;
49import com.sun.tools.javac.code.Symbol.*;
50import com.sun.tools.javac.code.Type.ClassType;
51import com.sun.tools.javac.code.Types;
52import com.sun.tools.javac.comp.AttrContext;
53import com.sun.tools.javac.comp.Check;
54import com.sun.tools.javac.comp.Enter;
55import com.sun.tools.javac.comp.Env;
56import com.sun.tools.javac.file.JavacFileManager;
57import com.sun.tools.javac.main.JavaCompiler;
58import com.sun.tools.javac.model.JavacElements;
59import com.sun.tools.javac.model.JavacTypes;
60import com.sun.tools.javac.tree.*;
61import com.sun.tools.javac.tree.JCTree.*;
62import com.sun.tools.javac.util.Abort;
63import com.sun.tools.javac.util.Assert;
64import com.sun.tools.javac.util.ClientCodeException;
65import com.sun.tools.javac.util.Context;
66import com.sun.tools.javac.util.Convert;
67import com.sun.tools.javac.util.DefinedBy;
68import com.sun.tools.javac.util.DefinedBy.Api;
69import com.sun.tools.javac.util.JCDiagnostic;
70import com.sun.tools.javac.util.JavacMessages;
71import com.sun.tools.javac.util.List;
72import com.sun.tools.javac.util.Log;
73import com.sun.tools.javac.util.Name;
74import com.sun.tools.javac.util.Names;
75import com.sun.tools.javac.util.Options;
76import com.sun.tools.javac.util.ServiceLoader;
77import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
78import static com.sun.tools.javac.main.Option.*;
79import static com.sun.tools.javac.comp.CompileStates.CompileState;
80import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
81
82/**
83 * Objects of this class hold and manage the state needed to support
84 * annotation processing.
85 *
86 * <p><b>This is NOT part of any supported API.
87 * If you write code that depends on this, you do so at your own risk.
88 * This code and its internal interfaces are subject to change or
89 * deletion without notice.</b>
90 */
91public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
92    private final Options options;
93
94    private final boolean printProcessorInfo;
95    private final boolean printRounds;
96    private final boolean verbose;
97    private final boolean lint;
98    private final boolean fatalErrors;
99    private final boolean werror;
100    private final boolean showResolveErrors;
101
102    private final JavacFiler filer;
103    private final JavacMessager messager;
104    private final JavacElements elementUtils;
105    private final JavacTypes typeUtils;
106    private final Types types;
107    private final JavaCompiler compiler;
108
109    /**
110     * Holds relevant state history of which processors have been
111     * used.
112     */
113    private DiscoveredProcessors discoveredProcs;
114
115    /**
116     * Map of processor-specific options.
117     */
118    private final Map<String, String> processorOptions;
119
120    /**
121     */
122    private final Set<String> unmatchedProcessorOptions;
123
124    /**
125     * Annotations implicitly processed and claimed by javac.
126     */
127    private final Set<String> platformAnnotations;
128
129    /**
130     * Set of packages given on command line.
131     */
132    private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
133
134    /** The log to be used for error reporting.
135     */
136    final Log log;
137
138    /** Diagnostic factory.
139     */
140    JCDiagnostic.Factory diags;
141
142    /**
143     * Source level of the compile.
144     */
145    Source source;
146
147    private ClassLoader processorClassLoader;
148    private SecurityException processorClassLoaderException;
149
150    /**
151     * JavacMessages object used for localization
152     */
153    private JavacMessages messages;
154
155    private MultiTaskListener taskListener;
156    private final Symtab symtab;
157    private final Names names;
158    private final Enter enter;
159    private final Completer initialCompleter;
160    private final Check chk;
161
162    private final Context context;
163
164    /** Get the JavacProcessingEnvironment instance for this context. */
165    public static JavacProcessingEnvironment instance(Context context) {
166        JavacProcessingEnvironment instance = context.get(JavacProcessingEnvironment.class);
167        if (instance == null)
168            instance = new JavacProcessingEnvironment(context);
169        return instance;
170    }
171
172    protected JavacProcessingEnvironment(Context context) {
173        this.context = context;
174        context.put(JavacProcessingEnvironment.class, this);
175        log = Log.instance(context);
176        source = Source.instance(context);
177        diags = JCDiagnostic.Factory.instance(context);
178        options = Options.instance(context);
179        printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
180        printRounds = options.isSet(XPRINTROUNDS);
181        verbose = options.isSet(VERBOSE);
182        lint = Lint.instance(context).isEnabled(PROCESSING);
183        compiler = JavaCompiler.instance(context);
184        if (options.isSet(PROC, "only") || options.isSet(XPRINT)) {
185            compiler.shouldStopPolicyIfNoError = CompileState.PROCESS;
186        }
187        fatalErrors = options.isSet("fatalEnterError");
188        showResolveErrors = options.isSet("showResolveErrors");
189        werror = options.isSet(WERROR);
190        platformAnnotations = initPlatformAnnotations();
191
192        // Initialize services before any processors are initialized
193        // in case processors use them.
194        filer = new JavacFiler(context);
195        messager = new JavacMessager(context, this);
196        elementUtils = JavacElements.instance(context);
197        typeUtils = JavacTypes.instance(context);
198        types = Types.instance(context);
199        processorOptions = initProcessorOptions();
200        unmatchedProcessorOptions = initUnmatchedProcessorOptions();
201        messages = JavacMessages.instance(context);
202        taskListener = MultiTaskListener.instance(context);
203        symtab = Symtab.instance(context);
204        names = Names.instance(context);
205        enter = Enter.instance(context);
206        initialCompleter = ClassFinder.instance(context).getCompleter();
207        chk = Check.instance(context);
208        initProcessorClassLoader();
209    }
210
211    public void setProcessors(Iterable<? extends Processor> processors) {
212        Assert.checkNull(discoveredProcs);
213        initProcessorIterator(processors);
214    }
215
216    private Set<String> initPlatformAnnotations() {
217        Set<String> platformAnnotations = new HashSet<>();
218        platformAnnotations.add("java.lang.Deprecated");
219        platformAnnotations.add("java.lang.Override");
220        platformAnnotations.add("java.lang.SuppressWarnings");
221        platformAnnotations.add("java.lang.annotation.Documented");
222        platformAnnotations.add("java.lang.annotation.Inherited");
223        platformAnnotations.add("java.lang.annotation.Retention");
224        platformAnnotations.add("java.lang.annotation.Target");
225        return Collections.unmodifiableSet(platformAnnotations);
226    }
227
228    private void initProcessorClassLoader() {
229        JavaFileManager fileManager = context.get(JavaFileManager.class);
230        try {
231            // If processorpath is not explicitly set, use the classpath.
232            processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
233                ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
234                : fileManager.getClassLoader(CLASS_PATH);
235
236            if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
237                compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
238            }
239        } catch (SecurityException e) {
240            processorClassLoaderException = e;
241        }
242    }
243
244    private void initProcessorIterator(Iterable<? extends Processor> processors) {
245        Iterator<? extends Processor> processorIterator;
246
247        if (options.isSet(XPRINT)) {
248            try {
249                Processor processor = PrintingProcessor.class.newInstance();
250                processorIterator = List.of(processor).iterator();
251            } catch (Throwable t) {
252                AssertionError assertError =
253                    new AssertionError("Problem instantiating PrintingProcessor.");
254                assertError.initCause(t);
255                throw assertError;
256            }
257        } else if (processors != null) {
258            processorIterator = processors.iterator();
259        } else {
260            String processorNames = options.get(PROCESSOR);
261            if (processorClassLoaderException == null) {
262                /*
263                 * If the "-processor" option is used, search the appropriate
264                 * path for the named class.  Otherwise, use a service
265                 * provider mechanism to create the processor iterator.
266                 */
267                if (processorNames != null) {
268                    processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
269                } else {
270                    processorIterator = new ServiceIterator(processorClassLoader, log);
271                }
272            } else {
273                /*
274                 * A security exception will occur if we can't create a classloader.
275                 * Ignore the exception if, with hindsight, we didn't need it anyway
276                 * (i.e. no processor was specified either explicitly, or implicitly,
277                 * in service configuration file.) Otherwise, we cannot continue.
278                 */
279                processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader",
280                        processorClassLoaderException);
281            }
282        }
283        discoveredProcs = new DiscoveredProcessors(processorIterator);
284    }
285
286    /**
287     * Returns an empty processor iterator if no processors are on the
288     * relevant path, otherwise if processors are present, logs an
289     * error.  Called when a service loader is unavailable for some
290     * reason, either because a service loader class cannot be found
291     * or because a security policy prevents class loaders from being
292     * created.
293     *
294     * @param key The resource key to use to log an error message
295     * @param e   If non-null, pass this exception to Abort
296     */
297    private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
298        JavaFileManager fileManager = context.get(JavaFileManager.class);
299
300        if (fileManager instanceof JavacFileManager) {
301            StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
302            Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
303                ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
304                : standardFileManager.getLocation(CLASS_PATH);
305
306            if (needClassLoader(options.get(PROCESSOR), workingPath) )
307                handleException(key, e);
308
309        } else {
310            handleException(key, e);
311        }
312
313        java.util.List<Processor> pl = Collections.emptyList();
314        return pl.iterator();
315    }
316
317    /**
318     * Handle a security exception thrown during initializing the
319     * Processor iterator.
320     */
321    private void handleException(String key, Exception e) {
322        if (e != null) {
323            log.error(key, e.getLocalizedMessage());
324            throw new Abort(e);
325        } else {
326            log.error(key);
327            throw new Abort();
328        }
329    }
330
331    /**
332     * Use a service loader appropriate for the platform to provide an
333     * iterator over annotations processors; fails if a loader is
334     * needed but unavailable.
335     */
336    private class ServiceIterator implements Iterator<Processor> {
337        private Iterator<Processor> iterator;
338        private Log log;
339        private ServiceLoader<Processor> loader;
340
341        ServiceIterator(ClassLoader classLoader, Log log) {
342            this.log = log;
343            try {
344                try {
345                    loader = ServiceLoader.load(Processor.class, classLoader);
346                    this.iterator = loader.iterator();
347                } catch (Exception e) {
348                    // Fail softly if a loader is not actually needed.
349                    this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
350                }
351            } catch (Throwable t) {
352                log.error("proc.service.problem");
353                throw new Abort(t);
354            }
355        }
356
357        public boolean hasNext() {
358            try {
359                return iterator.hasNext();
360            } catch(ServiceConfigurationError sce) {
361                log.error("proc.bad.config.file", sce.getLocalizedMessage());
362                throw new Abort(sce);
363            } catch (Throwable t) {
364                throw new Abort(t);
365            }
366        }
367
368        public Processor next() {
369            try {
370                return iterator.next();
371            } catch (ServiceConfigurationError sce) {
372                log.error("proc.bad.config.file", sce.getLocalizedMessage());
373                throw new Abort(sce);
374            } catch (Throwable t) {
375                throw new Abort(t);
376            }
377        }
378
379        public void remove() {
380            throw new UnsupportedOperationException();
381        }
382
383        public void close() {
384            if (loader != null) {
385                try {
386                    loader.reload();
387                } catch(Exception e) {
388                    // Ignore problems during a call to reload.
389                }
390            }
391        }
392    }
393
394
395    private static class NameProcessIterator implements Iterator<Processor> {
396        Processor nextProc = null;
397        Iterator<String> names;
398        ClassLoader processorCL;
399        Log log;
400
401        NameProcessIterator(String names, ClassLoader processorCL, Log log) {
402            this.names = Arrays.asList(names.split(",")).iterator();
403            this.processorCL = processorCL;
404            this.log = log;
405        }
406
407        public boolean hasNext() {
408            if (nextProc != null)
409                return true;
410            else {
411                if (!names.hasNext())
412                    return false;
413                else {
414                    String processorName = names.next();
415
416                    Processor processor;
417                    try {
418                        try {
419                            processor =
420                                (Processor) (processorCL.loadClass(processorName).newInstance());
421                        } catch (ClassNotFoundException cnfe) {
422                            log.error("proc.processor.not.found", processorName);
423                            return false;
424                        } catch (ClassCastException cce) {
425                            log.error("proc.processor.wrong.type", processorName);
426                            return false;
427                        } catch (Exception e ) {
428                            log.error("proc.processor.cant.instantiate", processorName);
429                            return false;
430                        }
431                    } catch(ClientCodeException e) {
432                        throw e;
433                    } catch(Throwable t) {
434                        throw new AnnotationProcessingError(t);
435                    }
436                    nextProc = processor;
437                    return true;
438                }
439
440            }
441        }
442
443        public Processor next() {
444            if (hasNext()) {
445                Processor p = nextProc;
446                nextProc = null;
447                return p;
448            } else
449                throw new NoSuchElementException();
450        }
451
452        public void remove () {
453            throw new UnsupportedOperationException();
454        }
455    }
456
457    public boolean atLeastOneProcessor() {
458        return discoveredProcs.iterator().hasNext();
459    }
460
461    private Map<String, String> initProcessorOptions() {
462        Set<String> keySet = options.keySet();
463        Map<String, String> tempOptions = new LinkedHashMap<>();
464
465        for(String key : keySet) {
466            if (key.startsWith("-A") && key.length() > 2) {
467                int sepIndex = key.indexOf('=');
468                String candidateKey = null;
469                String candidateValue = null;
470
471                if (sepIndex == -1)
472                    candidateKey = key.substring(2);
473                else if (sepIndex >= 3) {
474                    candidateKey = key.substring(2, sepIndex);
475                    candidateValue = (sepIndex < key.length()-1)?
476                        key.substring(sepIndex+1) : null;
477                }
478                tempOptions.put(candidateKey, candidateValue);
479            }
480        }
481
482        return Collections.unmodifiableMap(tempOptions);
483    }
484
485    private Set<String> initUnmatchedProcessorOptions() {
486        Set<String> unmatchedProcessorOptions = new HashSet<>();
487        unmatchedProcessorOptions.addAll(processorOptions.keySet());
488        return unmatchedProcessorOptions;
489    }
490
491    /**
492     * State about how a processor has been used by the tool.  If a
493     * processor has been used on a prior round, its process method is
494     * called on all subsequent rounds, perhaps with an empty set of
495     * annotations to process.  The {@code annotationSupported} method
496     * caches the supported annotation information from the first (and
497     * only) getSupportedAnnotationTypes call to the processor.
498     */
499    static class ProcessorState {
500        public Processor processor;
501        public boolean   contributed;
502        private ArrayList<Pattern> supportedAnnotationPatterns;
503        private ArrayList<String>  supportedOptionNames;
504
505        ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
506            processor = p;
507            contributed = false;
508
509            try {
510                processor.init(env);
511
512                checkSourceVersionCompatibility(source, log);
513
514                supportedAnnotationPatterns = new ArrayList<>();
515                for (String importString : processor.getSupportedAnnotationTypes()) {
516                    supportedAnnotationPatterns.add(importStringToPattern(importString,
517                                                                          processor,
518                                                                          log));
519                }
520
521                supportedOptionNames = new ArrayList<>();
522                for (String optionName : processor.getSupportedOptions() ) {
523                    if (checkOptionName(optionName, log))
524                        supportedOptionNames.add(optionName);
525                }
526
527            } catch (ClientCodeException e) {
528                throw e;
529            } catch (Throwable t) {
530                throw new AnnotationProcessingError(t);
531            }
532        }
533
534        /**
535         * Checks whether or not a processor's source version is
536         * compatible with the compilation source version.  The
537         * processor's source version needs to be greater than or
538         * equal to the source version of the compile.
539         */
540        private void checkSourceVersionCompatibility(Source source, Log log) {
541            SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
542
543            if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 )  {
544                log.warning("proc.processor.incompatible.source.version",
545                            procSourceVersion,
546                            processor.getClass().getName(),
547                            source.name);
548            }
549        }
550
551        private boolean checkOptionName(String optionName, Log log) {
552            boolean valid = isValidOptionName(optionName);
553            if (!valid)
554                log.error("proc.processor.bad.option.name",
555                            optionName,
556                            processor.getClass().getName());
557            return valid;
558        }
559
560        public boolean annotationSupported(String annotationName) {
561            for(Pattern p: supportedAnnotationPatterns) {
562                if (p.matcher(annotationName).matches())
563                    return true;
564            }
565            return false;
566        }
567
568        /**
569         * Remove options that are matched by this processor.
570         */
571        public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
572            unmatchedProcessorOptions.removeAll(supportedOptionNames);
573        }
574    }
575
576    // TODO: These two classes can probably be rewritten better...
577    /**
578     * This class holds information about the processors that have
579     * been discoverd so far as well as the means to discover more, if
580     * necessary.  A single iterator should be used per round of
581     * annotation processing.  The iterator first visits already
582     * discovered processors then fails over to the service provider
583     * mechanism if additional queries are made.
584     */
585    class DiscoveredProcessors implements Iterable<ProcessorState> {
586
587        class ProcessorStateIterator implements Iterator<ProcessorState> {
588            DiscoveredProcessors psi;
589            Iterator<ProcessorState> innerIter;
590            boolean onProcInterator;
591
592            ProcessorStateIterator(DiscoveredProcessors psi) {
593                this.psi = psi;
594                this.innerIter = psi.procStateList.iterator();
595                this.onProcInterator = false;
596            }
597
598            public ProcessorState next() {
599                if (!onProcInterator) {
600                    if (innerIter.hasNext())
601                        return innerIter.next();
602                    else
603                        onProcInterator = true;
604                }
605
606                if (psi.processorIterator.hasNext()) {
607                    ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
608                                                           log, source, JavacProcessingEnvironment.this);
609                    psi.procStateList.add(ps);
610                    return ps;
611                } else
612                    throw new NoSuchElementException();
613            }
614
615            public boolean hasNext() {
616                if (onProcInterator)
617                    return  psi.processorIterator.hasNext();
618                else
619                    return innerIter.hasNext() || psi.processorIterator.hasNext();
620            }
621
622            public void remove () {
623                throw new UnsupportedOperationException();
624            }
625
626            /**
627             * Run all remaining processors on the procStateList that
628             * have not already run this round with an empty set of
629             * annotations.
630             */
631            public void runContributingProcs(RoundEnvironment re) {
632                if (!onProcInterator) {
633                    Set<TypeElement> emptyTypeElements = Collections.emptySet();
634                    while(innerIter.hasNext()) {
635                        ProcessorState ps = innerIter.next();
636                        if (ps.contributed)
637                            callProcessor(ps.processor, emptyTypeElements, re);
638                    }
639                }
640            }
641        }
642
643        Iterator<? extends Processor> processorIterator;
644        ArrayList<ProcessorState>  procStateList;
645
646        public ProcessorStateIterator iterator() {
647            return new ProcessorStateIterator(this);
648        }
649
650        DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
651            this.processorIterator = processorIterator;
652            this.procStateList = new ArrayList<>();
653        }
654
655        /**
656         * Free jar files, etc. if using a service loader.
657         */
658        public void close() {
659            if (processorIterator != null &&
660                processorIterator instanceof ServiceIterator) {
661                ((ServiceIterator) processorIterator).close();
662            }
663        }
664    }
665
666    private void discoverAndRunProcs(Set<TypeElement> annotationsPresent,
667                                     List<ClassSymbol> topLevelClasses,
668                                     List<PackageSymbol> packageInfoFiles) {
669        Map<String, TypeElement> unmatchedAnnotations = new HashMap<>(annotationsPresent.size());
670
671        for(TypeElement a  : annotationsPresent) {
672                unmatchedAnnotations.put(a.getQualifiedName().toString(),
673                                         a);
674        }
675
676        // Give "*" processors a chance to match
677        if (unmatchedAnnotations.size() == 0)
678            unmatchedAnnotations.put("", null);
679
680        DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
681        // TODO: Create proper argument values; need past round
682        // information to fill in this constructor.  Note that the 1
683        // st round of processing could be the last round if there
684        // were parse errors on the initial source files; however, we
685        // are not doing processing in that case.
686
687        Set<Element> rootElements = new LinkedHashSet<>();
688        rootElements.addAll(topLevelClasses);
689        rootElements.addAll(packageInfoFiles);
690        rootElements = Collections.unmodifiableSet(rootElements);
691
692        RoundEnvironment renv = new JavacRoundEnvironment(false,
693                                                          false,
694                                                          rootElements,
695                                                          JavacProcessingEnvironment.this);
696
697        while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
698            ProcessorState ps = psi.next();
699            Set<String>  matchedNames = new HashSet<>();
700            Set<TypeElement> typeElements = new LinkedHashSet<>();
701
702            for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
703                String unmatchedAnnotationName = entry.getKey();
704                if (ps.annotationSupported(unmatchedAnnotationName) ) {
705                    matchedNames.add(unmatchedAnnotationName);
706                    TypeElement te = entry.getValue();
707                    if (te != null)
708                        typeElements.add(te);
709                }
710            }
711
712            if (matchedNames.size() > 0 || ps.contributed) {
713                boolean processingResult = callProcessor(ps.processor, typeElements, renv);
714                ps.contributed = true;
715                ps.removeSupportedOptions(unmatchedProcessorOptions);
716
717                if (printProcessorInfo || verbose) {
718                    log.printLines("x.print.processor.info",
719                            ps.processor.getClass().getName(),
720                            matchedNames.toString(),
721                            processingResult);
722                }
723
724                if (processingResult) {
725                    unmatchedAnnotations.keySet().removeAll(matchedNames);
726                }
727
728            }
729        }
730        unmatchedAnnotations.remove("");
731
732        if (lint && unmatchedAnnotations.size() > 0) {
733            // Remove annotations processed by javac
734            unmatchedAnnotations.keySet().removeAll(platformAnnotations);
735            if (unmatchedAnnotations.size() > 0) {
736                log.warning("proc.annotations.without.processors",
737                            unmatchedAnnotations.keySet());
738            }
739        }
740
741        // Run contributing processors that haven't run yet
742        psi.runContributingProcs(renv);
743
744        // Debugging
745        if (options.isSet("displayFilerState"))
746            filer.displayState();
747    }
748
749    /**
750     * Computes the set of annotations on the symbol in question.
751     * Leave class public for external testing purposes.
752     */
753    public static class ComputeAnnotationSet extends
754        ElementScanner9<Set<TypeElement>, Set<TypeElement>> {
755        final Elements elements;
756
757        public ComputeAnnotationSet(Elements elements) {
758            super();
759            this.elements = elements;
760        }
761
762        @Override @DefinedBy(Api.LANGUAGE_MODEL)
763        public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
764            // Don't scan enclosed elements of a package
765            return p;
766        }
767
768        @Override @DefinedBy(Api.LANGUAGE_MODEL)
769        public Set<TypeElement> visitType(TypeElement e, Set<TypeElement> p) {
770            // Type parameters are not considered to be enclosed by a type
771            scan(e.getTypeParameters(), p);
772            return super.visitType(e, p);
773        }
774
775        @Override @DefinedBy(Api.LANGUAGE_MODEL)
776        public Set<TypeElement> visitExecutable(ExecutableElement e, Set<TypeElement> p) {
777            // Type parameters are not considered to be enclosed by an executable
778            scan(e.getTypeParameters(), p);
779            return super.visitExecutable(e, p);
780        }
781
782        void addAnnotations(Element e, Set<TypeElement> p) {
783            for (AnnotationMirror annotationMirror :
784                     elements.getAllAnnotationMirrors(e) ) {
785                Element e2 = annotationMirror.getAnnotationType().asElement();
786                p.add((TypeElement) e2);
787            }
788        }
789
790        @Override @DefinedBy(Api.LANGUAGE_MODEL)
791        public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
792            addAnnotations(e, p);
793            return super.scan(e, p);
794        }
795    }
796
797    private boolean callProcessor(Processor proc,
798                                         Set<? extends TypeElement> tes,
799                                         RoundEnvironment renv) {
800        try {
801            return proc.process(tes, renv);
802        } catch (ClassFinder.BadClassFile ex) {
803            log.error("proc.cant.access.1", ex.sym, ex.getDetailValue());
804            return false;
805        } catch (CompletionFailure ex) {
806            StringWriter out = new StringWriter();
807            ex.printStackTrace(new PrintWriter(out));
808            log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
809            return false;
810        } catch (ClientCodeException e) {
811            throw e;
812        } catch (Throwable t) {
813            throw new AnnotationProcessingError(t);
814        }
815    }
816
817    /**
818     * Helper object for a single round of annotation processing.
819     */
820    class Round {
821        /** The round number. */
822        final int number;
823        /** The diagnostic handler for the round. */
824        final Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
825
826        /** The ASTs to be compiled. */
827        List<JCCompilationUnit> roots;
828        /** The trees that need to be cleaned - includes roots and implicitly parsed trees. */
829        Set<JCCompilationUnit> treesToClean;
830        /** The classes to be compiler that have were generated. */
831        Map<String, JavaFileObject> genClassFiles;
832
833        /** The set of annotations to be processed this round. */
834        Set<TypeElement> annotationsPresent;
835        /** The set of top level classes to be processed this round. */
836        List<ClassSymbol> topLevelClasses;
837        /** The set of package-info files to be processed this round. */
838        List<PackageSymbol> packageInfoFiles;
839
840        /** Create a round (common code). */
841        private Round(int number, Set<JCCompilationUnit> treesToClean,
842                Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
843            this.number = number;
844
845            if (number == 1) {
846                Assert.checkNonNull(deferredDiagnosticHandler);
847                this.deferredDiagnosticHandler = deferredDiagnosticHandler;
848            } else {
849                this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
850                compiler.setDeferredDiagnosticHandler(this.deferredDiagnosticHandler);
851            }
852
853            // the following will be populated as needed
854            topLevelClasses  = List.nil();
855            packageInfoFiles = List.nil();
856            this.treesToClean = treesToClean;
857        }
858
859        /** Create the first round. */
860        Round(List<JCCompilationUnit> roots,
861              List<ClassSymbol> classSymbols,
862              Set<JCCompilationUnit> treesToClean,
863              Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
864            this(1, treesToClean, deferredDiagnosticHandler);
865            this.roots = roots;
866            genClassFiles = new HashMap<>();
867
868            // The reverse() in the following line is to maintain behavioural
869            // compatibility with the previous revision of the code. Strictly speaking,
870            // it should not be necessary, but a javah golden file test fails without it.
871            topLevelClasses =
872                getTopLevelClasses(roots).prependList(classSymbols.reverse());
873
874            packageInfoFiles = getPackageInfoFiles(roots);
875
876            findAnnotationsPresent();
877        }
878
879        /** Create a new round. */
880        private Round(Round prev,
881                Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
882            this(prev.number+1, prev.treesToClean, null);
883            prev.newRound();
884            this.genClassFiles = prev.genClassFiles;
885
886            List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
887            roots = prev.roots.appendList(parsedFiles);
888
889            // Check for errors after parsing
890            if (unrecoverableError())
891                return;
892
893            enterClassFiles(genClassFiles);
894            List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
895            genClassFiles.putAll(newClassFiles);
896            enterTrees(roots);
897
898            if (unrecoverableError())
899                return;
900
901            topLevelClasses = join(
902                    getTopLevelClasses(parsedFiles),
903                    getTopLevelClassesFromClasses(newClasses));
904
905            packageInfoFiles = join(
906                    getPackageInfoFiles(parsedFiles),
907                    getPackageInfoFilesFromClasses(newClasses));
908
909            findAnnotationsPresent();
910        }
911
912        /** Create the next round to be used. */
913        Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
914            return new Round(this, newSourceFiles, newClassFiles);
915        }
916
917        /** Prepare the compiler for the final compilation. */
918        void finalCompiler() {
919            newRound();
920        }
921
922        /** Return the number of errors found so far in this round.
923         * This may include uncoverable errors, such as parse errors,
924         * and transient errors, such as missing symbols. */
925        int errorCount() {
926            return compiler.errorCount();
927        }
928
929        /** Return the number of warnings found so far in this round. */
930        int warningCount() {
931            return compiler.warningCount();
932        }
933
934        /** Return whether or not an unrecoverable error has occurred. */
935        boolean unrecoverableError() {
936            if (messager.errorRaised())
937                return true;
938
939            for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
940                switch (d.getKind()) {
941                    case WARNING:
942                        if (werror)
943                            return true;
944                        break;
945
946                    case ERROR:
947                        if (fatalErrors || !d.isFlagSet(RECOVERABLE))
948                            return true;
949                        break;
950                }
951            }
952
953            return false;
954        }
955
956        /** Find the set of annotations present in the set of top level
957         *  classes and package info files to be processed this round. */
958        void findAnnotationsPresent() {
959            ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
960            // Use annotation processing to compute the set of annotations present
961            annotationsPresent = new LinkedHashSet<>();
962            for (ClassSymbol classSym : topLevelClasses)
963                annotationComputer.scan(classSym, annotationsPresent);
964            for (PackageSymbol pkgSym : packageInfoFiles)
965                annotationComputer.scan(pkgSym, annotationsPresent);
966        }
967
968        /** Enter a set of generated class files. */
969        private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
970            List<ClassSymbol> list = List.nil();
971
972            for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) {
973                Name name = names.fromString(entry.getKey());
974                JavaFileObject file = entry.getValue();
975                if (file.getKind() != JavaFileObject.Kind.CLASS)
976                    throw new AssertionError(file);
977                ClassSymbol cs;
978                if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
979                    Name packageName = Convert.packagePart(name);
980                    PackageSymbol p = symtab.enterPackage(packageName);
981                    if (p.package_info == null)
982                        p.package_info = symtab.enterClass(Convert.shortName(name), p);
983                    cs = p.package_info;
984                    cs.reset();
985                    if (cs.classfile == null)
986                        cs.classfile = file;
987                    cs.completer = initialCompleter;
988                } else {
989                    cs = symtab.enterClass(name);
990                    cs.reset();
991                    cs.classfile = file;
992                    cs.completer = initialCompleter;
993                }
994                list = list.prepend(cs);
995            }
996            return list.reverse();
997        }
998
999        /** Enter a set of syntax trees. */
1000        private void enterTrees(List<JCCompilationUnit> roots) {
1001            compiler.enterTrees(roots);
1002        }
1003
1004        /** Run a processing round. */
1005        void run(boolean lastRound, boolean errorStatus) {
1006            printRoundInfo(lastRound);
1007
1008            if (!taskListener.isEmpty())
1009                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1010
1011            try {
1012                if (lastRound) {
1013                    filer.setLastRound(true);
1014                    Set<Element> emptyRootElements = Collections.emptySet(); // immutable
1015                    RoundEnvironment renv = new JavacRoundEnvironment(true,
1016                            errorStatus,
1017                            emptyRootElements,
1018                            JavacProcessingEnvironment.this);
1019                    discoveredProcs.iterator().runContributingProcs(renv);
1020                } else {
1021                    discoverAndRunProcs(annotationsPresent, topLevelClasses, packageInfoFiles);
1022                }
1023            } catch (Throwable t) {
1024                // we're specifically expecting Abort here, but if any Throwable
1025                // comes by, we should flush all deferred diagnostics, rather than
1026                // drop them on the ground.
1027                deferredDiagnosticHandler.reportDeferredDiagnostics();
1028                log.popDiagnosticHandler(deferredDiagnosticHandler);
1029                compiler.setDeferredDiagnosticHandler(null);
1030                throw t;
1031            } finally {
1032                if (!taskListener.isEmpty())
1033                    taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1034            }
1035        }
1036
1037        void showDiagnostics(boolean showAll) {
1038            Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
1039            if (!showAll) {
1040                // suppress errors, which are all presumed to be transient resolve errors
1041                kinds.remove(JCDiagnostic.Kind.ERROR);
1042            }
1043            deferredDiagnosticHandler.reportDeferredDiagnostics(kinds);
1044            log.popDiagnosticHandler(deferredDiagnosticHandler);
1045            compiler.setDeferredDiagnosticHandler(null);
1046        }
1047
1048        /** Print info about this round. */
1049        private void printRoundInfo(boolean lastRound) {
1050            if (printRounds || verbose) {
1051                List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
1052                Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
1053                log.printLines("x.print.rounds",
1054                        number,
1055                        "{" + tlc.toString(", ") + "}",
1056                        ap,
1057                        lastRound);
1058            }
1059        }
1060
1061        /** Prepare for new round of annotation processing. Cleans trees, resets symbols, and
1062         * asks selected services to prepare to a new round of annotation processing.
1063         */
1064        private void newRound() {
1065            //ensure treesToClean contains all trees, including implicitly parsed ones
1066            for (Env<AttrContext> env : enter.getEnvs()) {
1067                treesToClean.add(env.toplevel);
1068            }
1069            for (JCCompilationUnit node : treesToClean) {
1070                treeCleaner.scan(node);
1071            }
1072            chk.newRound();
1073            enter.newRound();
1074            filer.newRound();
1075            messager.newRound();
1076            compiler.newRound();
1077            types.newRound();
1078
1079            boolean foundError = false;
1080
1081            for (ClassSymbol cs : symtab.classes.values()) {
1082                if (cs.kind == Kinds.ERR) {
1083                    foundError = true;
1084                    break;
1085                }
1086            }
1087
1088            if (foundError) {
1089                for (ClassSymbol cs : symtab.classes.values()) {
1090                    if (cs.classfile != null || cs.kind == Kinds.ERR) {
1091                        cs.reset();
1092                        cs.type = new ClassType(cs.type.getEnclosingType(),
1093                                                null, cs, Type.noAnnotations);
1094                        if (cs.completer == null) {
1095                            cs.completer = initialCompleter;
1096                        }
1097                    }
1098                }
1099            }
1100        }
1101    }
1102
1103
1104    // TODO: internal catch clauses?; catch and rethrow an annotation
1105    // processing error
1106    public boolean doProcessing(List<JCCompilationUnit> roots,
1107                                List<ClassSymbol> classSymbols,
1108                                Iterable<? extends PackageSymbol> pckSymbols,
1109                                Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
1110        final Set<JCCompilationUnit> treesToClean =
1111                Collections.newSetFromMap(new IdentityHashMap<JCCompilationUnit, Boolean>());
1112
1113        //fill already attributed implicit trees:
1114        for (Env<AttrContext> env : enter.getEnvs()) {
1115            treesToClean.add(env.toplevel);
1116        }
1117
1118        Set<PackageSymbol> specifiedPackages = new LinkedHashSet<>();
1119        for (PackageSymbol psym : pckSymbols)
1120            specifiedPackages.add(psym);
1121        this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
1122
1123        Round round = new Round(roots, classSymbols, treesToClean, deferredDiagnosticHandler);
1124
1125        boolean errorStatus;
1126        boolean moreToDo;
1127        do {
1128            // Run processors for round n
1129            round.run(false, false);
1130
1131            // Processors for round n have run to completion.
1132            // Check for errors and whether there is more work to do.
1133            errorStatus = round.unrecoverableError();
1134            moreToDo = moreToDo();
1135
1136            round.showDiagnostics(errorStatus || showResolveErrors);
1137
1138            // Set up next round.
1139            // Copy mutable collections returned from filer.
1140            round = round.next(
1141                    new LinkedHashSet<>(filer.getGeneratedSourceFileObjects()),
1142                    new LinkedHashMap<>(filer.getGeneratedClasses()));
1143
1144             // Check for errors during setup.
1145            if (round.unrecoverableError())
1146                errorStatus = true;
1147
1148        } while (moreToDo && !errorStatus);
1149
1150        // run last round
1151        round.run(true, errorStatus);
1152        round.showDiagnostics(true);
1153
1154        filer.warnIfUnclosedFiles();
1155        warnIfUnmatchedOptions();
1156
1157        /*
1158         * If an annotation processor raises an error in a round,
1159         * that round runs to completion and one last round occurs.
1160         * The last round may also occur because no more source or
1161         * class files have been generated.  Therefore, if an error
1162         * was raised on either of the last *two* rounds, the compile
1163         * should exit with a nonzero exit code.  The current value of
1164         * errorStatus holds whether or not an error was raised on the
1165         * second to last round; errorRaised() gives the error status
1166         * of the last round.
1167         */
1168        if (messager.errorRaised()
1169                || werror && round.warningCount() > 0 && round.errorCount() > 0)
1170            errorStatus = true;
1171
1172        Set<JavaFileObject> newSourceFiles =
1173                new LinkedHashSet<>(filer.getGeneratedSourceFileObjects());
1174        roots = round.roots;
1175
1176        errorStatus = errorStatus || (compiler.errorCount() > 0);
1177
1178        if (!errorStatus)
1179            round.finalCompiler();
1180
1181        if (newSourceFiles.size() > 0)
1182            roots = roots.appendList(compiler.parseFiles(newSourceFiles));
1183
1184        errorStatus = errorStatus || (compiler.errorCount() > 0);
1185
1186        // Free resources
1187        this.close();
1188
1189        if (!taskListener.isEmpty())
1190            taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1191
1192        if (errorStatus) {
1193            if (compiler.errorCount() == 0)
1194                compiler.log.nerrors++;
1195            return true;
1196        }
1197
1198        compiler.enterTreesIfNeeded(roots);
1199
1200        return true;
1201    }
1202
1203    private void warnIfUnmatchedOptions() {
1204        if (!unmatchedProcessorOptions.isEmpty()) {
1205            log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
1206        }
1207    }
1208
1209    /**
1210     * Free resources related to annotation processing.
1211     */
1212    public void close() {
1213        filer.close();
1214        if (discoveredProcs != null) // Make calling close idempotent
1215            discoveredProcs.close();
1216        discoveredProcs = null;
1217    }
1218
1219    private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
1220        List<ClassSymbol> classes = List.nil();
1221        for (JCCompilationUnit unit : units) {
1222            for (JCTree node : unit.defs) {
1223                if (node.hasTag(JCTree.Tag.CLASSDEF)) {
1224                    ClassSymbol sym = ((JCClassDecl) node).sym;
1225                    Assert.checkNonNull(sym);
1226                    classes = classes.prepend(sym);
1227                }
1228            }
1229        }
1230        return classes.reverse();
1231    }
1232
1233    private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
1234        List<ClassSymbol> classes = List.nil();
1235        for (ClassSymbol sym : syms) {
1236            if (!isPkgInfo(sym)) {
1237                classes = classes.prepend(sym);
1238            }
1239        }
1240        return classes.reverse();
1241    }
1242
1243    private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
1244        List<PackageSymbol> packages = List.nil();
1245        for (JCCompilationUnit unit : units) {
1246            if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
1247                packages = packages.prepend(unit.packge);
1248            }
1249        }
1250        return packages.reverse();
1251    }
1252
1253    private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
1254        List<PackageSymbol> packages = List.nil();
1255        for (ClassSymbol sym : syms) {
1256            if (isPkgInfo(sym)) {
1257                packages = packages.prepend((PackageSymbol) sym.owner);
1258            }
1259        }
1260        return packages.reverse();
1261    }
1262
1263    // avoid unchecked warning from use of varargs
1264    private static <T> List<T> join(List<T> list1, List<T> list2) {
1265        return list1.appendList(list2);
1266    }
1267
1268    private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
1269        return fo.isNameCompatible("package-info", kind);
1270    }
1271
1272    private boolean isPkgInfo(ClassSymbol sym) {
1273        return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
1274    }
1275
1276    /*
1277     * Called retroactively to determine if a class loader was required,
1278     * after we have failed to create one.
1279     */
1280    private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
1281        if (procNames != null)
1282            return true;
1283
1284        URL[] urls = new URL[1];
1285        for(File pathElement : workingpath) {
1286            try {
1287                urls[0] = pathElement.toURI().toURL();
1288                if (ServiceProxy.hasService(Processor.class, urls))
1289                    return true;
1290            } catch (MalformedURLException ex) {
1291                throw new AssertionError(ex);
1292            }
1293            catch (ServiceProxy.ServiceConfigurationError e) {
1294                log.error("proc.bad.config.file", e.getLocalizedMessage());
1295                return true;
1296            }
1297        }
1298
1299        return false;
1300    }
1301
1302    class ImplicitCompleter implements Completer {
1303
1304        private final JCCompilationUnit topLevel;
1305
1306        public ImplicitCompleter(JCCompilationUnit topLevel) {
1307            this.topLevel = topLevel;
1308        }
1309
1310        @Override public void complete(Symbol sym) throws CompletionFailure {
1311            compiler.readSourceFile(topLevel, (ClassSymbol) sym);
1312        }
1313    }
1314
1315    private final TreeScanner treeCleaner = new TreeScanner() {
1316            public void scan(JCTree node) {
1317                super.scan(node);
1318                if (node != null)
1319                    node.type = null;
1320            }
1321            JCCompilationUnit topLevel;
1322            public void visitTopLevel(JCCompilationUnit node) {
1323                if (node.packge != null) {
1324                    if (node.packge.package_info != null) {
1325                        node.packge.package_info.reset();
1326                    }
1327                    node.packge.reset();
1328                }
1329                node.packge = null;
1330                topLevel = node;
1331                try {
1332                    super.visitTopLevel(node);
1333                } finally {
1334                    topLevel = null;
1335                }
1336            }
1337            public void visitClassDef(JCClassDecl node) {
1338                if (node.sym != null) {
1339                    node.sym.reset();
1340                    node.sym.completer = new ImplicitCompleter(topLevel);
1341                }
1342                node.sym = null;
1343                super.visitClassDef(node);
1344            }
1345            public void visitMethodDef(JCMethodDecl node) {
1346                node.sym = null;
1347                super.visitMethodDef(node);
1348            }
1349            public void visitVarDef(JCVariableDecl node) {
1350                node.sym = null;
1351                super.visitVarDef(node);
1352            }
1353            public void visitNewClass(JCNewClass node) {
1354                node.constructor = null;
1355                super.visitNewClass(node);
1356            }
1357            public void visitAssignop(JCAssignOp node) {
1358                node.operator = null;
1359                super.visitAssignop(node);
1360            }
1361            public void visitUnary(JCUnary node) {
1362                node.operator = null;
1363                super.visitUnary(node);
1364            }
1365            public void visitBinary(JCBinary node) {
1366                node.operator = null;
1367                super.visitBinary(node);
1368            }
1369            public void visitSelect(JCFieldAccess node) {
1370                node.sym = null;
1371                super.visitSelect(node);
1372            }
1373            public void visitIdent(JCIdent node) {
1374                node.sym = null;
1375                super.visitIdent(node);
1376            }
1377            public void visitAnnotation(JCAnnotation node) {
1378                node.attribute = null;
1379                super.visitAnnotation(node);
1380            }
1381        };
1382
1383
1384    private boolean moreToDo() {
1385        return filer.newFiles();
1386    }
1387
1388    /**
1389     * {@inheritdoc}
1390     *
1391     * Command line options suitable for presenting to annotation
1392     * processors.
1393     * {@literal "-Afoo=bar"} should be {@literal "-Afoo" => "bar"}.
1394     */
1395    @DefinedBy(Api.ANNOTATION_PROCESSING)
1396    public Map<String,String> getOptions() {
1397        return processorOptions;
1398    }
1399
1400    @DefinedBy(Api.ANNOTATION_PROCESSING)
1401    public Messager getMessager() {
1402        return messager;
1403    }
1404
1405    @DefinedBy(Api.ANNOTATION_PROCESSING)
1406    public Filer getFiler() {
1407        return filer;
1408    }
1409
1410    @DefinedBy(Api.ANNOTATION_PROCESSING)
1411    public JavacElements getElementUtils() {
1412        return elementUtils;
1413    }
1414
1415    @DefinedBy(Api.ANNOTATION_PROCESSING)
1416    public JavacTypes getTypeUtils() {
1417        return typeUtils;
1418    }
1419
1420    @DefinedBy(Api.ANNOTATION_PROCESSING)
1421    public SourceVersion getSourceVersion() {
1422        return Source.toSourceVersion(source);
1423    }
1424
1425    @DefinedBy(Api.ANNOTATION_PROCESSING)
1426    public Locale getLocale() {
1427        return messages.getCurrentLocale();
1428    }
1429
1430    public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
1431        return specifiedPackages;
1432    }
1433
1434    private static final Pattern allMatches = Pattern.compile(".*");
1435    public static final Pattern noMatches  = Pattern.compile("(\\P{all})+");
1436
1437    /**
1438     * Convert import-style string for supported annotations into a
1439     * regex matching that string.  If the string is a valid
1440     * import-style string, return a regex that won't match anything.
1441     */
1442    private static Pattern importStringToPattern(String s, Processor p, Log log) {
1443        if (isValidImportString(s)) {
1444            return validImportStringToPattern(s);
1445        } else {
1446            log.warning("proc.malformed.supported.string", s, p.getClass().getName());
1447            return noMatches; // won't match any valid identifier
1448        }
1449    }
1450
1451    /**
1452     * Return true if the argument string is a valid import-style
1453     * string specifying claimed annotations; return false otherwise.
1454     */
1455    public static boolean isValidImportString(String s) {
1456        if (s.equals("*"))
1457            return true;
1458
1459        boolean valid = true;
1460        String t = s;
1461        int index = t.indexOf('*');
1462
1463        if (index != -1) {
1464            // '*' must be last character...
1465            if (index == t.length() -1) {
1466                // ... any and preceding character must be '.'
1467                if ( index-1 >= 0 ) {
1468                    valid = t.charAt(index-1) == '.';
1469                    // Strip off ".*$" for identifier checks
1470                    t = t.substring(0, t.length()-2);
1471                }
1472            } else
1473                return false;
1474        }
1475
1476        // Verify string is off the form (javaId \.)+ or javaId
1477        if (valid) {
1478            String[] javaIds = t.split("\\.", t.length()+2);
1479            for(String javaId: javaIds)
1480                valid &= SourceVersion.isIdentifier(javaId);
1481        }
1482        return valid;
1483    }
1484
1485    public static Pattern validImportStringToPattern(String s) {
1486        if (s.equals("*")) {
1487            return allMatches;
1488        } else {
1489            String s_prime = s.replace(".", "\\.");
1490
1491            if (s_prime.endsWith("*")) {
1492                s_prime =  s_prime.substring(0, s_prime.length() - 1) + ".+";
1493            }
1494
1495            return Pattern.compile(s_prime);
1496        }
1497    }
1498
1499    /**
1500     * For internal use only.  This method may be removed without warning.
1501     */
1502    public Context getContext() {
1503        return context;
1504    }
1505
1506    /**
1507     * For internal use only.  This method may be removed without warning.
1508     */
1509    public ClassLoader getProcessorClassLoader() {
1510        return processorClassLoader;
1511    }
1512
1513    public String toString() {
1514        return "javac ProcessingEnvironment";
1515    }
1516
1517    public static boolean isValidOptionName(String optionName) {
1518        for(String s : optionName.split("\\.", -1)) {
1519            if (!SourceVersion.isIdentifier(s))
1520                return false;
1521        }
1522        return true;
1523    }
1524}
1525