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