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