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