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