1 /*
   2  * Copyright (c) 2009, 2021, 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.code;
  27 
  28 import javax.lang.model.element.Element;
  29 import javax.lang.model.element.ElementKind;
  30 import javax.lang.model.type.TypeKind;
  31 import javax.tools.JavaFileObject;
  32 
  33 import com.sun.tools.javac.code.Attribute.TypeCompound;
  34 import com.sun.tools.javac.code.Symbol.ClassSymbol;
  35 import com.sun.tools.javac.code.Symbol.TypeSymbol;
  36 import com.sun.tools.javac.code.Type.ArrayType;
  37 import com.sun.tools.javac.code.Type.CapturedType;
  38 import com.sun.tools.javac.code.Type.ClassType;
  39 import com.sun.tools.javac.code.Type.ErrorType;
  40 import com.sun.tools.javac.code.Type.ForAll;
  41 import com.sun.tools.javac.code.Type.MethodType;
  42 import com.sun.tools.javac.code.Type.PackageType;
  43 import com.sun.tools.javac.code.Type.TypeVar;
  44 import com.sun.tools.javac.code.Type.UndetVar;
  45 import com.sun.tools.javac.code.Type.Visitor;
  46 import com.sun.tools.javac.code.Type.WildcardType;
  47 import com.sun.tools.javac.code.TypeAnnotationPosition.TypePathEntry;
  48 import com.sun.tools.javac.code.TypeAnnotationPosition.TypePathEntryKind;
  49 import com.sun.tools.javac.code.Symbol.VarSymbol;
  50 import com.sun.tools.javac.code.Symbol.MethodSymbol;
  51 import com.sun.tools.javac.code.Type.ModuleType;
  52 import com.sun.tools.javac.code.TypeMetadata.Entry.Kind;
  53 import com.sun.tools.javac.comp.Annotate;
  54 import com.sun.tools.javac.comp.Attr;
  55 import com.sun.tools.javac.comp.AttrContext;
  56 import com.sun.tools.javac.comp.Env;
  57 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  58 import com.sun.tools.javac.tree.JCTree;
  59 import com.sun.tools.javac.tree.JCTree.JCAnnotatedType;
  60 import com.sun.tools.javac.tree.JCTree.JCAnnotation;
  61 import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
  62 import com.sun.tools.javac.tree.JCTree.JCBlock;
  63 import com.sun.tools.javac.tree.JCTree.JCClassDecl;
  64 import com.sun.tools.javac.tree.JCTree.JCExpression;
  65 import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
  66 import com.sun.tools.javac.tree.JCTree.JCLambda;
  67 import com.sun.tools.javac.tree.JCTree.JCMemberReference;
  68 import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
  69 import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
  70 import com.sun.tools.javac.tree.JCTree.JCNewArray;
  71 import com.sun.tools.javac.tree.JCTree.JCNewClass;
  72 import com.sun.tools.javac.tree.JCTree.JCTypeApply;
  73 import com.sun.tools.javac.tree.JCTree.JCTypeIntersection;
  74 import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
  75 import com.sun.tools.javac.tree.JCTree.JCTypeUnion;
  76 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
  77 import com.sun.tools.javac.tree.JCTree.Tag;
  78 import com.sun.tools.javac.tree.TreeInfo;
  79 import com.sun.tools.javac.tree.TreeScanner;
  80 import com.sun.tools.javac.util.Assert;
  81 import com.sun.tools.javac.util.Context;
  82 import com.sun.tools.javac.util.List;
  83 import com.sun.tools.javac.util.ListBuffer;
  84 import com.sun.tools.javac.util.Log;
  85 import com.sun.tools.javac.util.Names;
  86 
  87 import static com.sun.tools.javac.code.Kinds.Kind.*;
  88 
  89 /**
  90  * Contains operations specific to processing type annotations.
  91  * This class has two functions:
  92  * separate declaration from type annotations and insert the type
  93  * annotations to their types;
  94  * and determine the TypeAnnotationPositions for all type annotations.
  95  */
  96 public class TypeAnnotations {
  97     protected static final Context.Key<TypeAnnotations> typeAnnosKey = new Context.Key<>();
  98 
  99     public static TypeAnnotations instance(Context context) {
 100         TypeAnnotations instance = context.get(typeAnnosKey);
 101         if (instance == null)
 102             instance = new TypeAnnotations(context);
 103         return instance;
 104     }
 105 
 106     final Log log;
 107     final Names names;
 108     final Symtab syms;
 109     final Annotate annotate;
 110     final Attr attr;
 111 
 112     protected TypeAnnotations(Context context) {
 113         context.put(typeAnnosKey, this);
 114         names = Names.instance(context);
 115         log = Log.instance(context);
 116         syms = Symtab.instance(context);
 117         annotate = Annotate.instance(context);
 118         attr = Attr.instance(context);
 119     }
 120 
 121     /**
 122      * Separate type annotations from declaration annotations and
 123      * determine the correct positions for type annotations.
 124      * This version only visits types in signatures and should be
 125      * called from MemberEnter.
 126      */
 127     public void organizeTypeAnnotationsSignatures(final Env<AttrContext> env, final JCClassDecl tree) {
 128         annotate.afterTypes(() -> {
 129             JavaFileObject oldSource = log.useSource(env.toplevel.sourcefile);
 130             try {
 131                 new TypeAnnotationPositions(true).scan(tree);
 132             } finally {
 133                 log.useSource(oldSource);
 134             }
 135         });
 136     }
 137 
 138     public void validateTypeAnnotationsSignatures(final Env<AttrContext> env, final JCClassDecl tree) {
 139         annotate.validate(() -> { //validate annotations
 140             JavaFileObject oldSource = log.useSource(env.toplevel.sourcefile);
 141             try {
 142                 attr.validateTypeAnnotations(tree, true);
 143             } finally {
 144                 log.useSource(oldSource);
 145             }
 146         });
 147     }
 148 
 149     /**
 150      * This version only visits types in bodies, that is, field initializers,
 151      * top-level blocks, and method bodies, and should be called from Attr.
 152      */
 153     public void organizeTypeAnnotationsBodies(JCClassDecl tree) {
 154         new TypeAnnotationPositions(false).scan(tree);
 155     }
 156 
 157     public enum AnnotationType { DECLARATION, TYPE, NONE, BOTH }
 158 
 159     public List<Attribute> annotationTargets(TypeSymbol tsym) {
 160         Attribute.Compound atTarget = tsym.getAnnotationTypeMetadata().getTarget();
 161         if (atTarget == null) {
 162             return null;
 163         }
 164 
 165         Attribute atValue = atTarget.member(names.value);
 166         if (!(atValue instanceof Attribute.Array arrayVal)) {
 167             return null;
 168         }
 169 
 170         List<Attribute> targets = arrayVal.getValue();
 171         if (targets.stream().anyMatch(a -> !(a instanceof Attribute.Enum))) {
 172             return null;
 173         }
 174 
 175         return targets;
 176     }
 177 
 178     /**
 179      * Determine whether an annotation is a declaration annotation,
 180      * a type annotation, or both (or none, i.e a non-annotation masquerading as one).
 181      */
 182     public AnnotationType annotationTargetType(Attribute.Compound a, Symbol s) {
 183         if (!a.type.tsym.isAnnotationType()) {
 184             return AnnotationType.NONE;
 185         }
 186         List<Attribute> targets = annotationTargets(a.type.tsym);
 187         return (targets == null) ?
 188                 AnnotationType.DECLARATION :
 189                 targets.stream()
 190                         .map(attr -> targetToAnnotationType(attr, s))
 191                         .reduce(AnnotationType.NONE, this::combineAnnotationType);
 192     }
 193 
 194     private AnnotationType combineAnnotationType(AnnotationType at1, AnnotationType at2) {
 195         if (at1 == AnnotationType.NONE) {
 196             return at2;
 197         } else if (at2 == AnnotationType.NONE) {
 198             return at1;
 199         } else if (at1 != at2) {
 200             return AnnotationType.BOTH;
 201         } else {
 202             return at1;
 203         }
 204     }
 205 
 206     private AnnotationType targetToAnnotationType(Attribute a, Symbol s) {
 207         Attribute.Enum e = (Attribute.Enum)a;
 208         if (e.value.name == names.TYPE) {
 209             if (s.kind == TYP)
 210                 return AnnotationType.DECLARATION;
 211         } else if (e.value.name == names.FIELD || e.value.name == names.RECORD_COMPONENT) {
 212             if (s.kind == VAR &&
 213                     s.owner.kind != MTH)
 214                 return AnnotationType.DECLARATION;
 215         } else if (e.value.name == names.METHOD) {
 216             if (s.kind == MTH &&
 217                     !s.isConstructor())
 218                 return AnnotationType.DECLARATION;
 219         } else if (e.value.name == names.PARAMETER) {
 220             if (s.kind == VAR &&
 221                     s.owner.kind == MTH &&
 222                     (s.flags() & Flags.PARAMETER) != 0)
 223                 return AnnotationType.DECLARATION;
 224         } else if (e.value.name == names.CONSTRUCTOR) {
 225             if (s.kind == MTH &&
 226                     s.isConstructor())
 227                 return AnnotationType.DECLARATION;
 228         } else if (e.value.name == names.LOCAL_VARIABLE) {
 229             if (s.kind == VAR &&
 230                     s.owner.kind == MTH &&
 231                     (s.flags() & Flags.PARAMETER) == 0)
 232                 return AnnotationType.DECLARATION;
 233         } else if (e.value.name == names.ANNOTATION_TYPE) {
 234             if (s.kind == TYP &&
 235                     (s.flags() & Flags.ANNOTATION) != 0)
 236                 return AnnotationType.DECLARATION;
 237         } else if (e.value.name == names.PACKAGE) {
 238             if (s.kind == PCK)
 239                 return AnnotationType.DECLARATION;
 240         } else if (e.value.name == names.TYPE_USE) {
 241             if (s.kind == TYP ||
 242                     s.kind == VAR ||
 243                     (s.kind == MTH && !s.isConstructor() &&
 244                     !s.type.getReturnType().hasTag(TypeTag.VOID)) ||
 245                     (s.kind == MTH && s.isConstructor()))
 246                 return AnnotationType.TYPE;
 247         } else if (e.value.name == names.TYPE_PARAMETER) {
 248             /* Irrelevant in this case */
 249             // TYPE_PARAMETER doesn't aid in distinguishing between
 250             // Type annotations and declaration annotations on an
 251             // Element
 252         } else if (e.value.name == names.MODULE) {
 253             if (s.kind == MDL)
 254                 return AnnotationType.DECLARATION;
 255         } else {
 256             Assert.error("annotationTargetType(): unrecognized Attribute name " + e.value.name +
 257                     " (" + e.value.name.getClass() + ")");
 258             return AnnotationType.DECLARATION;
 259         }
 260         return AnnotationType.NONE;
 261     }
 262 
 263     private class TypeAnnotationPositions extends TreeScanner {
 264 
 265         private final boolean sigOnly;
 266 
 267         TypeAnnotationPositions(boolean sigOnly) {
 268             this.sigOnly = sigOnly;
 269         }
 270 
 271         /*
 272          * When traversing the AST we keep the "frames" of visited
 273          * trees in order to determine the position of annotations.
 274          */
 275         private List<JCTree> frames = List.nil();
 276 
 277         protected void push(JCTree t) {
 278             frames = frames.prepend(t);
 279         }
 280         protected JCTree pop() {
 281             JCTree t = frames.head;
 282             frames = frames.tail;
 283             return t;
 284             }
 285         // could this be frames.elems.tail.head?
 286         private JCTree peek2() {
 287             return frames.tail.head;
 288         }
 289 
 290         @Override
 291         public void scan(JCTree tree) {
 292             push(tree);
 293             try {
 294                 super.scan(tree);
 295             } finally {
 296                 pop();
 297             }
 298         }
 299 
 300         /**
 301          * Separates type annotations from declaration annotations.
 302          * This step is needed because in certain locations (where declaration
 303          * and type annotations can be mixed, e.g. the type of a field)
 304          * we never build an JCAnnotatedType. This step finds these
 305          * annotations and marks them as if they were part of the type.
 306          */
 307         private void separateAnnotationsKinds(JCTree typetree, Type type,
 308                                               Symbol sym, TypeAnnotationPosition pos)
 309         {
 310             List<Attribute.Compound> allAnnotations = sym.getRawAttributes();
 311             ListBuffer<Attribute.Compound> declAnnos = new ListBuffer<>();
 312             ListBuffer<Attribute.TypeCompound> typeAnnos = new ListBuffer<>();
 313             ListBuffer<Attribute.TypeCompound> onlyTypeAnnos = new ListBuffer<>();
 314 
 315             for (Attribute.Compound a : allAnnotations) {
 316                 switch (annotationTargetType(a, sym)) {
 317                     case DECLARATION:
 318                         declAnnos.append(a);
 319                         break;
 320                     case BOTH: {
 321                         declAnnos.append(a);
 322                         Attribute.TypeCompound ta = toTypeCompound(a, pos);
 323                         typeAnnos.append(ta);
 324                         break;
 325                     }
 326                     case TYPE: {
 327                         Attribute.TypeCompound ta = toTypeCompound(a, pos);
 328                         typeAnnos.append(ta);
 329                         // Also keep track which annotations are only type annotations
 330                         onlyTypeAnnos.append(ta);
 331                         break;
 332                     }
 333                     case NONE: // Error signaled already, just drop the non-annotation.
 334                         break;
 335                 }
 336             }
 337 
 338             // If we have no type annotations we are done for this Symbol
 339             if (typeAnnos.isEmpty()) {
 340                 return;
 341             }
 342 
 343             // Reset decl annotations to the set {all - type only}
 344             sym.resetAnnotations();
 345             sym.setDeclarationAttributes(declAnnos.toList());
 346 
 347             List<Attribute.TypeCompound> typeAnnotations = typeAnnos.toList();
 348 
 349             if (type == null) {
 350                 // When type is null, put the type annotations to the symbol.
 351                 // This is used for constructor return annotations, for which
 352                 // we use the type of the enclosing class.
 353                 type = sym.getEnclosingElement().asType();
 354 
 355                 // Declaration annotations are always allowed on constructor returns.
 356                 // Therefore, use typeAnnotations instead of onlyTypeAnnos.
 357                 typeWithAnnotations(typetree, type, typeAnnotations, typeAnnotations, pos);
 358                 // Note that we don't use the result, the call to
 359                 // typeWithAnnotations side-effects the type annotation positions.
 360                 // This is important for constructors of nested classes.
 361                 sym.appendUniqueTypeAttributes(typeAnnotations);
 362                 return;
 363             }
 364 
 365             // type is non-null, add type annotations from declaration context to the type
 366             type = typeWithAnnotations(typetree, type, typeAnnotations, onlyTypeAnnos.toList(), pos);
 367 
 368             if (sym.getKind() == ElementKind.METHOD) {
 369                 sym.type.asMethodType().restype = type;
 370             } else if (sym.getKind() == ElementKind.PARAMETER && currentLambda == null) {
 371                 sym.type = type;
 372                 if (sym.getQualifiedName().equals(names._this)) {
 373                     sym.owner.type.asMethodType().recvtype = type;
 374                     // note that the typeAnnotations will also be added to the owner below.
 375                 } else {
 376                     MethodType methType = sym.owner.type.asMethodType();
 377                     List<VarSymbol> params = ((MethodSymbol)sym.owner).params;
 378                     List<Type> oldArgs = methType.argtypes;
 379                     ListBuffer<Type> newArgs = new ListBuffer<>();
 380                     while (params.nonEmpty()) {
 381                         if (params.head == sym) {
 382                             newArgs.add(type);
 383                         } else {
 384                             newArgs.add(oldArgs.head);
 385                         }
 386                         oldArgs = oldArgs.tail;
 387                         params = params.tail;
 388                     }
 389                     methType.argtypes = newArgs.toList();
 390                 }
 391             } else {
 392                 sym.type = type;
 393             }
 394 
 395             sym.appendUniqueTypeAttributes(typeAnnotations);
 396 
 397             if (sym.getKind() == ElementKind.PARAMETER ||
 398                 sym.getKind() == ElementKind.LOCAL_VARIABLE ||
 399                 sym.getKind() == ElementKind.RESOURCE_VARIABLE ||
 400                 sym.getKind() == ElementKind.EXCEPTION_PARAMETER ||
 401                 sym.getKind() == ElementKind.BINDING_VARIABLE) {
 402                 appendTypeAnnotationsToOwner(sym, typeAnnotations);
 403             }
 404         }
 405 
 406         private void appendTypeAnnotationsToOwner(Symbol sym, List<Attribute.TypeCompound> typeAnnotations) {
 407             // Make sure all type annotations from the symbol are also
 408             // on the owner. If the owner is an initializer block, propagate
 409             // to the type.
 410             final long ownerFlags = sym.owner.flags();
 411             if ((ownerFlags & Flags.BLOCK) != 0) {
 412                 // Store init and clinit type annotations with the ClassSymbol
 413                 // to allow output in Gen.normalizeDefs.
 414                 ClassSymbol cs = (ClassSymbol) sym.owner.owner;
 415                 if ((ownerFlags & Flags.STATIC) != 0) {
 416                     cs.appendClassInitTypeAttributes(typeAnnotations);
 417                 } else {
 418                     cs.appendInitTypeAttributes(typeAnnotations);
 419                 }
 420             } else {
 421                 sym.owner.appendUniqueTypeAttributes(typeAnnotations);
 422             }
 423         }
 424 
 425         // This method has a similar purpose as
 426         // {@link com.sun.tools.javac.parser.JavacParser.insertAnnotationsToMostInner(JCExpression, List<JCTypeAnnotation>, boolean)}
 427         // We found a type annotation in a declaration annotation position,
 428         // for example, on the return type.
 429         // Such an annotation is _not_ part of an JCAnnotatedType tree and we therefore
 430         // need to set its position explicitly.
 431         // The method returns a copy of type that contains these annotations.
 432         //
 433         // As a side effect the method sets the type annotation position of "annotations".
 434         // Note that it is assumed that all annotations share the same position.
 435         private Type typeWithAnnotations(final JCTree typetree, final Type type,
 436                 final List<Attribute.TypeCompound> annotations,
 437                 final List<Attribute.TypeCompound> onlyTypeAnnotations,
 438                 final TypeAnnotationPosition pos)
 439         {
 440             if (annotations.isEmpty()) {
 441                 return type;
 442             }
 443             // All annotations share the same position
 444             for (TypeCompound tc : annotations) {
 445                 Assert.check(tc.position == pos);
 446             }
 447 
 448             if (type.hasTag(TypeTag.ARRAY))
 449                 return rewriteArrayType((ArrayType)type, annotations, pos);
 450 
 451             if (type.hasTag(TypeTag.TYPEVAR)) {
 452                 return type.annotatedType(onlyTypeAnnotations);
 453             } else if (type.getKind() == TypeKind.UNION) {
 454                 // There is a TypeKind, but no TypeTag.
 455                 JCTypeUnion tutree = (JCTypeUnion)typetree;
 456                 JCExpression fst = tutree.alternatives.get(0);
 457                 Type res = typeWithAnnotations(fst, fst.type, annotations, onlyTypeAnnotations, pos);
 458                 fst.type = res;
 459                 // TODO: do we want to set res as first element in uct.alternatives?
 460                 // UnionClassType uct = (com.sun.tools.javac.code.Type.UnionClassType)type;
 461                 // Return the un-annotated union-type.
 462                 return type;
 463             } else {
 464                 Type enclTy = type;
 465                 Element enclEl = type.asElement();
 466                 JCTree enclTr = typetree;
 467 
 468                 while (enclEl != null &&
 469                         enclEl.getKind() != ElementKind.PACKAGE &&
 470                         enclTy != null &&
 471                         enclTy.getKind() != TypeKind.NONE &&
 472                         enclTy.getKind() != TypeKind.ERROR &&
 473                         (enclTr.getKind() == JCTree.Kind.MEMBER_SELECT ||
 474                                 enclTr.getKind() == JCTree.Kind.PARAMETERIZED_TYPE ||
 475                                 enclTr.getKind() == JCTree.Kind.ANNOTATED_TYPE)) {
 476                     // Iterate also over the type tree, not just the type: the type is already
 477                     // completely resolved and we cannot distinguish where the annotation
 478                     // belongs for a nested type.
 479                     if (enclTr.getKind() == JCTree.Kind.MEMBER_SELECT) {
 480                         // only change encl in this case.
 481                         enclTy = enclTy.getEnclosingType();
 482                         enclEl = enclEl.getEnclosingElement();
 483                         enclTr = ((JCFieldAccess)enclTr).getExpression();
 484                     } else if (enclTr.getKind() == JCTree.Kind.PARAMETERIZED_TYPE) {
 485                         enclTr = ((JCTypeApply)enclTr).getType();
 486                     } else {
 487                         // only other option because of while condition
 488                         enclTr = ((JCAnnotatedType)enclTr).getUnderlyingType();
 489                     }
 490                 }
 491 
 492                 /** We are trying to annotate some enclosing type,
 493                  * but nothing more exists.
 494                  */
 495                 if (enclTy != null &&
 496                         enclTy.hasTag(TypeTag.NONE)) {
 497                     switch (onlyTypeAnnotations.size()) {
 498                         case 0:
 499                             // Don't issue an error if all type annotations are
 500                             // also declaration annotations.
 501                             // If the annotations are also declaration annotations, they are
 502                             // illegal as type annotations but might be legal as declaration annotations.
 503                             // The normal declaration annotation checks make sure that the use is valid.
 504                             break;
 505                         case 1:
 506                             log.error(typetree.pos(),
 507                                       Errors.CantTypeAnnotateScoping1(onlyTypeAnnotations.head));
 508                             break;
 509                         default:
 510                             log.error(typetree.pos(),
 511                                       Errors.CantTypeAnnotateScoping(onlyTypeAnnotations));
 512                     }
 513                     return type;
 514                 }
 515 
 516                 // At this point we have visited the part of the nested
 517                 // type that is written in the source code.
 518                 // Now count from here to the actual top-level class to determine
 519                 // the correct nesting.
 520 
 521                 // The genericLocation for the annotation.
 522                 ListBuffer<TypePathEntry> depth = new ListBuffer<>();
 523 
 524                 Type topTy = enclTy;
 525                 while (enclEl != null &&
 526                         enclEl.getKind() != ElementKind.PACKAGE &&
 527                         topTy != null &&
 528                         topTy.getKind() != TypeKind.NONE &&
 529                         topTy.getKind() != TypeKind.ERROR) {
 530                     topTy = topTy.getEnclosingType();
 531                     enclEl = enclEl.getEnclosingElement();
 532 
 533                     if (topTy != null && topTy.getKind() != TypeKind.NONE) {
 534                         // Only count enclosing types.
 535                         depth = depth.append(TypePathEntry.INNER_TYPE);
 536                     }
 537                 }
 538 
 539                 if (depth.nonEmpty()) {
 540                     // Only need to change the annotation positions
 541                     // if they are on an enclosed type.
 542                     pos.location = pos.location.appendList(depth.toList());
 543                 }
 544 
 545                 Type ret = typeWithAnnotations(type, enclTy, annotations);
 546                 typetree.type = ret;
 547                 return ret;
 548             }
 549         }
 550 
 551         /**
 552          * Create a copy of the {@code Type type} with the help of the Tree for a type
 553          * {@code JCTree typetree} inserting all type annotations in {@code annotations} to the
 554          * innermost array component type.
 555          *
 556          * SIDE EFFECT: Update position for the annotations to be {@code pos}.
 557          */
 558         private Type rewriteArrayType(ArrayType type, List<TypeCompound> annotations, TypeAnnotationPosition pos) {
 559             ArrayType tomodify = new ArrayType(type);
 560             if (type.isVarargs()) {
 561                 tomodify = tomodify.makeVarargs();
 562             }
 563             ArrayType res = tomodify;
 564 
 565             List<TypePathEntry> loc = List.nil();
 566 
 567             // peel one and update loc
 568             Type tmpType = type.elemtype;
 569             loc = loc.prepend(TypePathEntry.ARRAY);
 570 
 571             while (tmpType.hasTag(TypeTag.ARRAY)) {
 572                 ArrayType arr = (ArrayType)tmpType;
 573 
 574                 // Update last type with new element type
 575                 ArrayType tmp = new ArrayType(arr);
 576                 tomodify.elemtype = tmp;
 577                 tomodify = tmp;
 578 
 579                 tmpType = arr.elemtype;
 580                 loc = loc.prepend(TypePathEntry.ARRAY);
 581             }
 582 
 583             // Fix innermost element type
 584             Type elemType;
 585             if (tmpType.getMetadata() != null) {
 586                 List<TypeCompound> tcs;
 587                 if (tmpType.getAnnotationMirrors().isEmpty()) {
 588                     tcs = annotations;
 589                 } else {
 590                     // Special case, lets prepend
 591                     tcs =  annotations.appendList(tmpType.getAnnotationMirrors());
 592                 }
 593                 elemType = tmpType.cloneWithMetadata(tmpType
 594                         .getMetadata()
 595                         .without(Kind.ANNOTATIONS)
 596                         .combine(new TypeMetadata.Annotations(tcs)));
 597             } else {
 598                 elemType = tmpType.cloneWithMetadata(new TypeMetadata(new TypeMetadata.Annotations(annotations)));
 599             }
 600             tomodify.elemtype = elemType;
 601 
 602             // Update positions
 603             pos.location = loc;
 604 
 605             return res;
 606         }
 607 
 608         /** Return a copy of the first type that only differs by
 609          * inserting the annotations to the left-most/inner-most type
 610          * or the type given by stopAt.
 611          *
 612          * We need the stopAt parameter to know where on a type to
 613          * put the annotations.
 614          * If we have nested classes Outer > Middle > Inner, and we
 615          * have the source type "@A Middle.Inner", we will invoke
 616          * this method with type = Outer.Middle.Inner,
 617          * stopAt = Middle.Inner, and annotations = @A.
 618          *
 619          * @param type The type to copy.
 620          * @param stopAt The type to stop at.
 621          * @param annotations The annotations to insert.
 622          * @return A copy of type that contains the annotations.
 623          */
 624         private Type typeWithAnnotations(final Type type,
 625                 final Type stopAt,
 626                 final List<Attribute.TypeCompound> annotations) {
 627             Visitor<Type, List<TypeCompound>> visitor =
 628                     new Type.Visitor<Type, List<Attribute.TypeCompound>>() {
 629                 @Override
 630                 public Type visitClassType(ClassType t, List<TypeCompound> s) {
 631                     // assert that t.constValue() == null?
 632                     if (t == stopAt ||
 633                         t.getEnclosingType() == Type.noType) {
 634                         return t.annotatedType(s);
 635                     } else {
 636                         ClassType ret = new ClassType(t.getEnclosingType().accept(this, s),
 637                                                       t.typarams_field, t.tsym,
 638                                                       t.getMetadata());
 639                         ret.all_interfaces_field = t.all_interfaces_field;
 640                         ret.allparams_field = t.allparams_field;
 641                         ret.interfaces_field = t.interfaces_field;
 642                         ret.rank_field = t.rank_field;
 643                         ret.supertype_field = t.supertype_field;
 644                         return ret;
 645                     }
 646                 }
 647 
 648                 @Override
 649                 public Type visitWildcardType(WildcardType t, List<TypeCompound> s) {
 650                     return t.annotatedType(s);
 651                 }
 652 
 653                 @Override
 654                 public Type visitArrayType(ArrayType t, List<TypeCompound> s) {
 655                     ArrayType ret = new ArrayType(t.elemtype.accept(this, s), t.tsym,
 656                                                   t.getMetadata());
 657                     return ret;
 658                 }
 659 
 660                 @Override
 661                 public Type visitMethodType(MethodType t, List<TypeCompound> s) {
 662                     // Impossible?
 663                     return t;
 664                 }
 665 
 666                 @Override
 667                 public Type visitPackageType(PackageType t, List<TypeCompound> s) {
 668                     // Impossible?
 669                     return t;
 670                 }
 671 
 672                 @Override
 673                 public Type visitTypeVar(TypeVar t, List<TypeCompound> s) {
 674                     return t.annotatedType(s);
 675                 }
 676 
 677                 @Override
 678                 public Type visitModuleType(ModuleType t, List<TypeCompound> s) {
 679                     return t.annotatedType(s);
 680                 }
 681 
 682                 @Override
 683                 public Type visitCapturedType(CapturedType t, List<TypeCompound> s) {
 684                     return t.annotatedType(s);
 685                 }
 686 
 687                 @Override
 688                 public Type visitForAll(ForAll t, List<TypeCompound> s) {
 689                     // Impossible?
 690                     return t;
 691                 }
 692 
 693                 @Override
 694                 public Type visitUndetVar(UndetVar t, List<TypeCompound> s) {
 695                     // Impossible?
 696                     return t;
 697                 }
 698 
 699                 @Override
 700                 public Type visitErrorType(ErrorType t, List<TypeCompound> s) {
 701                     return t.annotatedType(s);
 702                 }
 703 
 704                 @Override
 705                 public Type visitType(Type t, List<TypeCompound> s) {
 706                     return t.annotatedType(s);
 707                 }
 708             };
 709 
 710             return type.accept(visitor, annotations);
 711         }
 712 
 713         private Attribute.TypeCompound toTypeCompound(Attribute.Compound a, TypeAnnotationPosition p) {
 714             // It is safe to alias the position.
 715             return new Attribute.TypeCompound(a, p);
 716         }
 717 
 718 
 719         /* This is the beginning of the second part of organizing
 720          * type annotations: determine the type annotation positions.
 721          */
 722         private TypeAnnotationPosition
 723             resolveFrame(JCTree tree,
 724                          JCTree frame,
 725                          List<JCTree> path,
 726                          JCLambda currentLambda,
 727                          int outer_type_index,
 728                          ListBuffer<TypePathEntry> location)
 729         {
 730 
 731             // Note that p.offset is set in
 732             // com.sun.tools.javac.jvm.Gen.setTypeAnnotationPositions(int)
 733 
 734             switch (frame.getKind()) {
 735                 case TYPE_CAST:
 736                     return TypeAnnotationPosition.typeCast(location.toList(),
 737                                                            currentLambda,
 738                                                            outer_type_index,
 739                                                            frame.pos);
 740 
 741                 case INSTANCE_OF:
 742                     return TypeAnnotationPosition.instanceOf(location.toList(),
 743                                                              currentLambda,
 744                                                              frame.pos);
 745 
 746                 case NEW_CLASS:
 747                     final JCNewClass frameNewClass = (JCNewClass) frame;
 748                     if (frameNewClass.def != null) {
 749                         // Special handling for anonymous class instantiations
 750                         final JCClassDecl frameClassDecl = frameNewClass.def;
 751                         if (frameClassDecl.implementing.contains(tree)) {
 752                             final int type_index =
 753                                 frameClassDecl.implementing.indexOf(tree);
 754                             return TypeAnnotationPosition
 755                                 .classExtends(location.toList(), currentLambda,
 756                                               type_index, frame.pos);
 757                         } else {
 758                             //for encl.new @TA Clazz(), tree may be different from frameClassDecl.extending
 759                             return TypeAnnotationPosition
 760                                 .classExtends(location.toList(), currentLambda,
 761                                               frame.pos);
 762                         }
 763                     } else if (frameNewClass.typeargs.contains(tree)) {
 764                         final int type_index =
 765                             frameNewClass.typeargs.indexOf(tree);
 766                         return TypeAnnotationPosition
 767                             .constructorInvocationTypeArg(location.toList(),
 768                                                           currentLambda,
 769                                                           type_index,
 770                                                           frame.pos);
 771                     } else {
 772                         return TypeAnnotationPosition
 773                             .newObj(location.toList(), currentLambda,
 774                                     frame.pos);
 775                     }
 776 
 777                 case NEW_ARRAY:
 778                     return TypeAnnotationPosition
 779                         .newObj(location.toList(), currentLambda, frame.pos);
 780 
 781                 case ANNOTATION_TYPE:
 782                 case CLASS:
 783                 case ENUM:
 784                 case INTERFACE:
 785                 case RECORD:
 786                     if (((JCClassDecl)frame).extending == tree) {
 787                         return TypeAnnotationPosition
 788                             .classExtends(location.toList(), currentLambda,
 789                                           frame.pos);
 790                     } else if (((JCClassDecl)frame).implementing.contains(tree)) {
 791                         final int type_index =
 792                             ((JCClassDecl)frame).implementing.indexOf(tree);
 793                         return TypeAnnotationPosition
 794                             .classExtends(location.toList(), currentLambda,
 795                                           type_index, frame.pos);
 796                     } else if (((JCClassDecl)frame).typarams.contains(tree)) {
 797                         final int parameter_index =
 798                             ((JCClassDecl)frame).typarams.indexOf(tree);
 799                         return TypeAnnotationPosition
 800                             .typeParameter(location.toList(), currentLambda,
 801                                            parameter_index, frame.pos);
 802                     } else {
 803                         throw new AssertionError("Could not determine position of tree " +
 804                                                  tree + " within frame " + frame);
 805                     }
 806 
 807                 case METHOD: {
 808                     final JCMethodDecl frameMethod = (JCMethodDecl) frame;
 809                     if (frameMethod.thrown.contains(tree)) {
 810                         final int type_index = frameMethod.thrown.indexOf(tree);
 811                         return TypeAnnotationPosition
 812                             .methodThrows(location.toList(), currentLambda,
 813                                           type_index, frame.pos);
 814                     } else if (frameMethod.restype == tree) {
 815                         return TypeAnnotationPosition
 816                             .methodReturn(location.toList(), currentLambda,
 817                                           frame.pos);
 818                     } else if (frameMethod.typarams.contains(tree)) {
 819                         final int parameter_index =
 820                             frameMethod.typarams.indexOf(tree);
 821                         return TypeAnnotationPosition
 822                             .methodTypeParameter(location.toList(),
 823                                                  currentLambda,
 824                                                  parameter_index, frame.pos);
 825                     } else {
 826                         throw new AssertionError("Could not determine position of tree " + tree +
 827                                                  " within frame " + frame);
 828                     }
 829                 }
 830 
 831                 case PARAMETERIZED_TYPE: {
 832                     List<JCTree> newPath = path.tail;
 833 
 834                     if (((JCTypeApply)frame).clazz == tree) {
 835                         // generic: RAW; noop
 836                     } else if (((JCTypeApply)frame).arguments.contains(tree)) {
 837                         JCTypeApply taframe = (JCTypeApply) frame;
 838                         int arg = taframe.arguments.indexOf(tree);
 839                         location = location.prepend(
 840                             new TypePathEntry(TypePathEntryKind.TYPE_ARGUMENT,
 841                                               arg));
 842 
 843                         Type typeToUse;
 844                         if (newPath.tail != null &&
 845                             newPath.tail.head.hasTag(Tag.NEWCLASS)) {
 846                             // If we are within an anonymous class
 847                             // instantiation, use its type, because it
 848                             // contains a correctly nested type.
 849                             typeToUse = newPath.tail.head.type;
 850                         } else {
 851                             typeToUse = taframe.type;
 852                         }
 853 
 854                         location = locateNestedTypes(typeToUse, location);
 855                     } else {
 856                         throw new AssertionError("Could not determine type argument position of tree " + tree +
 857                                                  " within frame " + frame);
 858                     }
 859 
 860                     return resolveFrame(newPath.head, newPath.tail.head,
 861                                         newPath, currentLambda,
 862                                         outer_type_index, location);
 863                 }
 864 
 865                 case MEMBER_REFERENCE: {
 866                     JCMemberReference mrframe = (JCMemberReference) frame;
 867 
 868                     if (mrframe.expr == tree) {
 869                         switch (mrframe.mode) {
 870                         case INVOKE:
 871                             return TypeAnnotationPosition
 872                                 .methodRef(location.toList(), currentLambda,
 873                                            frame.pos);
 874                         case NEW:
 875                             return TypeAnnotationPosition
 876                                 .constructorRef(location.toList(),
 877                                                 currentLambda,
 878                                                 frame.pos);
 879                         default:
 880                             throw new AssertionError("Unknown method reference mode " + mrframe.mode +
 881                                                      " for tree " + tree + " within frame " + frame);
 882                         }
 883                     } else if (mrframe.typeargs != null &&
 884                             mrframe.typeargs.contains(tree)) {
 885                         final int type_index = mrframe.typeargs.indexOf(tree);
 886                         switch (mrframe.mode) {
 887                         case INVOKE:
 888                             return TypeAnnotationPosition
 889                                 .methodRefTypeArg(location.toList(),
 890                                                   currentLambda,
 891                                                   type_index, frame.pos);
 892                         case NEW:
 893                             return TypeAnnotationPosition
 894                                 .constructorRefTypeArg(location.toList(),
 895                                                        currentLambda,
 896                                                        type_index, frame.pos);
 897                         default:
 898                             throw new AssertionError("Unknown method reference mode " + mrframe.mode +
 899                                                    " for tree " + tree + " within frame " + frame);
 900                         }
 901                     } else {
 902                         throw new AssertionError("Could not determine type argument position of tree " + tree +
 903                                                " within frame " + frame);
 904                     }
 905                 }
 906 
 907                 case ARRAY_TYPE: {
 908                     location = location.prepend(TypePathEntry.ARRAY);
 909                     List<JCTree> newPath = path.tail;
 910                     while (true) {
 911                         JCTree npHead = newPath.tail.head;
 912                         if (npHead.hasTag(JCTree.Tag.TYPEARRAY)) {
 913                             newPath = newPath.tail;
 914                             location = location.prepend(TypePathEntry.ARRAY);
 915                         } else if (npHead.hasTag(JCTree.Tag.ANNOTATED_TYPE)) {
 916                             newPath = newPath.tail;
 917                         } else {
 918                             break;
 919                         }
 920                     }
 921                     return resolveFrame(newPath.head, newPath.tail.head,
 922                                         newPath, currentLambda,
 923                                         outer_type_index, location);
 924                 }
 925 
 926                 case TYPE_PARAMETER:
 927                     if (path.tail.tail.head.hasTag(JCTree.Tag.CLASSDEF)) {
 928                         final JCClassDecl clazz =
 929                             (JCClassDecl)path.tail.tail.head;
 930                         final int parameter_index =
 931                             clazz.typarams.indexOf(path.tail.head);
 932                         final int bound_index =
 933                             ((JCTypeParameter)frame).bounds.get(0)
 934                             .type.isInterface() ?
 935                             ((JCTypeParameter)frame).bounds.indexOf(tree) + 1:
 936                             ((JCTypeParameter)frame).bounds.indexOf(tree);
 937                         return TypeAnnotationPosition
 938                             .typeParameterBound(location.toList(),
 939                                                 currentLambda,
 940                                                 parameter_index, bound_index,
 941                                                 frame.pos);
 942                     } else if (path.tail.tail.head.hasTag(JCTree.Tag.METHODDEF)) {
 943                         final JCMethodDecl method =
 944                             (JCMethodDecl)path.tail.tail.head;
 945                         final int parameter_index =
 946                             method.typarams.indexOf(path.tail.head);
 947                         final int bound_index =
 948                             ((JCTypeParameter)frame).bounds.get(0)
 949                             .type.isInterface() ?
 950                             ((JCTypeParameter)frame).bounds.indexOf(tree) + 1:
 951                             ((JCTypeParameter)frame).bounds.indexOf(tree);
 952                         return TypeAnnotationPosition
 953                             .methodTypeParameterBound(location.toList(),
 954                                                       currentLambda,
 955                                                       parameter_index,
 956                                                       bound_index,
 957                                                       frame.pos);
 958                     } else {
 959                         throw new AssertionError("Could not determine position of tree " + tree +
 960                                                  " within frame " + frame);
 961                     }
 962 
 963                 case VARIABLE:
 964                     VarSymbol v = ((JCVariableDecl) frame).sym;
 965                     if (v.getKind() != ElementKind.FIELD) {
 966                         appendTypeAnnotationsToOwner(v, v.getRawTypeAttributes());
 967                     }
 968                     switch (v.getKind()) {
 969                         case BINDING_VARIABLE:
 970                         case LOCAL_VARIABLE:
 971                             return TypeAnnotationPosition
 972                                 .localVariable(location.toList(), currentLambda,
 973                                                frame.pos);
 974                         case FIELD:
 975                             return TypeAnnotationPosition.field(location.toList(),
 976                                                                 currentLambda,
 977                                                                 frame.pos);
 978                         case PARAMETER:
 979                             if (v.getQualifiedName().equals(names._this)) {
 980                                 return TypeAnnotationPosition
 981                                     .methodReceiver(location.toList(),
 982                                                     currentLambda,
 983                                                     frame.pos);
 984                             } else {
 985                                 final int parameter_index =
 986                                     methodParamIndex(path, frame);
 987                                 return TypeAnnotationPosition
 988                                     .methodParameter(location.toList(),
 989                                                      currentLambda,
 990                                                      parameter_index,
 991                                                      frame.pos);
 992                             }
 993                         case EXCEPTION_PARAMETER:
 994                             return TypeAnnotationPosition
 995                                 .exceptionParameter(location.toList(),
 996                                                     currentLambda,
 997                                                     frame.pos);
 998                         case RESOURCE_VARIABLE:
 999                             return TypeAnnotationPosition
1000                                 .resourceVariable(location.toList(),
1001                                                   currentLambda,
1002                                                   frame.pos);
1003                         default:
1004                             throw new AssertionError("Found unexpected type annotation for variable: " + v + " with kind: " + v.getKind());
1005                     }
1006 
1007                 case ANNOTATED_TYPE: {
1008                     if (frame == tree) {
1009                         // This is only true for the first annotated type we see.
1010                         // For any other annotated types along the path, we do
1011                         // not care about inner types.
1012                         JCAnnotatedType atypetree = (JCAnnotatedType) frame;
1013                         final Type utype = atypetree.underlyingType.type;
1014                         Assert.checkNonNull(utype);
1015                         Symbol tsym = utype.tsym;
1016                         if (tsym.getKind().equals(ElementKind.TYPE_PARAMETER) ||
1017                                 utype.getKind().equals(TypeKind.WILDCARD) ||
1018                                 utype.getKind().equals(TypeKind.ARRAY)) {
1019                             // Type parameters, wildcards, and arrays have the declaring
1020                             // class/method as enclosing elements.
1021                             // There is actually nothing to do for them.
1022                         } else {
1023                             location = locateNestedTypes(utype, location);
1024                         }
1025                     }
1026                     List<JCTree> newPath = path.tail;
1027                     return resolveFrame(newPath.head, newPath.tail.head,
1028                                         newPath, currentLambda,
1029                                         outer_type_index, location);
1030                 }
1031 
1032                 case UNION_TYPE: {
1033                     List<JCTree> newPath = path.tail;
1034                     return resolveFrame(newPath.head, newPath.tail.head,
1035                                         newPath, currentLambda,
1036                                         outer_type_index, location);
1037                 }
1038 
1039                 case INTERSECTION_TYPE: {
1040                     JCTypeIntersection isect = (JCTypeIntersection)frame;
1041                     final List<JCTree> newPath = path.tail;
1042                     return resolveFrame(newPath.head, newPath.tail.head,
1043                                         newPath, currentLambda,
1044                                         isect.bounds.indexOf(tree), location);
1045                 }
1046 
1047                 case METHOD_INVOCATION: {
1048                     JCMethodInvocation invocation = (JCMethodInvocation)frame;
1049                     if (!invocation.typeargs.contains(tree)) {
1050                         return TypeAnnotationPosition.unknown;
1051                     }
1052                     MethodSymbol exsym = (MethodSymbol) TreeInfo.symbol(invocation.getMethodSelect());
1053                     final int type_index = invocation.typeargs.indexOf(tree);
1054                     if (exsym == null) {
1055                         throw new AssertionError("could not determine symbol for {" + invocation + "}");
1056                     } else if (exsym.isConstructor()) {
1057                         return TypeAnnotationPosition
1058                             .constructorInvocationTypeArg(location.toList(),
1059                                                           currentLambda,
1060                                                           type_index,
1061                                                           invocation.pos);
1062                     } else {
1063                         return TypeAnnotationPosition
1064                             .methodInvocationTypeArg(location.toList(),
1065                                                      currentLambda,
1066                                                      type_index,
1067                                                      invocation.pos);
1068                     }
1069                 }
1070 
1071                 case EXTENDS_WILDCARD:
1072                 case SUPER_WILDCARD: {
1073                     // Annotations in wildcard bounds
1074                     final List<JCTree> newPath = path.tail;
1075                     return resolveFrame(newPath.head, newPath.tail.head,
1076                                         newPath, currentLambda,
1077                                         outer_type_index,
1078                                         location.prepend(TypePathEntry.WILDCARD));
1079                 }
1080 
1081                 case MEMBER_SELECT: {
1082                     final List<JCTree> newPath = path.tail;
1083                     return resolveFrame(newPath.head, newPath.tail.head,
1084                                         newPath, currentLambda,
1085                                         outer_type_index, location);
1086                 }
1087 
1088                 default:
1089                     throw new AssertionError("Unresolved frame: " + frame +
1090                                              " of kind: " + frame.getKind() +
1091                                              "\n    Looking for tree: " + tree);
1092             }
1093         }
1094 
1095         private ListBuffer<TypePathEntry>
1096             locateNestedTypes(Type type,
1097                               ListBuffer<TypePathEntry> depth) {
1098             Type encl = type.getEnclosingType();
1099             while (encl != null &&
1100                     encl.getKind() != TypeKind.NONE &&
1101                     encl.getKind() != TypeKind.ERROR) {
1102                 depth = depth.prepend(TypePathEntry.INNER_TYPE);
1103                 encl = encl.getEnclosingType();
1104             }
1105             return depth;
1106         }
1107 
1108         private int methodParamIndex(List<JCTree> path, JCTree param) {
1109             List<JCTree> curr = path;
1110             while (curr.head.getTag() != Tag.METHODDEF &&
1111                     curr.head.getTag() != Tag.LAMBDA) {
1112                 curr = curr.tail;
1113             }
1114             if (curr.head.getTag() == Tag.METHODDEF) {
1115                 JCMethodDecl method = (JCMethodDecl)curr.head;
1116                 return method.params.indexOf(param);
1117             } else if (curr.head.getTag() == Tag.LAMBDA) {
1118                 JCLambda lambda = (JCLambda)curr.head;
1119                 return lambda.params.indexOf(param);
1120             } else {
1121                 Assert.error("methodParamIndex expected to find method or lambda for param: " + param);
1122                 return -1;
1123             }
1124         }
1125 
1126         // Each class (including enclosed inner classes) is visited separately.
1127         // This flag is used to prevent from visiting inner classes.
1128         private boolean isInClass = false;
1129 
1130         @Override
1131         public void visitClassDef(JCClassDecl tree) {
1132             if (isInClass)
1133                 return;
1134             isInClass = true;
1135 
1136             if (sigOnly) {
1137                 scan(tree.mods);
1138                 scan(tree.typarams);
1139                 scan(tree.extending);
1140                 scan(tree.implementing);
1141             }
1142             scan(tree.defs);
1143             if (tree.sym.isRecord()) {
1144                 tree.sym.getRecordComponents().forEach(rc -> scan(rc.accessorMeth));
1145             }
1146         }
1147 
1148         /**
1149          * Resolve declaration vs. type annotations in methods and
1150          * then determine the positions.
1151          */
1152         @Override
1153         public void visitMethodDef(final JCMethodDecl tree) {
1154             if (tree.sym == null) {
1155                 Assert.error("Visiting tree node before memberEnter");
1156             }
1157             if (sigOnly) {
1158                 if (!tree.mods.annotations.isEmpty()) {
1159                     if (tree.sym.isConstructor()) {
1160                         final TypeAnnotationPosition pos =
1161                             TypeAnnotationPosition.methodReturn(tree.pos);
1162                         // Use null to mark that the annotations go
1163                         // with the symbol.
1164                         separateAnnotationsKinds(tree, null, tree.sym, pos);
1165                     } else {
1166                         final TypeAnnotationPosition pos =
1167                             TypeAnnotationPosition.methodReturn(tree.restype.pos);
1168                         separateAnnotationsKinds(tree.restype,
1169                                                  tree.sym.type.getReturnType(),
1170                                                  tree.sym, pos);
1171                     }
1172                 }
1173                 if (tree.recvparam != null && tree.recvparam.sym != null &&
1174                         !tree.recvparam.mods.annotations.isEmpty()) {
1175                     // Nothing to do for separateAnnotationsKinds if
1176                     // there are no annotations of either kind.
1177                     // TODO: make sure there are no declaration annotations.
1178                     final TypeAnnotationPosition pos = TypeAnnotationPosition.methodReceiver(tree.recvparam.vartype.pos);
1179                     push(tree.recvparam);
1180                     try {
1181                         separateAnnotationsKinds(tree.recvparam.vartype, tree.recvparam.sym.type, tree.recvparam.sym, pos);
1182                     } finally {
1183                         pop();
1184                     }
1185                 }
1186                 int i = 0;
1187                 for (JCVariableDecl param : tree.params) {
1188                     if (!param.mods.annotations.isEmpty()) {
1189                         // Nothing to do for separateAnnotationsKinds if
1190                         // there are no annotations of either kind.
1191                         final TypeAnnotationPosition pos = TypeAnnotationPosition.methodParameter(i, param.vartype.pos);
1192                         push(param);
1193                         try {
1194                             separateAnnotationsKinds(param.vartype, param.sym.type, param.sym, pos);
1195                         } finally {
1196                             pop();
1197                         }
1198                     }
1199                     ++i;
1200                 }
1201             }
1202 
1203             if (sigOnly) {
1204                 scan(tree.mods);
1205                 scan(tree.restype);
1206                 scan(tree.typarams);
1207                 scan(tree.recvparam);
1208                 scan(tree.params);
1209                 scan(tree.thrown);
1210             } else {
1211                 scan(tree.defaultValue);
1212                 scan(tree.body);
1213             }
1214         }
1215 
1216         /* Store a reference to the current lambda expression, to
1217          * be used by all type annotations within this expression.
1218          */
1219         private JCLambda currentLambda = null;
1220 
1221         public void visitLambda(JCLambda tree) {
1222             JCLambda prevLambda = currentLambda;
1223             try {
1224                 currentLambda = tree;
1225 
1226                 int i = 0;
1227                 for (JCVariableDecl param : tree.params) {
1228                     if (!param.mods.annotations.isEmpty()) {
1229                         // Nothing to do for separateAnnotationsKinds if
1230                         // there are no annotations of either kind.
1231                         final TypeAnnotationPosition pos =  TypeAnnotationPosition
1232                                 .methodParameter(tree, i, param.vartype.pos);
1233                         push(param);
1234                         try {
1235                             if (!param.declaredUsingVar()) {
1236                                 separateAnnotationsKinds(param.vartype, param.sym.type, param.sym, pos);
1237                             }
1238                         } finally {
1239                             pop();
1240                         }
1241                     }
1242                     ++i;
1243                 }
1244 
1245                 scan(tree.body);
1246                 scan(tree.params);
1247             } finally {
1248                 currentLambda = prevLambda;
1249             }
1250         }
1251 
1252         /**
1253          * Resolve declaration vs. type annotations in variable declarations and
1254          * then determine the positions.
1255          */
1256         @Override
1257         public void visitVarDef(final JCVariableDecl tree) {
1258             if (tree.mods.annotations.isEmpty()) {
1259                 // Nothing to do for separateAnnotationsKinds if
1260                 // there are no annotations of either kind.
1261             } else if (tree.sym == null) {
1262                 Assert.error("Visiting tree node before memberEnter");
1263             } else if (tree.sym.getKind() == ElementKind.PARAMETER) {
1264                 // Parameters are handled in visitMethodDef or visitLambda.
1265             } else if (tree.sym.getKind() == ElementKind.FIELD) {
1266                 if (sigOnly) {
1267                     TypeAnnotationPosition pos =
1268                         TypeAnnotationPosition.field(tree.pos);
1269                     separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
1270                 }
1271             } else if (tree.sym.getKind() == ElementKind.LOCAL_VARIABLE) {
1272                 final TypeAnnotationPosition pos =
1273                     TypeAnnotationPosition.localVariable(currentLambda,
1274                                                          tree.pos);
1275                 if (!tree.declaredUsingVar()) {
1276                     separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
1277                 }
1278             } else if (tree.sym.getKind() == ElementKind.BINDING_VARIABLE) {
1279                 final TypeAnnotationPosition pos =
1280                     TypeAnnotationPosition.localVariable(currentLambda,
1281                                                          tree.pos);
1282                 separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
1283             } else if (tree.sym.getKind() == ElementKind.EXCEPTION_PARAMETER) {
1284                 final TypeAnnotationPosition pos =
1285                     TypeAnnotationPosition.exceptionParameter(currentLambda,
1286                                                               tree.pos);
1287                 separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
1288             } else if (tree.sym.getKind() == ElementKind.RESOURCE_VARIABLE) {
1289                 final TypeAnnotationPosition pos =
1290                     TypeAnnotationPosition.resourceVariable(currentLambda,
1291                                                             tree.pos);
1292                 separateAnnotationsKinds(tree.vartype, tree.sym.type, tree.sym, pos);
1293             } else if (tree.sym.getKind() == ElementKind.ENUM_CONSTANT) {
1294                 // No type annotations can occur here.
1295             } else {
1296                 // There is nothing else in a variable declaration that needs separation.
1297                 Assert.error("Unhandled variable kind: " + tree.sym.getKind());
1298             }
1299 
1300             scan(tree.mods);
1301             scan(tree.vartype);
1302             if (!sigOnly) {
1303                 scan(tree.init);
1304             }
1305         }
1306 
1307         @Override
1308         public void visitBlock(JCBlock tree) {
1309             // Do not descend into top-level blocks when only interested
1310             // in the signature.
1311             if (!sigOnly) {
1312                 scan(tree.stats);
1313             }
1314         }
1315 
1316         @Override
1317         public void visitAnnotatedType(JCAnnotatedType tree) {
1318             push(tree);
1319             findPosition(tree, tree, tree.annotations);
1320             pop();
1321             super.visitAnnotatedType(tree);
1322         }
1323 
1324         @Override
1325         public void visitTypeParameter(JCTypeParameter tree) {
1326             findPosition(tree, peek2(), tree.annotations);
1327             super.visitTypeParameter(tree);
1328         }
1329 
1330         private void propagateNewClassAnnotationsToOwner(JCNewClass tree) {
1331             Symbol sym = tree.def.sym;
1332             // The anonymous class' synthetic class declaration is itself an inner class,
1333             // so the type path is one INNER_TYPE entry deeper than that of the
1334             // lexically enclosing class.
1335             List<TypePathEntry> depth =
1336                     locateNestedTypes(sym.owner.enclClass().type, new ListBuffer<>())
1337                             .append(TypePathEntry.INNER_TYPE).toList();
1338             TypeAnnotationPosition pos =
1339                     TypeAnnotationPosition.newObj(depth, /* currentLambda= */ null, tree.pos);
1340 
1341             ListBuffer<Attribute.TypeCompound> newattrs = new ListBuffer<>();
1342             List<TypePathEntry> expectedLocation =
1343                     locateNestedTypes(tree.clazz.type, new ListBuffer<>()).toList();
1344             for (Attribute.TypeCompound old : sym.getRawTypeAttributes()) {
1345                 // Only propagate type annotations from the top-level supertype,
1346                 // (including if the supertype is an inner class).
1347                 if (old.position.location.equals(expectedLocation)) {
1348                     newattrs.append(new Attribute.TypeCompound(old.type, old.values, pos));
1349                 }
1350             }
1351 
1352             sym.owner.appendUniqueTypeAttributes(newattrs.toList());
1353         }
1354 
1355         @Override
1356         public void visitNewClass(JCNewClass tree) {
1357             if (tree.def != null && tree.def.sym != null) {
1358                 propagateNewClassAnnotationsToOwner(tree);
1359             }
1360 
1361             scan(tree.encl);
1362             scan(tree.typeargs);
1363             if (tree.def == null) {
1364                 scan(tree.clazz);
1365             } // else super type will already have been scanned in the context of the anonymous class.
1366             scan(tree.args);
1367 
1368             // The class body will already be scanned.
1369             // scan(tree.def);
1370         }
1371 
1372         @Override
1373         public void visitNewArray(JCNewArray tree) {
1374             findPosition(tree, tree, tree.annotations);
1375             int dimAnnosCount = tree.dimAnnotations.size();
1376             ListBuffer<TypePathEntry> depth = new ListBuffer<>();
1377 
1378             // handle annotations associated with dimensions
1379             for (int i = 0; i < dimAnnosCount; ++i) {
1380                 ListBuffer<TypePathEntry> location =
1381                     new ListBuffer<TypePathEntry>();
1382                 if (i != 0) {
1383                     depth = depth.append(TypePathEntry.ARRAY);
1384                     location = location.appendList(depth.toList());
1385                 }
1386                 final TypeAnnotationPosition p =
1387                     TypeAnnotationPosition.newObj(location.toList(),
1388                                                   currentLambda,
1389                                                   tree.pos);
1390 
1391                 setTypeAnnotationPos(tree.dimAnnotations.get(i), p);
1392             }
1393 
1394             // handle "free" annotations
1395             // int i = dimAnnosCount == 0 ? 0 : dimAnnosCount - 1;
1396             // TODO: is depth.size == i here?
1397             JCExpression elemType = tree.elemtype;
1398             depth = depth.append(TypePathEntry.ARRAY);
1399             while (elemType != null) {
1400                 if (elemType.hasTag(JCTree.Tag.ANNOTATED_TYPE)) {
1401                     JCAnnotatedType at = (JCAnnotatedType)elemType;
1402                     final ListBuffer<TypePathEntry> locationbuf =
1403                         locateNestedTypes(elemType.type,
1404                                           new ListBuffer<TypePathEntry>());
1405                     final List<TypePathEntry> location =
1406                         locationbuf.toList().prependList(depth.toList());
1407                     final TypeAnnotationPosition p =
1408                         TypeAnnotationPosition.newObj(location, currentLambda,
1409                                                       tree.pos);
1410                     setTypeAnnotationPos(at.annotations, p);
1411                     elemType = at.underlyingType;
1412                 } else if (elemType.hasTag(JCTree.Tag.TYPEARRAY)) {
1413                     depth = depth.append(TypePathEntry.ARRAY);
1414                     elemType = ((JCArrayTypeTree)elemType).elemtype;
1415                 } else if (elemType.hasTag(JCTree.Tag.SELECT)) {
1416                     elemType = ((JCFieldAccess)elemType).selected;
1417                 } else {
1418                     break;
1419                 }
1420             }
1421             scan(tree.elems);
1422         }
1423 
1424         private void findPosition(JCTree tree, JCTree frame, List<JCAnnotation> annotations) {
1425             if (!annotations.isEmpty())
1426             {
1427                 final TypeAnnotationPosition p =
1428                     resolveFrame(tree, frame, frames, currentLambda, 0, new ListBuffer<>());
1429 
1430                 setTypeAnnotationPos(annotations, p);
1431             }
1432         }
1433 
1434         private void setTypeAnnotationPos(List<JCAnnotation> annotations, TypeAnnotationPosition position)
1435         {
1436             // attribute might be null during DeferredAttr;
1437             // we will be back later.
1438             for (JCAnnotation anno : annotations) {
1439                 if (anno.attribute != null)
1440                     ((Attribute.TypeCompound) anno.attribute).position = position;
1441             }
1442         }
1443 
1444 
1445         @Override
1446         public String toString() {
1447             return super.toString() + ": sigOnly: " + sigOnly;
1448         }
1449     }
1450 }