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

Sun, 20 Oct 2013 12:01:43 -0700

author
jjg
date
Sun, 20 Oct 2013 12:01:43 -0700
changeset 2149
e5d3cd43c85e
parent 2136
7f6481e5fe3a
child 2150
ae4f5cb78ebd
permissions
-rw-r--r--

8025109: Better encapsulation for AnnotatedType
Reviewed-by: jjg
Contributed-by: wdietl@gmail.com

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

mercurial