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