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