1 /*
   2  * Copyright (c) 2005, 2019, 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 
  26 package com.sun.tools.javac.model;
  27 
  28 import java.util.Collections;
  29 import java.util.HashMap;
  30 import java.util.HashSet;
  31 import java.util.LinkedHashSet;
  32 import java.util.Map;
  33 import java.util.Optional;
  34 import java.util.Set;
  35 import java.util.stream.Collectors;
  36 
  37 import javax.lang.model.AnnotatedConstruct;
  38 import javax.lang.model.SourceVersion;
  39 import javax.lang.model.element.*;
  40 import javax.lang.model.type.DeclaredType;
  41 import javax.lang.model.util.Elements;
  42 import javax.tools.JavaFileObject;
  43 import static javax.lang.model.util.ElementFilter.methodsIn;
  44 
  45 import com.sun.source.util.JavacTask;
  46 import com.sun.tools.javac.api.JavacTaskImpl;
  47 import com.sun.tools.javac.code.*;
  48 import com.sun.tools.javac.code.Attribute.Compound;
  49 import com.sun.tools.javac.code.Directive.ExportsDirective;
  50 import com.sun.tools.javac.code.Directive.ExportsFlag;
  51 import com.sun.tools.javac.code.Directive.OpensDirective;
  52 import com.sun.tools.javac.code.Directive.OpensFlag;
  53 import com.sun.tools.javac.code.Directive.RequiresDirective;
  54 import com.sun.tools.javac.code.Directive.RequiresFlag;
  55 import com.sun.tools.javac.code.Scope.WriteableScope;
  56 import com.sun.tools.javac.code.Source.Feature;
  57 import com.sun.tools.javac.code.Symbol.*;
  58 import com.sun.tools.javac.comp.AttrContext;
  59 import com.sun.tools.javac.comp.Enter;
  60 import com.sun.tools.javac.comp.Env;
  61 import com.sun.tools.javac.main.JavaCompiler;
  62 import com.sun.tools.javac.processing.PrintingProcessor;
  63 import com.sun.tools.javac.tree.JCTree;
  64 import com.sun.tools.javac.tree.JCTree.*;
  65 import com.sun.tools.javac.tree.TreeInfo;
  66 import com.sun.tools.javac.tree.TreeScanner;
  67 import com.sun.tools.javac.util.*;
  68 import com.sun.tools.javac.util.DefinedBy.Api;
  69 import com.sun.tools.javac.util.Name;
  70 import static com.sun.tools.javac.code.Kinds.Kind.*;
  71 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  72 import static com.sun.tools.javac.code.TypeTag.CLASS;
  73 import com.sun.tools.javac.comp.Modules;
  74 import com.sun.tools.javac.comp.Resolve;
  75 import com.sun.tools.javac.comp.Resolve.RecoveryLoadClass;
  76 import com.sun.tools.javac.resources.CompilerProperties.Notes;
  77 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  78 
  79 /**
  80  * Utility methods for operating on program elements.
  81  *
  82  * <p><b>This is NOT part of any supported API.
  83  * If you write code that depends on this, you do so at your own
  84  * risk.  This code and its internal interfaces are subject to change
  85  * or deletion without notice.</b></p>
  86  */
  87 public class JavacElements implements Elements {
  88 
  89     private final JavaCompiler javaCompiler;
  90     private final Symtab syms;
  91     private final Modules modules;
  92     private final Names names;
  93     private final Types types;
  94     private final Enter enter;
  95     private final Resolve resolve;
  96     private final JavacTaskImpl javacTaskImpl;
  97     private final Log log;
  98     private final boolean allowModules;
  99 
 100     public static JavacElements instance(Context context) {
 101         JavacElements instance = context.get(JavacElements.class);
 102         if (instance == null)
 103             instance = new JavacElements(context);
 104         return instance;
 105     }
 106 
 107     protected JavacElements(Context context) {
 108         context.put(JavacElements.class, this);
 109         javaCompiler = JavaCompiler.instance(context);
 110         syms = Symtab.instance(context);
 111         modules = Modules.instance(context);
 112         names = Names.instance(context);
 113         types = Types.instance(context);
 114         enter = Enter.instance(context);
 115         resolve = Resolve.instance(context);
 116         JavacTask t = context.get(JavacTask.class);
 117         javacTaskImpl = t instanceof JavacTaskImpl ? (JavacTaskImpl) t : null;
 118         log = Log.instance(context);
 119         Source source = Source.instance(context);
 120         allowModules = Feature.MODULES.allowedInSource(source);
 121     }
 122 
 123     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 124     public Set<? extends ModuleElement> getAllModuleElements() {
 125         if (allowModules)
 126             return Collections.unmodifiableSet(modules.allModules());
 127         else
 128             return Collections.emptySet();
 129     }
 130 
 131     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 132     public ModuleSymbol getModuleElement(CharSequence name) {
 133         ensureEntered("getModuleElement");
 134         if (modules.getDefaultModule() == syms.noModule)
 135             return null;
 136         String strName = name.toString();
 137         if (strName.equals(""))
 138             return syms.unnamedModule;
 139         return modules.getObservableModule(names.fromString(strName));
 140     }
 141 
 142     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 143     public PackageSymbol getPackageElement(CharSequence name) {
 144         return doGetPackageElement(null, name);
 145     }
 146 
 147     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 148     public PackageSymbol getPackageElement(ModuleElement module, CharSequence name) {
 149         module.getClass();
 150         return doGetPackageElement(module, name);
 151     }
 152 
 153     private PackageSymbol doGetPackageElement(ModuleElement module, CharSequence name) {
 154         ensureEntered("getPackageElement");
 155         return doGetElement(module, "getPackageElement", name, PackageSymbol.class);
 156     }
 157 
 158     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 159     public ClassSymbol getTypeElement(CharSequence name) {
 160         return doGetTypeElement(null, name);
 161     }
 162 
 163     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 164     public ClassSymbol getTypeElement(ModuleElement module, CharSequence name) {
 165         module.getClass();
 166 
 167         return doGetTypeElement(module, name);
 168     }
 169 
 170     private ClassSymbol doGetTypeElement(ModuleElement module, CharSequence name) {
 171         ensureEntered("getTypeElement");
 172         return doGetElement(module, "getTypeElement", name, ClassSymbol.class);
 173     }
 174 
 175     private <S extends Symbol> S doGetElement(ModuleElement module, String methodName,
 176                                               CharSequence name, Class<S> clazz) {
 177         String strName = name.toString();
 178         if (!SourceVersion.isName(strName) && (!strName.isEmpty() || clazz == ClassSymbol.class)) {
 179             return null;
 180         }
 181         if (module == null) {
 182             return unboundNameToSymbol(methodName, strName, clazz);
 183         } else {
 184             return nameToSymbol((ModuleSymbol) module, strName, clazz);
 185         }
 186     }
 187 
 188     private final Set<String> alreadyWarnedDuplicates = new HashSet<>();
 189     private final Map<Pair<String, String>, Optional<Symbol>> resultCache = new HashMap<>();
 190 
 191     @SuppressWarnings("unchecked")
 192     private <S extends Symbol> S unboundNameToSymbol(String methodName,
 193                                                      String nameStr,
 194                                                      Class<S> clazz) {
 195         if (modules.getDefaultModule() == syms.noModule) { //not a modular mode:
 196             return nameToSymbol(syms.noModule, nameStr, clazz);
 197         }
 198 
 199         return (S) resultCache.computeIfAbsent(Pair.of(methodName, nameStr), p -> {
 200             Set<S> found = new LinkedHashSet<>();
 201 
 202             for (ModuleSymbol msym : modules.allModules()) {
 203                 S sym = nameToSymbol(msym, nameStr, clazz);
 204 
 205                 if (sym == null)
 206                     continue;
 207 
 208                 if (clazz == ClassSymbol.class) {
 209                     // Always include classes
 210                     found.add(sym);
 211                 } else if (clazz == PackageSymbol.class) {
 212                     // In module mode, ignore the "spurious" empty packages that "enclose" module-specific packages.
 213                     // For example, if a module contains classes or package info in package p.q.r, it will also appear
 214                     // to have additional packages p.q and p, even though these packages have no content other
 215                     // than the subpackage.  We don't want those empty packages showing up in searches for p or p.q.
 216                     if (!sym.members().isEmpty() || ((PackageSymbol) sym).package_info != null) {
 217                         found.add(sym);
 218                     }
 219                 }
 220             }
 221 
 222             if (found.size() == 1) {
 223                 return Optional.of(found.iterator().next());
 224             } else if (found.size() > 1) {
 225                 //more than one element found, produce a note:
 226                 if (alreadyWarnedDuplicates.add(methodName + ":" + nameStr)) {
 227                     String moduleNames = found.stream()
 228                                               .map(s -> s.packge().modle)
 229                                               .map(m -> m.toString())
 230                                               .collect(Collectors.joining(", "));
 231                     log.note(Notes.MultipleElements(methodName, nameStr, moduleNames));
 232                 }
 233                 return Optional.empty();
 234             } else {
 235                 //not found:
 236                 return Optional.empty();
 237             }
 238         }).orElse(null);
 239     }
 240 
 241     /**
 242      * Returns a symbol given the type's or package's canonical name,
 243      * or null if the name isn't found.
 244      */
 245     private <S extends Symbol> S nameToSymbol(ModuleSymbol module, String nameStr, Class<S> clazz) {
 246         Name name = names.fromString(nameStr);
 247         // First check cache.
 248         Symbol sym = (clazz == ClassSymbol.class)
 249                     ? syms.getClass(module, name)
 250                     : syms.lookupPackage(module, name);
 251 
 252         try {
 253             if (sym == null)
 254                 sym = javaCompiler.resolveIdent(module, nameStr);
 255 
 256             if (clazz.isInstance(sym)) {
 257                 sym.complete();
 258                 if (sym.kind != ERR &&
 259                     sym.exists() &&
 260                     name.equals(sym.getQualifiedName())) {
 261                     return clazz.cast(sym);
 262                 }
 263             }
 264             return null;
 265         } catch (CompletionFailure cf) {
 266             cf.dcfh.handleAPICompletionFailure(cf);
 267             return null;
 268         }
 269     }
 270 
 271     /**
 272      * Returns the tree for an annotation given the annotated element
 273      * and the element's own tree.  Returns null if the tree cannot be found.
 274      */
 275     private JCTree matchAnnoToTree(AnnotationMirror findme,
 276                                    Element e, JCTree tree) {
 277         Symbol sym = cast(Symbol.class, e);
 278         class Vis extends JCTree.Visitor {
 279             List<JCAnnotation> result = null;
 280             public void visitPackageDef(JCPackageDecl tree) {
 281                 result = tree.annotations;
 282             }
 283             public void visitClassDef(JCClassDecl tree) {
 284                 result = tree.mods.annotations;
 285             }
 286             public void visitMethodDef(JCMethodDecl tree) {
 287                 result = tree.mods.annotations;
 288             }
 289             public void visitVarDef(JCVariableDecl tree) {
 290                 result = tree.mods.annotations;
 291             }
 292             @Override
 293             public void visitTypeParameter(JCTypeParameter tree) {
 294                 result = tree.annotations;
 295             }
 296         }
 297         Vis vis = new Vis();
 298         tree.accept(vis);
 299         if (vis.result == null)
 300             return null;
 301 
 302         List<Attribute.Compound> annos = sym.getAnnotationMirrors();
 303         return matchAnnoToTree(cast(Attribute.Compound.class, findme),
 304                                annos,
 305                                vis.result);
 306     }
 307 
 308     /**
 309      * Returns the tree for an annotation given a list of annotations
 310      * in which to search (recursively) and their corresponding trees.
 311      * Returns null if the tree cannot be found.
 312      */
 313     private JCTree matchAnnoToTree(Attribute.Compound findme,
 314                                    List<Attribute.Compound> annos,
 315                                    List<JCAnnotation> trees) {
 316         for (Attribute.Compound anno : annos) {
 317             for (JCAnnotation tree : trees) {
 318                 if (tree.type.tsym != anno.type.tsym)
 319                     continue;
 320                 JCTree match = matchAttributeToTree(findme, anno, tree);
 321                 if (match != null)
 322                     return match;
 323             }
 324         }
 325         return null;
 326     }
 327 
 328     /**
 329      * Returns the tree for an attribute given an enclosing attribute to
 330      * search (recursively) and the enclosing attribute's corresponding tree.
 331      * Returns null if the tree cannot be found.
 332      */
 333     private JCTree matchAttributeToTree(final Attribute findme,
 334                                         final Attribute attr,
 335                                         final JCTree tree) {
 336         if (attr == findme)
 337             return tree;
 338 
 339         class Vis implements Attribute.Visitor {
 340             JCTree result = null;
 341             public void visitConstant(Attribute.Constant value) {
 342             }
 343             public void visitClass(Attribute.Class clazz) {
 344             }
 345             public void visitCompound(Attribute.Compound anno) {
 346                 for (Pair<MethodSymbol, Attribute> pair : anno.values) {
 347                     JCExpression expr = scanForAssign(pair.fst, tree);
 348                     if (expr != null) {
 349                         JCTree match = matchAttributeToTree(findme, pair.snd, expr);
 350                         if (match != null) {
 351                             result = match;
 352                             return;
 353                         }
 354                     }
 355                 }
 356             }
 357             public void visitArray(Attribute.Array array) {
 358                 if (tree.hasTag(NEWARRAY)) {
 359                     List<JCExpression> elems = ((JCNewArray)tree).elems;
 360                     for (Attribute value : array.values) {
 361                         JCTree match = matchAttributeToTree(findme, value, elems.head);
 362                         if (match != null) {
 363                             result = match;
 364                             return;
 365                         }
 366                         elems = elems.tail;
 367                     }
 368                 } else if (array.values.length == 1) {
 369                     // the tree may not be a NEWARRAY for single-element array initializers
 370                     result = matchAttributeToTree(findme, array.values[0], tree);
 371                 }
 372             }
 373             public void visitEnum(Attribute.Enum e) {
 374             }
 375             public void visitError(Attribute.Error e) {
 376             }
 377         }
 378         Vis vis = new Vis();
 379         attr.accept(vis);
 380         return vis.result;
 381     }
 382 
 383     /**
 384      * Scans for a JCAssign node with a LHS matching a given
 385      * symbol, and returns its RHS.  Does not scan nested JCAnnotations.
 386      */
 387     private JCExpression scanForAssign(final MethodSymbol sym,
 388                                        final JCTree tree) {
 389         class TS extends TreeScanner {
 390             JCExpression result = null;
 391             public void scan(JCTree t) {
 392                 if (t != null && result == null)
 393                     t.accept(this);
 394             }
 395             public void visitAnnotation(JCAnnotation t) {
 396                 if (t == tree)
 397                     scan(t.args);
 398             }
 399             public void visitAssign(JCAssign t) {
 400                 if (t.lhs.hasTag(IDENT)) {
 401                     JCIdent ident = (JCIdent) t.lhs;
 402                     if (ident.sym == sym)
 403                         result = t.rhs;
 404                 }
 405             }
 406         }
 407         TS scanner = new TS();
 408         tree.accept(scanner);
 409         return scanner.result;
 410     }
 411 
 412     /**
 413      * Returns the tree node corresponding to this element, or null
 414      * if none can be found.
 415      */
 416     public JCTree getTree(Element e) {
 417         Pair<JCTree, ?> treeTop = getTreeAndTopLevel(e);
 418         return (treeTop != null) ? treeTop.fst : null;
 419     }
 420 
 421     @DefinedBy(Api.LANGUAGE_MODEL)
 422     public String getDocComment(Element e) {
 423         // Our doc comment is contained in a map in our toplevel,
 424         // indexed by our tree.  Find our enter environment, which gives
 425         // us our toplevel.  It also gives us a tree that contains our
 426         // tree:  walk it to find our tree.  This is painful.
 427         Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
 428         if (treeTop == null)
 429             return null;
 430         JCTree tree = treeTop.fst;
 431         JCCompilationUnit toplevel = treeTop.snd;
 432         if (toplevel.docComments == null)
 433             return null;
 434         return toplevel.docComments.getCommentText(tree);
 435     }
 436 
 437     @DefinedBy(Api.LANGUAGE_MODEL)
 438     public PackageElement getPackageOf(Element e) {
 439         if (e.getKind() == ElementKind.MODULE)
 440             return null;
 441         else
 442             return cast(Symbol.class, e).packge();
 443     }
 444 
 445     @DefinedBy(Api.LANGUAGE_MODEL)
 446     public ModuleElement getModuleOf(Element e) {
 447         Symbol sym = cast(Symbol.class, e);
 448         if (modules.getDefaultModule() == syms.noModule)
 449             return null;
 450         return (sym.kind == MDL) ? ((ModuleElement) e) : sym.packge().modle;
 451     }
 452 
 453     @DefinedBy(Api.LANGUAGE_MODEL)
 454     public boolean isDeprecated(Element e) {
 455         Symbol sym = cast(Symbol.class, e);
 456         sym.apiComplete();
 457         return sym.isDeprecated();
 458     }
 459 
 460     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 461     public Origin getOrigin(Element e) {
 462         Symbol sym = cast(Symbol.class, e);
 463         if ((sym.flags() & Flags.GENERATEDCONSTR) != 0)
 464             return Origin.MANDATED;
 465         //TypeElement.getEnclosedElements does not return synthetic elements,
 466         //and most synthetic elements are not read from the classfile anyway:
 467         return Origin.EXPLICIT;
 468     }
 469 
 470     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 471     public Origin getOrigin(AnnotatedConstruct c, AnnotationMirror a) {
 472         Compound ac = cast(Compound.class, a);
 473         if (ac.isSynthesized())
 474             return Origin.MANDATED;
 475         return Origin.EXPLICIT;
 476     }
 477 
 478     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 479     public Origin getOrigin(ModuleElement m, ModuleElement.Directive directive) {
 480         switch (directive.getKind()) {
 481             case REQUIRES:
 482                 RequiresDirective rd = cast(RequiresDirective.class, directive);
 483                 if (rd.flags.contains(RequiresFlag.MANDATED))
 484                     return Origin.MANDATED;
 485                 if (rd.flags.contains(RequiresFlag.SYNTHETIC))
 486                     return Origin.SYNTHETIC;
 487                 return Origin.EXPLICIT;
 488             case EXPORTS:
 489                 ExportsDirective ed = cast(ExportsDirective.class, directive);
 490                 if (ed.flags.contains(ExportsFlag.MANDATED))
 491                     return Origin.MANDATED;
 492                 if (ed.flags.contains(ExportsFlag.SYNTHETIC))
 493                     return Origin.SYNTHETIC;
 494                 return Origin.EXPLICIT;
 495             case OPENS:
 496                 OpensDirective od = cast(OpensDirective.class, directive);
 497                 if (od.flags.contains(OpensFlag.MANDATED))
 498                     return Origin.MANDATED;
 499                 if (od.flags.contains(OpensFlag.SYNTHETIC))
 500                     return Origin.SYNTHETIC;
 501                 return Origin.EXPLICIT;
 502         }
 503         return Origin.EXPLICIT;
 504     }
 505 
 506     @DefinedBy(Api.LANGUAGE_MODEL)
 507     public Name getBinaryName(TypeElement type) {
 508         return cast(TypeSymbol.class, type).flatName();
 509     }
 510 
 511     @DefinedBy(Api.LANGUAGE_MODEL)
 512     public Map<MethodSymbol, Attribute> getElementValuesWithDefaults(
 513                                                         AnnotationMirror a) {
 514         Attribute.Compound anno = cast(Attribute.Compound.class, a);
 515         DeclaredType annotype = a.getAnnotationType();
 516         Map<MethodSymbol, Attribute> valmap = anno.getElementValues();
 517 
 518         for (ExecutableElement ex :
 519                  methodsIn(annotype.asElement().getEnclosedElements())) {
 520             MethodSymbol meth = (MethodSymbol) ex;
 521             Attribute defaultValue = meth.getDefaultValue();
 522             if (defaultValue != null && !valmap.containsKey(meth)) {
 523                 valmap.put(meth, defaultValue);
 524             }
 525         }
 526         return valmap;
 527     }
 528 
 529     /**
 530      * {@inheritDoc}
 531      */
 532     @DefinedBy(Api.LANGUAGE_MODEL)
 533     public FilteredMemberList getAllMembers(TypeElement element) {
 534         Symbol sym = cast(Symbol.class, element);
 535         WriteableScope scope = sym.members().dupUnshared();
 536         List<Type> closure = types.closure(sym.asType());
 537         for (Type t : closure)
 538             addMembers(scope, t);
 539         return new FilteredMemberList(scope);
 540     }
 541     // where
 542         private void addMembers(WriteableScope scope, Type type) {
 543             members:
 544             for (Symbol e : type.asElement().members().getSymbols(NON_RECURSIVE)) {
 545                 for (Symbol overrider : scope.getSymbolsByName(e.getSimpleName())) {
 546                     if (overrider.kind == e.kind && (overrider.flags() & Flags.SYNTHETIC) == 0) {
 547                         if (overrider.getKind() == ElementKind.METHOD &&
 548                                 overrides((ExecutableElement)overrider, (ExecutableElement)e, (TypeElement)type.asElement())) {
 549                             continue members;
 550                         }
 551                     }
 552                 }
 553                 boolean derived = e.getEnclosingElement() != scope.owner;
 554                 ElementKind kind = e.getKind();
 555                 boolean initializer = kind == ElementKind.CONSTRUCTOR
 556                     || kind == ElementKind.INSTANCE_INIT
 557                     || kind == ElementKind.STATIC_INIT;
 558                 if (!derived || (!initializer && e.isInheritedIn(scope.owner, types)))
 559                     scope.enter(e);
 560             }
 561         }
 562 
 563     /**
 564      * Returns all annotations of an element, whether
 565      * inherited or directly present.
 566      *
 567      * @param e  the element being examined
 568      * @return all annotations of the element
 569      */
 570     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 571     public List<Attribute.Compound> getAllAnnotationMirrors(Element e) {
 572         Symbol sym = cast(Symbol.class, e);
 573         List<Attribute.Compound> annos = sym.getAnnotationMirrors();
 574         while (sym.getKind() == ElementKind.CLASS) {
 575             Type sup = ((ClassSymbol) sym).getSuperclass();
 576             if (!sup.hasTag(CLASS) || sup.isErroneous() ||
 577                     sup.tsym == syms.objectType.tsym) {
 578                 break;
 579             }
 580             sym = sup.tsym;
 581             List<Attribute.Compound> oldAnnos = annos;
 582             List<Attribute.Compound> newAnnos = sym.getAnnotationMirrors();
 583             for (Attribute.Compound anno : newAnnos) {
 584                 if (isInherited(anno.type) &&
 585                         !containsAnnoOfType(oldAnnos, anno.type)) {
 586                     annos = annos.prepend(anno);
 587                 }
 588             }
 589         }
 590         return annos;
 591     }
 592 
 593     /**
 594      * Tests whether an annotation type is @Inherited.
 595      */
 596     private boolean isInherited(Type annotype) {
 597         return annotype.tsym.attribute(syms.inheritedType.tsym) != null;
 598     }
 599 
 600     /**
 601      * Tests whether a list of annotations contains an annotation
 602      * of a given type.
 603      */
 604     private static boolean containsAnnoOfType(List<Attribute.Compound> annos,
 605                                               Type type) {
 606         for (Attribute.Compound anno : annos) {
 607             if (anno.type.tsym == type.tsym)
 608                 return true;
 609         }
 610         return false;
 611     }
 612 
 613     @DefinedBy(Api.LANGUAGE_MODEL)
 614     public boolean hides(Element hiderEl, Element hideeEl) {
 615         Symbol hider = cast(Symbol.class, hiderEl);
 616         Symbol hidee = cast(Symbol.class, hideeEl);
 617 
 618         // Fields only hide fields; methods only methods; types only types.
 619         // Names must match.  Nothing hides itself (just try it).
 620         if (hider == hidee ||
 621                 hider.kind != hidee.kind ||
 622                 hider.name != hidee.name) {
 623             return false;
 624         }
 625 
 626         // Only static methods can hide other methods.
 627         // Methods only hide methods with matching signatures.
 628         if (hider.kind == MTH) {
 629             if (!hider.isStatic() ||
 630                         !types.isSubSignature(hider.type, hidee.type)) {
 631                 return false;
 632             }
 633         }
 634 
 635         // Hider must be in a subclass of hidee's class.
 636         // Note that if M1 hides M2, and M2 hides M3, and M3 is accessible
 637         // in M1's class, then M1 and M2 both hide M3.
 638         ClassSymbol hiderClass = hider.owner.enclClass();
 639         ClassSymbol hideeClass = hidee.owner.enclClass();
 640         if (hiderClass == null || hideeClass == null ||
 641                 !hiderClass.isSubClass(hideeClass, types)) {
 642             return false;
 643         }
 644 
 645         // Hidee must be accessible in hider's class.
 646         return hidee.isAccessibleIn(hiderClass, types);
 647     }
 648 
 649     @DefinedBy(Api.LANGUAGE_MODEL)
 650     public boolean overrides(ExecutableElement riderEl,
 651                              ExecutableElement rideeEl, TypeElement typeEl) {
 652         MethodSymbol rider = cast(MethodSymbol.class, riderEl);
 653         MethodSymbol ridee = cast(MethodSymbol.class, rideeEl);
 654         ClassSymbol origin = cast(ClassSymbol.class, typeEl);
 655 
 656         return rider.name == ridee.name &&
 657 
 658                // not reflexive as per JLS
 659                rider != ridee &&
 660 
 661                // we don't care if ridee is static, though that wouldn't
 662                // compile
 663                !rider.isStatic() &&
 664 
 665                // Symbol.overrides assumes the following
 666                ridee.isMemberOf(origin, types) &&
 667 
 668                // check access and signatures; don't check return types
 669                rider.overrides(ridee, origin, types, false);
 670     }
 671 
 672     @DefinedBy(Api.LANGUAGE_MODEL)
 673     public String getConstantExpression(Object value) {
 674         return Constants.format(value);
 675     }
 676 
 677     /**
 678      * Print a representation of the elements to the given writer in
 679      * the specified order.  The main purpose of this method is for
 680      * diagnostics.  The exact format of the output is <em>not</em>
 681      * specified and is subject to change.
 682      *
 683      * @param w the writer to print the output to
 684      * @param elements the elements to print
 685      */
 686     @DefinedBy(Api.LANGUAGE_MODEL)
 687     public void printElements(java.io.Writer w, Element... elements) {
 688         for (Element element : elements)
 689             (new PrintingProcessor.PrintingElementVisitor(w, this)).visit(element).flush();
 690     }
 691 
 692     @DefinedBy(Api.LANGUAGE_MODEL)
 693     public Name getName(CharSequence cs) {
 694         return names.fromString(cs.toString());
 695     }
 696 
 697     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 698     public boolean isFunctionalInterface(TypeElement element) {
 699         if (element.getKind() != ElementKind.INTERFACE)
 700             return false;
 701         else {
 702             TypeSymbol tsym = cast(TypeSymbol.class, element);
 703             return types.isFunctionalInterface(tsym);
 704         }
 705     }
 706 
 707     /**
 708      * Returns the tree node and compilation unit corresponding to this
 709      * element, or null if they can't be found.
 710      */
 711     private Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(Element e) {
 712         Symbol sym = cast(Symbol.class, e);
 713         Env<AttrContext> enterEnv = getEnterEnv(sym);
 714         if (enterEnv == null)
 715             return null;
 716         JCTree tree = TreeInfo.declarationFor(sym, enterEnv.tree);
 717         if (tree == null || enterEnv.toplevel == null)
 718             return null;
 719         return new Pair<>(tree, enterEnv.toplevel);
 720     }
 721 
 722     /**
 723      * Returns the best approximation for the tree node and compilation unit
 724      * corresponding to the given element, annotation and value.
 725      * If the element is null, null is returned.
 726      * If the annotation is null or cannot be found, the tree node and
 727      * compilation unit for the element is returned.
 728      * If the annotation value is null or cannot be found, the tree node and
 729      * compilation unit for the annotation is returned.
 730      */
 731     public Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(
 732                       Element e, AnnotationMirror a, AnnotationValue v) {
 733         if (e == null)
 734             return null;
 735 
 736         Pair<JCTree, JCCompilationUnit> elemTreeTop = getTreeAndTopLevel(e);
 737         if (elemTreeTop == null)
 738             return null;
 739 
 740         if (a == null)
 741             return elemTreeTop;
 742 
 743         JCTree annoTree = matchAnnoToTree(a, e, elemTreeTop.fst);
 744         if (annoTree == null)
 745             return elemTreeTop;
 746 
 747         if (v == null)
 748             return new Pair<>(annoTree, elemTreeTop.snd);
 749 
 750         JCTree valueTree = matchAttributeToTree(
 751                 cast(Attribute.class, v), cast(Attribute.class, a), annoTree);
 752         if (valueTree == null)
 753             return new Pair<>(annoTree, elemTreeTop.snd);
 754 
 755         return new Pair<>(valueTree, elemTreeTop.snd);
 756     }
 757 
 758     /**
 759      * Returns a symbol's enter environment, or null if it has none.
 760      */
 761     private Env<AttrContext> getEnterEnv(Symbol sym) {
 762         // Get enclosing class of sym, or sym itself if it is a class
 763         // package, or module.
 764         TypeSymbol ts = null;
 765         switch (sym.kind) {
 766             case PCK:
 767                 ts = (PackageSymbol)sym;
 768                 break;
 769             case MDL:
 770                 ts = (ModuleSymbol)sym;
 771                 break;
 772             default:
 773                 ts = sym.enclClass();
 774         }
 775         return (ts != null)
 776                 ? enter.getEnv(ts)
 777                 : null;
 778     }
 779 
 780     private void ensureEntered(String methodName) {
 781         if (javacTaskImpl != null) {
 782             javacTaskImpl.ensureEntered();
 783         }
 784         if (!javaCompiler.isEnterDone()) {
 785             throw new IllegalStateException("Cannot use Elements." + methodName + " before the TaskEvent.Kind.ENTER finished event.");
 786         }
 787     }
 788 
 789     /**
 790      * Returns an object cast to the specified type.
 791      * @throws NullPointerException if the object is {@code null}
 792      * @throws IllegalArgumentException if the object is of the wrong type
 793      */
 794     private static <T> T cast(Class<T> clazz, Object o) {
 795         if (! clazz.isInstance(o))
 796             throw new IllegalArgumentException(o.toString());
 797         return clazz.cast(o);
 798     }
 799 
 800     public void newRound() {
 801         resultCache.clear();
 802     }
 803 }