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