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