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