src/share/classes/com/sun/tools/javac/code/TypeAnnotations.java

Thu, 10 Oct 2013 20:12:08 -0400

author
emc
date
Thu, 10 Oct 2013 20:12:08 -0400
changeset 2103
b1b4a6dcc282
parent 2056
5043e7056be8
child 2111
87b5bfef7edb
permissions
-rw-r--r--

8008762: Type annotation on inner class in anonymous class show up as regular type annotations
8015257: type annotation with TYPE_USE and FIELD attributed differently if repeated.
8013409: test failures for type annotations
Summary: Fixes to address some problems in type annotations
Reviewed-by: jfranck, jjg

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

mercurial