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