1 /* 2 * Copyright (c) 2003, 2025, 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.comp; 27 28 import com.sun.tools.javac.code.*; 29 import com.sun.tools.javac.code.Attribute.Compound; 30 import com.sun.tools.javac.code.Attribute.TypeCompound; 31 import com.sun.tools.javac.code.Kinds.KindSelector; 32 import com.sun.tools.javac.code.Scope.WriteableScope; 33 import com.sun.tools.javac.code.Source.Feature; 34 import com.sun.tools.javac.code.Symbol.*; 35 import com.sun.tools.javac.code.TypeMetadata.Annotations; 36 import com.sun.tools.javac.comp.Check.CheckContext; 37 import com.sun.tools.javac.resources.CompilerProperties.Errors; 38 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 39 import com.sun.tools.javac.tree.JCTree; 40 import com.sun.tools.javac.tree.JCTree.*; 41 import com.sun.tools.javac.tree.TreeInfo; 42 import com.sun.tools.javac.tree.TreeMaker; 43 import com.sun.tools.javac.tree.TreeScanner; 44 import com.sun.tools.javac.util.*; 45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 46 import com.sun.tools.javac.util.List; 47 48 import javax.tools.JavaFileObject; 49 50 import java.util.*; 51 52 import static com.sun.tools.javac.code.Flags.SYNTHETIC; 53 import static com.sun.tools.javac.code.Kinds.Kind.MDL; 54 import static com.sun.tools.javac.code.Kinds.Kind.MTH; 55 import static com.sun.tools.javac.code.Kinds.Kind.PCK; 56 import static com.sun.tools.javac.code.Kinds.Kind.TYP; 57 import static com.sun.tools.javac.code.Kinds.Kind.VAR; 58 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 59 import static com.sun.tools.javac.code.TypeTag.ARRAY; 60 import static com.sun.tools.javac.code.TypeTag.CLASS; 61 import static com.sun.tools.javac.tree.JCTree.Tag.ANNOTATION; 62 import static com.sun.tools.javac.tree.JCTree.Tag.ASSIGN; 63 import static com.sun.tools.javac.tree.JCTree.Tag.IDENT; 64 import static com.sun.tools.javac.tree.JCTree.Tag.NEWARRAY; 65 66 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 67 68 69 /** Enter annotations onto symbols and types (and trees). 70 * 71 * This is also a pseudo stage in the compiler taking care of scheduling when annotations are 72 * entered. 73 * 74 * <p><b>This is NOT part of any supported API. 75 * If you write code that depends on this, you do so at your own risk. 76 * This code and its internal interfaces are subject to change or 77 * deletion without notice.</b> 78 */ 79 public class Annotate { 80 protected static final Context.Key<Annotate> annotateKey = new Context.Key<>(); 81 82 public static Annotate instance(Context context) { 83 Annotate instance = context.get(annotateKey); 84 if (instance == null) 85 instance = new Annotate(context); 86 return instance; 87 } 88 89 private final Attr attr; 90 private final Check chk; 91 private final ConstFold cfolder; 92 private final DeferredLintHandler deferredLintHandler; 93 private final Enter enter; 94 private final Lint lint; 95 private final Log log; 96 private final Names names; 97 private final Resolve resolve; 98 private final TreeMaker make; 99 private final Symtab syms; 100 private final TypeEnvs typeEnvs; 101 private final Types types; 102 103 private final Attribute theUnfinishedDefaultValue; 104 private final String sourceName; 105 106 @SuppressWarnings("this-escape") 107 protected Annotate(Context context) { 108 context.put(annotateKey, this); 109 110 attr = Attr.instance(context); 111 chk = Check.instance(context); 112 cfolder = ConstFold.instance(context); 113 deferredLintHandler = DeferredLintHandler.instance(context); 114 enter = Enter.instance(context); 115 log = Log.instance(context); 116 lint = Lint.instance(context); 117 make = TreeMaker.instance(context); 118 names = Names.instance(context); 119 resolve = Resolve.instance(context); 120 syms = Symtab.instance(context); 121 typeEnvs = TypeEnvs.instance(context); 122 types = Types.instance(context); 123 124 theUnfinishedDefaultValue = new Attribute.Error(syms.errType); 125 126 Source source = Source.instance(context); 127 sourceName = source.name; 128 129 blockCount = 1; 130 } 131 132 /** Semaphore to delay annotation processing */ 133 private int blockCount = 0; 134 135 /** Called when annotations processing needs to be postponed. */ 136 public void blockAnnotations() { 137 blockCount++; 138 } 139 140 /** Called when annotation processing can be resumed. */ 141 public void unblockAnnotations() { 142 blockCount--; 143 if (blockCount == 0) 144 flush(); 145 } 146 147 /** Variant which allows for a delayed flush of annotations. 148 * Needed by ClassReader */ 149 public void unblockAnnotationsNoFlush() { 150 blockCount--; 151 } 152 153 /** are we blocking annotation processing? */ 154 public boolean annotationsBlocked() {return blockCount > 0; } 155 156 public void enterDone() { 157 unblockAnnotations(); 158 } 159 160 public List<TypeCompound> fromAnnotations(List<JCAnnotation> annotations) { 161 if (annotations.isEmpty()) { 162 return List.nil(); 163 } 164 165 ListBuffer<TypeCompound> buf = new ListBuffer<>(); 166 for (JCAnnotation anno : annotations) { 167 Assert.checkNonNull(anno.attribute); 168 buf.append((TypeCompound) anno.attribute); 169 } 170 return buf.toList(); 171 } 172 173 /** Annotate (used for everything else) */ 174 public void normal(Runnable r) { 175 q.append(r); 176 } 177 178 /** Validate, triggers after 'normal' */ 179 public void validate(Runnable a) { 180 validateQ.append(a); 181 } 182 183 /** Flush all annotation queues */ 184 public void flush() { 185 if (annotationsBlocked()) return; 186 if (isFlushing()) return; 187 188 startFlushing(); 189 try { 190 while (q.nonEmpty()) { 191 q.next().run(); 192 } 193 while (typesQ.nonEmpty()) { 194 typesQ.next().run(); 195 } 196 while (afterTypesQ.nonEmpty()) { 197 afterTypesQ.next().run(); 198 } 199 while (validateQ.nonEmpty()) { 200 validateQ.next().run(); 201 } 202 } finally { 203 doneFlushing(); 204 } 205 } 206 207 private ListBuffer<Runnable> q = new ListBuffer<>(); 208 private ListBuffer<Runnable> validateQ = new ListBuffer<>(); 209 210 private int flushCount = 0; 211 private boolean isFlushing() { return flushCount > 0; } 212 private void startFlushing() { flushCount++; } 213 private void doneFlushing() { flushCount--; } 214 215 ListBuffer<Runnable> typesQ = new ListBuffer<>(); 216 ListBuffer<Runnable> afterTypesQ = new ListBuffer<>(); 217 218 219 public void typeAnnotation(Runnable a) { 220 typesQ.append(a); 221 } 222 223 public void afterTypes(Runnable a) { 224 afterTypesQ.append(a); 225 } 226 227 /** 228 * Queue annotations for later attribution and entering. This is probably the method you are looking for. 229 * 230 * @param annotations the list of JCAnnotations to attribute and enter 231 * @param localEnv the enclosing env 232 * @param s the Symbol on which to enter the annotations 233 * @param deferDecl enclosing declaration for DeferredLintHandler, or null for no deferral 234 */ 235 public void annotateLater(List<JCAnnotation> annotations, Env<AttrContext> localEnv, 236 Symbol s, JCTree deferDecl) 237 { 238 if (annotations.isEmpty()) { 239 return; 240 } 241 242 s.resetAnnotations(); // mark Annotations as incomplete for now 243 244 normal(() -> { 245 // Packages are unusual, in that they are the only type of declaration that can legally appear 246 // more than once in a compilation, and in all cases refer to the same underlying symbol. 247 // This means they are the only kind of declaration that syntactically may have multiple sets 248 // of annotations, each on a different package declaration, even though that is ultimately 249 // forbidden by JLS 8 section 7.4. 250 // The corollary here is that all of the annotations on a package symbol may have already 251 // been handled, meaning that the set of annotations pending completion is now empty. 252 Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); 253 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 254 Assert.check(deferDecl != null); 255 deferredLintHandler.push(deferDecl); 256 try { 257 if (s.hasAnnotations() && annotations.nonEmpty()) 258 log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); 259 260 Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); 261 262 // false is passed as fifth parameter since annotateLater is 263 // never called for a type parameter 264 annotateNow(s, annotations, localEnv, false, false); 265 } finally { 266 deferredLintHandler.pop(); 267 log.useSource(prev); 268 } 269 }); 270 271 validate(() -> { //validate annotations 272 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 273 try { 274 chk.validateAnnotations(annotations, TreeInfo.declarationFor(s, localEnv.tree), s); 275 } finally { 276 log.useSource(prev); 277 } 278 }); 279 } 280 281 282 /** Queue processing of an attribute default value. */ 283 public void annotateDefaultValueLater(JCExpression defaultValue, Env<AttrContext> localEnv, 284 MethodSymbol m, JCTree deferDecl) 285 { 286 normal(() -> { 287 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 288 deferredLintHandler.push(deferDecl); 289 try { 290 enterDefaultValue(defaultValue, localEnv, m); 291 } finally { 292 deferredLintHandler.pop(); 293 log.useSource(prev); 294 } 295 }); 296 297 validate(() -> { //validate annotations 298 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 299 try { 300 // if default value is an annotation, check it is a well-formed 301 // annotation value (e.g. no duplicate values, no missing values, etc.) 302 chk.validateAnnotationTree(defaultValue); 303 } finally { 304 log.useSource(prev); 305 } 306 }); 307 } 308 309 /** Enter a default value for an annotation element. */ 310 private void enterDefaultValue(JCExpression defaultValue, 311 Env<AttrContext> localEnv, MethodSymbol m) { 312 m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); 313 } 314 315 /** 316 * Gather up annotations into a map from type symbols to lists of Compound attributes, 317 * then continue on with repeating annotations processing. 318 */ 319 private <T extends Attribute.Compound> void annotateNow(Symbol toAnnotate, 320 List<JCAnnotation> withAnnotations, Env<AttrContext> env, boolean typeAnnotations, 321 boolean isTypeParam) 322 { 323 Map<TypeSymbol, ListBuffer<T>> annotated = new LinkedHashMap<>(); 324 Map<T, DiagnosticPosition> pos = new HashMap<>(); 325 326 for (List<JCAnnotation> al = withAnnotations; !al.isEmpty(); al = al.tail) { 327 JCAnnotation a = al.head; 328 329 T c; 330 if (typeAnnotations) { 331 @SuppressWarnings("unchecked") 332 T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); 333 c = tmp; 334 } else { 335 @SuppressWarnings("unchecked") 336 T tmp = (T)attributeAnnotation(a, syms.annotationType, env); 337 c = tmp; 338 } 339 340 Assert.checkNonNull(c, "Failed to create annotation"); 341 342 if (a.type.isErroneous() || a.type.tsym.isAnnotationType()) { 343 if (annotated.containsKey(a.type.tsym)) { 344 ListBuffer<T> l = annotated.get(a.type.tsym); 345 l = l.append(c); 346 annotated.put(a.type.tsym, l); 347 pos.put(c, a.pos()); 348 } else { 349 annotated.put(a.type.tsym, ListBuffer.of(c)); 350 pos.put(c, a.pos()); 351 } 352 } 353 354 // Note: @Deprecated has no effect on local variables and parameters 355 if (!c.type.isErroneous() 356 && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) 357 && types.isSameType(c.type, syms.deprecatedType)) { 358 toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); 359 if (isAttributeTrue(c.member(names.forRemoval))) { 360 toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; 361 } 362 } 363 364 if (!c.type.isErroneous() 365 && types.isSameType(c.type, syms.previewFeatureType)) { 366 toAnnotate.flags_field |= Flags.PREVIEW_API; 367 if (isAttributeTrue(c.member(names.reflective))) { 368 toAnnotate.flags_field |= Flags.PREVIEW_REFLECTIVE; 369 } 370 } 371 372 if (!c.type.isErroneous() 373 && toAnnotate.kind == TYP 374 && types.isSameType(c.type, syms.valueBasedType)) { 375 toAnnotate.flags_field |= Flags.VALUE_BASED; 376 } 377 378 if (!c.type.isErroneous() 379 && types.isSameType(c.type, syms.restrictedType)) { 380 toAnnotate.flags_field |= Flags.RESTRICTED; 381 } 382 } 383 384 List<T> buf = List.nil(); 385 for (ListBuffer<T> lb : annotated.values()) { 386 if (lb.size() == 1) { 387 buf = buf.prepend(lb.first()); 388 } else { 389 AnnotationContext<T> ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); 390 T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); 391 if (res != null) 392 buf = buf.prepend(res); 393 } 394 } 395 396 if (typeAnnotations) { 397 @SuppressWarnings("unchecked") 398 List<TypeCompound> attrs = (List<TypeCompound>)buf.reverse(); 399 toAnnotate.appendUniqueTypeAttributes(attrs); 400 } else { 401 @SuppressWarnings("unchecked") 402 List<Attribute.Compound> attrs = (List<Attribute.Compound>)buf.reverse(); 403 toAnnotate.resetAnnotations(); 404 toAnnotate.setDeclarationAttributes(attrs); 405 } 406 } 407 //where: 408 private boolean isAttributeTrue(Attribute attr) { 409 return (attr instanceof Attribute.Constant constant) 410 && constant.type == syms.booleanType 411 && ((Integer) constant.value) != 0; 412 } 413 414 /** 415 * Attribute and store a semantic representation of the annotation tree {@code tree} into the 416 * tree.attribute field. 417 * 418 * @param tree the tree representing an annotation 419 * @param expectedAnnotationType the expected (super)type of the annotation 420 * @param env the current env in where the annotation instance is found 421 */ 422 public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, 423 Env<AttrContext> env) 424 { 425 // The attribute might have been entered if it is Target or Repeatable 426 // Because TreeCopier does not copy type, redo this if type is null 427 if (tree.attribute != null && tree.type != null) 428 return tree.attribute; 429 430 List<Pair<MethodSymbol, Attribute>> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); 431 Attribute.Compound ac = new Attribute.Compound(tree.type, elems); 432 433 return tree.attribute = ac; 434 } 435 436 /** Attribute and store a semantic representation of the type annotation tree {@code tree} into 437 * the tree.attribute field. 438 * 439 * @param a the tree representing an annotation 440 * @param expectedAnnotationType the expected (super)type of the annotation 441 * @param env the current env in where the annotation instance is found 442 */ 443 public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, 444 Env<AttrContext> env) 445 { 446 // The attribute might have been entered if it is Target or Repeatable 447 // Because TreeCopier does not copy type, redo this if type is null 448 if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound typeCompound)) { 449 // Create a new TypeCompound 450 List<Pair<MethodSymbol,Attribute>> elems = 451 attributeAnnotationValues(a, expectedAnnotationType, env); 452 453 Attribute.TypeCompound tc = 454 new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); 455 a.attribute = tc; 456 return tc; 457 } else { 458 // Use an existing TypeCompound 459 return typeCompound; 460 } 461 } 462 463 /** 464 * Attribute annotation elements creating a list of pairs of the Symbol representing that 465 * element and the value of that element as an Attribute. */ 466 private List<Pair<MethodSymbol, Attribute>> attributeAnnotationValues(JCAnnotation a, 467 Type expected, Env<AttrContext> env) 468 { 469 // The annotation might have had its type attributed (but not 470 // checked) by attr.attribAnnotationTypes during MemberEnter, 471 // in which case we do not need to do it again. 472 Type at = (a.annotationType.type != null ? 473 a.annotationType.type : attr.attribType(a.annotationType, env)); 474 a.type = chk.checkType(a.annotationType.pos(), at, expected); 475 476 boolean isError = a.type.isErroneous(); 477 if (!a.type.tsym.isAnnotationType() && !isError) { 478 log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); 479 isError = true; 480 } 481 482 // List of name=value pairs (or implicit "value=" if size 1) 483 List<JCExpression> args = a.args; 484 485 boolean elidedValue = false; 486 // special case: elided "value=" assumed 487 if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { 488 args.head = make.at(args.head.pos). 489 Assign(make.Ident(names.value), args.head); 490 elidedValue = true; 491 } 492 493 ListBuffer<Pair<MethodSymbol,Attribute>> buf = new ListBuffer<>(); 494 for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) { 495 Pair<MethodSymbol, Attribute> p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); 496 if (p != null && !p.fst.type.isErroneous()) 497 buf.append(p); 498 } 499 return buf.toList(); 500 } 501 502 // where 503 private Pair<MethodSymbol, Attribute> attributeAnnotationNameValuePair(JCExpression nameValuePair, 504 Type thisAnnotationType, boolean badAnnotation, Env<AttrContext> env, boolean elidedValue) 505 { 506 if (!nameValuePair.hasTag(ASSIGN)) { 507 log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); 508 attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); 509 return null; 510 } 511 JCAssign assign = (JCAssign)nameValuePair; 512 if (!assign.lhs.hasTag(IDENT)) { 513 log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); 514 attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); 515 return null; 516 } 517 518 // Resolve element to MethodSym 519 JCIdent left = (JCIdent)assign.lhs; 520 Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), 521 env, thisAnnotationType, 522 left.name, List.nil(), null); 523 left.sym = method; 524 left.type = method.type; 525 chk.checkDeprecated(left, env.info.scope.owner, method); 526 if (method.owner != thisAnnotationType.tsym && !badAnnotation) 527 log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); 528 Type resultType = method.type.getReturnType(); 529 530 // Compute value part 531 Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); 532 nameValuePair.type = resultType; 533 534 return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); 535 536 } 537 538 /** Attribute an annotation element value */ 539 private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, 540 Env<AttrContext> env) 541 { 542 //first, try completing the symbol for the annotation value - if a completion 543 //error is thrown, we should recover gracefully, and display an 544 //ordinary resolution diagnostic. 545 try { 546 expectedElementType.tsym.complete(); 547 } catch(CompletionFailure e) { 548 log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); 549 expectedElementType = syms.errType; 550 } 551 552 if (expectedElementType.hasTag(ARRAY)) { 553 return getAnnotationArrayValue(expectedElementType, tree, env); 554 } 555 556 //error recovery 557 if (tree.hasTag(NEWARRAY)) { 558 if (!expectedElementType.isErroneous()) 559 log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); 560 JCNewArray na = (JCNewArray)tree; 561 if (na.elemtype != null) { 562 log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); 563 } 564 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) { 565 attributeAnnotationValue(syms.errType, 566 l.head, 567 env); 568 } 569 return new Attribute.Error(syms.errType); 570 } 571 572 if (expectedElementType.tsym.isAnnotationType()) { 573 if (tree.hasTag(ANNOTATION)) { 574 return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); 575 } else { 576 log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); 577 expectedElementType = syms.errType; 578 } 579 } 580 581 //error recovery 582 if (tree.hasTag(ANNOTATION)) { 583 if (!expectedElementType.isErroneous()) 584 log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); 585 attributeAnnotation((JCAnnotation)tree, syms.errType, env); 586 return new Attribute.Error(((JCAnnotation)tree).annotationType.type); 587 } 588 589 MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { 590 // the methods below are added to allow class literals on top of constant expressions 591 @Override 592 public void visitTypeIdent(JCPrimitiveTypeTree that) {} 593 594 @Override 595 public void visitTypeArray(JCArrayTypeTree that) {} 596 }; 597 tree.accept(initTreeVisitor); 598 if (!initTreeVisitor.result) { 599 log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); 600 return new Attribute.Error(syms.errType); 601 } 602 603 if (expectedElementType.isPrimitive() || 604 (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { 605 return getAnnotationPrimitiveValue(expectedElementType, tree, env); 606 } 607 608 if (expectedElementType.tsym == syms.classType.tsym) { 609 return getAnnotationClassValue(expectedElementType, tree, env); 610 } 611 612 if (expectedElementType.hasTag(CLASS) && 613 (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { 614 return getAnnotationEnumValue(expectedElementType, tree, env); 615 } 616 617 //error recovery: 618 if (!expectedElementType.isErroneous()) 619 log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); 620 return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); 621 } 622 623 private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) { 624 Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); 625 Symbol sym = TreeInfo.symbol(tree); 626 if (sym == null || 627 TreeInfo.nonstaticSelect(tree) || 628 sym.kind != VAR || 629 (sym.flags() & Flags.ENUM) == 0) { 630 log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); 631 return new Attribute.Error(result.getOriginalType()); 632 } 633 VarSymbol enumerator = (VarSymbol) sym; 634 return new Attribute.Enum(expectedElementType, enumerator); 635 } 636 637 private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) { 638 Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); 639 if (result.isErroneous()) { 640 // Does it look like an unresolved class literal? 641 if (TreeInfo.name(tree) == names._class && 642 ((JCFieldAccess) tree).selected.type.isErroneous()) { 643 Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); 644 return new Attribute.UnresolvedClass(expectedElementType, 645 types.createErrorType(n, 646 syms.unknownSymbol, syms.classType)); 647 } else { 648 return new Attribute.Error(result.getOriginalType()); 649 } 650 } 651 652 // Class literals look like field accesses of a field named class 653 // at the tree level 654 if (TreeInfo.name(tree) != names._class) { 655 log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); 656 return new Attribute.Error(syms.errType); 657 } 658 659 return new Attribute.Class(types, 660 (((JCFieldAccess) tree).selected).type); 661 } 662 663 private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) { 664 Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); 665 if (result.isErroneous()) 666 return new Attribute.Error(result.getOriginalType()); 667 if (result.constValue() == null) { 668 log.error(tree.pos(), Errors.AttributeValueMustBeConstant); 669 return new Attribute.Error(expectedElementType); 670 } 671 672 // Scan the annotation element value and then attribute nested annotations if present 673 if (tree.type != null && tree.type.tsym != null) { 674 queueScanTreeAndTypeAnnotate(tree, env, tree.type.tsym, null); 675 } 676 677 result = cfolder.coerce(result, expectedElementType); 678 return new Attribute.Constant(expectedElementType, result.constValue()); 679 } 680 681 private Attr.ResultInfo annotationValueInfo(Type pt) { 682 return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); 683 } 684 685 class AnnotationValueContext extends Check.NestedCheckContext { 686 AnnotationValueContext(CheckContext enclosingContext) { 687 super(enclosingContext); 688 } 689 690 @Override 691 public boolean compatible(Type found, Type req, Warner warn) { 692 //handle non-final implicitly-typed vars (will be rejected later on) 693 return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); 694 } 695 } 696 697 private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) { 698 // Special case, implicit array 699 if (!tree.hasTag(NEWARRAY)) { 700 tree = make.at(tree.pos). 701 NewArray(null, List.nil(), List.of(tree)); 702 } 703 704 JCNewArray na = (JCNewArray)tree; 705 List<JCExpression> elems = na.elems; 706 if (na.elemtype != null) { 707 log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); 708 if (elems == null) { 709 elems = List.nil(); 710 } 711 } 712 ListBuffer<Attribute> buf = new ListBuffer<>(); 713 for (List<JCExpression> l = elems; l.nonEmpty(); l = l.tail) { 714 buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), 715 l.head, 716 env)); 717 } 718 na.type = expectedElementType; 719 return new Attribute. 720 Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); 721 } 722 723 /* ********************************* 724 * Support for repeating annotations 725 ***********************************/ 726 727 /** 728 * This context contains all the information needed to synthesize new 729 * annotations trees for repeating annotations. 730 */ 731 private class AnnotationContext<T extends Attribute.Compound> { 732 public final Env<AttrContext> env; 733 public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated; 734 public final Map<T, JCDiagnostic.DiagnosticPosition> pos; 735 public final boolean isTypeCompound; 736 737 public AnnotationContext(Env<AttrContext> env, 738 Map<Symbol.TypeSymbol, ListBuffer<T>> annotated, 739 Map<T, JCDiagnostic.DiagnosticPosition> pos, 740 boolean isTypeCompound) { 741 Assert.checkNonNull(env); 742 Assert.checkNonNull(annotated); 743 Assert.checkNonNull(pos); 744 745 this.env = env; 746 this.annotated = annotated; 747 this.pos = pos; 748 this.isTypeCompound = isTypeCompound; 749 } 750 } 751 752 /* Process repeated annotations. This method returns the 753 * synthesized container annotation or null IFF all repeating 754 * annotation are invalid. This method reports errors/warnings. 755 */ 756 private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations, 757 AnnotationContext<T> ctx, Symbol on, boolean isTypeParam) 758 { 759 T firstOccurrence = annotations.head; 760 List<Attribute> repeated = List.nil(); 761 Type origAnnoType = null; 762 Type arrayOfOrigAnnoType = null; 763 Type targetContainerType = null; 764 MethodSymbol containerValueSymbol = null; 765 766 Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 767 768 int count = 0; 769 for (List<T> al = annotations; !al.isEmpty(); al = al.tail) { 770 count++; 771 772 // There must be more than a single anno in the annotation list 773 Assert.check(count > 1 || !al.tail.isEmpty()); 774 775 T currentAnno = al.head; 776 777 origAnnoType = currentAnno.type; 778 if (arrayOfOrigAnnoType == null) { 779 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); 780 } 781 782 // Only report errors if this isn't the first occurrence I.E. count > 1 783 boolean reportError = count > 1; 784 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); 785 if (currentContainerType == null) { 786 continue; 787 } 788 // Assert that the target Container is == for all repeated 789 // annos of the same annotation type, the types should 790 // come from the same Symbol, i.e. be '==' 791 Assert.check(targetContainerType == null || currentContainerType == targetContainerType); 792 targetContainerType = currentContainerType; 793 794 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); 795 796 if (containerValueSymbol == null) { // Check of CA type failed 797 // errors are already reported 798 continue; 799 } 800 801 repeated = repeated.prepend(currentAnno); 802 } 803 804 if (!repeated.isEmpty() && targetContainerType == null) { 805 log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); 806 return null; 807 } 808 809 if (!repeated.isEmpty()) { 810 repeated = repeated.reverse(); 811 DiagnosticPosition pos = ctx.pos.get(firstOccurrence); 812 TreeMaker m = make.at(pos); 813 Pair<MethodSymbol, Attribute> p = 814 new Pair<MethodSymbol, Attribute>(containerValueSymbol, 815 new Attribute.Array(arrayOfOrigAnnoType, repeated)); 816 if (ctx.isTypeCompound) { 817 /* TODO: the following code would be cleaner: 818 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), 819 ((Attribute.TypeCompound)annotations.head).position); 820 JCTypeAnnotation annoTree = m.TypeAnnotation(at); 821 at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); 822 */ 823 // However, we directly construct the TypeCompound to keep the 824 // direct relation to the contained TypeCompounds. 825 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), 826 ((Attribute.TypeCompound)annotations.head).position); 827 828 JCAnnotation annoTree = m.TypeAnnotation(at); 829 if (!chk.validateAnnotationDeferErrors(annoTree)) 830 log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); 831 832 if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { 833 log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) 834 : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); 835 } 836 837 at.setSynthesized(true); 838 839 @SuppressWarnings("unchecked") 840 T x = (T) at; 841 return x; 842 } else { 843 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); 844 JCAnnotation annoTree = m.Annotation(c); 845 846 boolean isRecordMember = (on.flags_field & Flags.RECORD) != 0 || on.enclClass() != null && on.enclClass().isRecord(); 847 /* if it is a record member we will not issue the error now and wait until annotations on records are 848 * checked at Check::validateAnnotation, which will issue it 849 */ 850 if (!chk.annotationApplicable(annoTree, on) && (!isRecordMember || isRecordMember && (on.flags_field & Flags.GENERATED_MEMBER) == 0)) { 851 log.error(annoTree.pos(), 852 Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); 853 } 854 855 if (!chk.validateAnnotationDeferErrors(annoTree)) 856 log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); 857 858 c = attributeAnnotation(annoTree, targetContainerType, ctx.env); 859 c.setSynthesized(true); 860 861 @SuppressWarnings("unchecked") 862 T x = (T) c; 863 return x; 864 } 865 } else { 866 return null; // errors should have been reported elsewhere 867 } 868 } 869 870 /** 871 * Fetches the actual Type that should be the containing annotation. 872 */ 873 private Type getContainingType(Attribute.Compound currentAnno, 874 DiagnosticPosition pos, 875 boolean reportError) 876 { 877 Type origAnnoType = currentAnno.type; 878 TypeSymbol origAnnoDecl = origAnnoType.tsym; 879 880 // Fetch the Repeatable annotation from the current 881 // annotation's declaration, or null if it has none 882 Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); 883 if (ca == null) { // has no Repeatable annotation 884 if (reportError) 885 log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); 886 return null; 887 } 888 889 return filterSame(extractContainingType(ca, pos, origAnnoDecl), 890 origAnnoType); 891 } 892 893 // returns null if t is same as 's', returns 't' otherwise 894 private Type filterSame(Type t, Type s) { 895 if (t == null || s == null) { 896 return t; 897 } 898 899 return types.isSameType(t, s) ? null : t; 900 } 901 902 /** Extract the actual Type to be used for a containing annotation. */ 903 private Type extractContainingType(Attribute.Compound ca, 904 DiagnosticPosition pos, 905 TypeSymbol annoDecl) 906 { 907 // The next three checks check that the Repeatable annotation 908 // on the declaration of the annotation type that is repeating is 909 // valid. 910 911 // Repeatable must have at least one element 912 if (ca.values.isEmpty()) { 913 log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); 914 return null; 915 } 916 Pair<MethodSymbol,Attribute> p = ca.values.head; 917 Name name = p.fst.name; 918 if (name != names.value) { // should contain only one element, named "value" 919 log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); 920 return null; 921 } 922 if (!(p.snd instanceof Attribute.Class attributeClass)) { // check that the value of "value" is an Attribute.Class 923 log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); 924 return null; 925 } 926 927 return attributeClass.getValue(); 928 } 929 930 /* Validate that the suggested targetContainerType Type is a valid 931 * container type for repeated instances of originalAnnoType 932 * annotations. Return null and report errors if this is not the 933 * case, return the MethodSymbol of the value element in 934 * targetContainerType if it is suitable (this is needed to 935 * synthesize the container). */ 936 private MethodSymbol validateContainer(Type targetContainerType, 937 Type originalAnnoType, 938 DiagnosticPosition pos) { 939 MethodSymbol containerValueSymbol = null; 940 boolean fatalError = false; 941 942 // Validate that there is a (and only 1) value method 943 Scope scope = null; 944 try { 945 scope = targetContainerType.tsym.members(); 946 } catch (CompletionFailure ex) { 947 chk.completionError(pos, ex); 948 return null; 949 } 950 int nr_value_elems = 0; 951 boolean error = false; 952 for(Symbol elm : scope.getSymbolsByName(names.value)) { 953 nr_value_elems++; 954 955 if (nr_value_elems == 1 && 956 elm.kind == MTH) { 957 containerValueSymbol = (MethodSymbol)elm; 958 } else { 959 error = true; 960 } 961 } 962 if (error) { 963 log.error(pos, 964 Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, 965 nr_value_elems)); 966 return null; 967 } else if (nr_value_elems == 0) { 968 log.error(pos, 969 Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); 970 return null; 971 } 972 973 // validate that the 'value' element is a method 974 // probably "impossible" to fail this 975 if (containerValueSymbol.kind != MTH) { 976 log.error(pos, 977 Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); 978 fatalError = true; 979 } 980 981 // validate that the 'value' element has the correct return type 982 // i.e. array of original anno 983 Type valueRetType = containerValueSymbol.type.getReturnType(); 984 Type expectedType = types.makeArrayType(originalAnnoType); 985 if (!(types.isArray(valueRetType) && 986 types.isSameType(expectedType, valueRetType))) { 987 log.error(pos, 988 Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, 989 valueRetType, 990 expectedType)); 991 fatalError = true; 992 } 993 994 return fatalError ? null : containerValueSymbol; 995 } 996 997 private <T extends Attribute.Compound> T makeContainerAnnotation(List<T> toBeReplaced, 998 AnnotationContext<T> ctx, Symbol sym, boolean isTypeParam) 999 { 1000 // Process repeated annotations 1001 T validRepeated = 1002 processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); 1003 1004 if (validRepeated != null) { 1005 // Check that the container isn't manually 1006 // present along with repeated instances of 1007 // its contained annotation. 1008 ListBuffer<T> manualContainer = ctx.annotated.get(validRepeated.type.tsym); 1009 if (manualContainer != null) { 1010 log.error(ctx.pos.get(manualContainer.first()), 1011 Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); 1012 } 1013 } 1014 1015 // A null return will delete the Placeholder 1016 return validRepeated; 1017 } 1018 1019 /* ****************** 1020 * Type annotations * 1021 ********************/ 1022 1023 /** 1024 * Attribute the list of annotations and enter them onto s. 1025 */ 1026 public void enterTypeAnnotations(List<JCAnnotation> annotations, Env<AttrContext> env, 1027 Symbol s, JCTree deferDecl, boolean isTypeParam) 1028 { 1029 Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); 1030 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 1031 1032 if (deferDecl != null) { 1033 deferredLintHandler.push(deferDecl); 1034 } 1035 try { 1036 annotateNow(s, annotations, env, true, isTypeParam); 1037 } finally { 1038 if (deferDecl != null) 1039 deferredLintHandler.pop(); 1040 log.useSource(prev); 1041 } 1042 } 1043 1044 /** 1045 * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. 1046 */ 1047 public void queueScanTreeAndTypeAnnotate(JCTree tree, Env<AttrContext> env, Symbol sym, JCTree deferDecl) 1048 { 1049 Assert.checkNonNull(sym); 1050 normal(() -> tree.accept(new TypeAnnotate(env, sym, deferDecl))); 1051 } 1052 1053 /** 1054 * Apply the annotations to the particular type. 1055 */ 1056 public void annotateTypeSecondStage(JCTree tree, List<JCAnnotation> annotations, Type storeAt) { 1057 typeAnnotation(() -> { 1058 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations); 1059 Assert.check(annotations.size() == compounds.size()); 1060 // the type already has annotation metadata, but it's empty 1061 Annotations metadata = storeAt.getMetadata(Annotations.class); 1062 Assert.checkNonNull(metadata); 1063 Assert.check(metadata.annotationBuffer().isEmpty()); 1064 metadata.annotationBuffer().appendList(compounds); 1065 }); 1066 } 1067 1068 /** 1069 * Apply the annotations to the particular type. 1070 */ 1071 public void annotateTypeParameterSecondStage(JCTree tree, List<JCAnnotation> annotations) { 1072 typeAnnotation(() -> { 1073 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations); 1074 Assert.check(annotations.size() == compounds.size()); 1075 }); 1076 } 1077 1078 /** 1079 * We need to use a TreeScanner, because it is not enough to visit the top-level 1080 * annotations. We also need to visit type arguments, etc. 1081 */ 1082 private class TypeAnnotate extends TreeScanner { 1083 private final Env<AttrContext> env; 1084 private final Symbol sym; 1085 private JCTree deferDecl; 1086 1087 public TypeAnnotate(Env<AttrContext> env, Symbol sym, JCTree deferDecl) { 1088 1089 this.env = env; 1090 this.sym = sym; 1091 this.deferDecl = deferDecl; 1092 } 1093 1094 @Override 1095 public void visitAnnotatedType(JCAnnotatedType tree) { 1096 enterTypeAnnotations(tree.annotations, env, sym, deferDecl, false); 1097 scan(tree.underlyingType); 1098 } 1099 1100 @Override 1101 public void visitTypeParameter(JCTypeParameter tree) { 1102 enterTypeAnnotations(tree.annotations, env, sym, deferDecl, true); 1103 scan(tree.bounds); 1104 } 1105 1106 @Override 1107 public void visitNewArray(JCNewArray tree) { 1108 enterTypeAnnotations(tree.annotations, env, sym, deferDecl, false); 1109 for (List<JCAnnotation> dimAnnos : tree.dimAnnotations) 1110 enterTypeAnnotations(dimAnnos, env, sym, deferDecl, false); 1111 scan(tree.elemtype); 1112 scan(tree.elems); 1113 } 1114 1115 @Override 1116 public void visitMethodDef(JCMethodDecl tree) { 1117 scan(tree.mods); 1118 scan(tree.restype); 1119 scan(tree.typarams); 1120 scan(tree.recvparam); 1121 scan(tree.params); 1122 scan(tree.thrown); 1123 scan(tree.defaultValue); 1124 // Do not annotate the body, just the signature. 1125 } 1126 1127 @Override 1128 public void visitVarDef(JCVariableDecl tree) { 1129 JCTree prevDecl = deferDecl; 1130 deferDecl = tree; 1131 try { 1132 if (sym != null && sym.kind == VAR) { 1133 // Don't visit a parameter once when the sym is the method 1134 // and once when the sym is the parameter. 1135 scan(tree.mods); 1136 scan(tree.vartype); 1137 } 1138 scan(tree.init); 1139 } finally { 1140 deferDecl = prevDecl; 1141 } 1142 } 1143 1144 @Override 1145 public void visitBindingPattern(JCTree.JCBindingPattern tree) { 1146 //type binding pattern's type will be annotated separately, avoid 1147 //adding its annotations into the owning method here (would clash 1148 //with repeatable annotations). 1149 } 1150 1151 @Override 1152 public void visitClassDef(JCClassDecl tree) { 1153 // We can only hit a classdef if it is declared within 1154 // a method. Ignore it - the class will be visited 1155 // separately later. 1156 } 1157 1158 @Override 1159 public void visitNewClass(JCNewClass tree) { 1160 scan(tree.encl); 1161 scan(tree.typeargs); 1162 if (tree.def == null) { 1163 scan(tree.clazz); 1164 } 1165 scan(tree.args); 1166 // the anonymous class instantiation if any will be visited separately. 1167 } 1168 1169 @Override 1170 public void visitErroneous(JCErroneous tree) { 1171 if (tree.errs != null) { 1172 for (JCTree err : tree.errs) { 1173 scan(err); 1174 } 1175 } 1176 } 1177 } 1178 1179 /* ******************* 1180 * Completer support * 1181 *********************/ 1182 1183 private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { 1184 @Override 1185 public void complete(ClassSymbol sym) throws CompletionFailure { 1186 Env<AttrContext> context = typeEnvs.get(sym); 1187 Annotate.this.attributeAnnotationType(context); 1188 } 1189 }; 1190 1191 /* Last stage completer to enter just enough annotations to have a prototype annotation type. 1192 * This currently means entering @Target and @Repeatable. 1193 */ 1194 public AnnotationTypeCompleter annotationTypeSourceCompleter() { 1195 return theSourceCompleter; 1196 } 1197 1198 private void attributeAnnotationType(Env<AttrContext> env) { 1199 Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), 1200 "Trying to annotation type complete a non-annotation type"); 1201 1202 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 1203 try { 1204 JCClassDecl tree = (JCClassDecl)env.tree; 1205 AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); 1206 v.scanAnnotationType(tree); 1207 tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); 1208 tree.sym.getAnnotationTypeMetadata().setTarget(v.target); 1209 } finally { 1210 log.useSource(prev); 1211 } 1212 } 1213 1214 public Attribute unfinishedDefaultValue() { 1215 return theUnfinishedDefaultValue; 1216 } 1217 1218 public static interface AnnotationTypeCompleter { 1219 void complete(ClassSymbol sym) throws CompletionFailure; 1220 } 1221 1222 /** Visitor to determine a prototype annotation type for a class declaring an annotation type. 1223 * 1224 * <p><b>This is NOT part of any supported API. 1225 * If you write code that depends on this, you do so at your own risk. 1226 * This code and its internal interfaces are subject to change or 1227 * deletion without notice.</b> 1228 */ 1229 public class AnnotationTypeVisitor extends TreeScanner { 1230 private Env<AttrContext> env; 1231 1232 private final Attr attr; 1233 private final Check check; 1234 private final Symtab tab; 1235 private final TypeEnvs typeEnvs; 1236 1237 private Compound target; 1238 private Compound repeatable; 1239 1240 public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { 1241 this.attr = attr; 1242 this.check = check; 1243 this.tab = tab; 1244 this.typeEnvs = typeEnvs; 1245 } 1246 1247 public Compound getRepeatable() { 1248 return repeatable; 1249 } 1250 1251 public Compound getTarget() { 1252 return target; 1253 } 1254 1255 public void scanAnnotationType(JCClassDecl decl) { 1256 visitClassDef(decl); 1257 } 1258 1259 @Override 1260 public void visitClassDef(JCClassDecl tree) { 1261 Env<AttrContext> prevEnv = env; 1262 env = typeEnvs.get(tree.sym); 1263 try { 1264 scan(tree.mods); // look for repeatable and target 1265 // don't descend into body 1266 } finally { 1267 env = prevEnv; 1268 } 1269 } 1270 1271 @Override 1272 public void visitAnnotation(JCAnnotation tree) { 1273 Type t = tree.annotationType.type; 1274 if (t == null) { 1275 t = attr.attribType(tree.annotationType, env); 1276 tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); 1277 } 1278 1279 if (t == tab.annotationTargetType) { 1280 target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); 1281 } else if (t == tab.repeatableType) { 1282 repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); 1283 } 1284 } 1285 } 1286 1287 /** Represents the semantics of an Annotation Type. 1288 * 1289 * <p><b>This is NOT part of any supported API. 1290 * If you write code that depends on this, you do so at your own risk. 1291 * This code and its internal interfaces are subject to change or 1292 * deletion without notice.</b> 1293 */ 1294 public static class AnnotationTypeMetadata { 1295 final ClassSymbol metaDataFor; 1296 private Compound target; 1297 private Compound repeatable; 1298 private AnnotationTypeCompleter annotationTypeCompleter; 1299 1300 public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { 1301 this.metaDataFor = metaDataFor; 1302 this.annotationTypeCompleter = annotationTypeCompleter; 1303 } 1304 1305 private void init() { 1306 // Make sure metaDataFor is member entered 1307 while (!metaDataFor.isCompleted()) 1308 metaDataFor.complete(); 1309 1310 if (annotationTypeCompleter != null) { 1311 AnnotationTypeCompleter c = annotationTypeCompleter; 1312 annotationTypeCompleter = null; 1313 c.complete(metaDataFor); 1314 } 1315 } 1316 1317 public void complete() { 1318 init(); 1319 } 1320 1321 public Compound getRepeatable() { 1322 init(); 1323 return repeatable; 1324 } 1325 1326 public void setRepeatable(Compound repeatable) { 1327 Assert.checkNull(this.repeatable); 1328 this.repeatable = repeatable; 1329 } 1330 1331 public Compound getTarget() { 1332 init(); 1333 return target; 1334 } 1335 1336 public void setTarget(Compound target) { 1337 Assert.checkNull(this.target); 1338 this.target = target; 1339 } 1340 1341 public Set<MethodSymbol> getAnnotationElements() { 1342 init(); 1343 Set<MethodSymbol> members = new LinkedHashSet<>(); 1344 WriteableScope s = metaDataFor.members(); 1345 Iterable<Symbol> ss = s.getSymbols(NON_RECURSIVE); 1346 for (Symbol sym : ss) 1347 if (sym.kind == MTH && 1348 sym.name != sym.name.table.names.clinit && 1349 (sym.flags() & SYNTHETIC) == 0) 1350 members.add((MethodSymbol)sym); 1351 return members; 1352 } 1353 1354 public Set<MethodSymbol> getAnnotationElementsWithDefault() { 1355 init(); 1356 Set<MethodSymbol> members = getAnnotationElements(); 1357 Set<MethodSymbol> res = new LinkedHashSet<>(); 1358 for (MethodSymbol m : members) 1359 if (m.defaultValue != null) 1360 res.add(m); 1361 return res; 1362 } 1363 1364 @Override 1365 public String toString() { 1366 return "Annotation type for: " + metaDataFor; 1367 } 1368 1369 public boolean isMetadataForAnnotationType() { return true; } 1370 1371 public static AnnotationTypeMetadata notAnAnnotationType() { 1372 return NOT_AN_ANNOTATION_TYPE; 1373 } 1374 1375 private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = 1376 new AnnotationTypeMetadata(null, null) { 1377 @Override 1378 public void complete() { 1379 } // do nothing 1380 1381 @Override 1382 public String toString() { 1383 return "Not an annotation type"; 1384 } 1385 1386 @Override 1387 public Set<MethodSymbol> getAnnotationElements() { 1388 return new LinkedHashSet<>(0); 1389 } 1390 1391 @Override 1392 public Set<MethodSymbol> getAnnotationElementsWithDefault() { 1393 return new LinkedHashSet<>(0); 1394 } 1395 1396 @Override 1397 public boolean isMetadataForAnnotationType() { 1398 return false; 1399 } 1400 1401 @Override 1402 public Compound getTarget() { 1403 return null; 1404 } 1405 1406 @Override 1407 public Compound getRepeatable() { 1408 return null; 1409 } 1410 }; 1411 } 1412 1413 public void newRound() { 1414 blockCount = 1; 1415 } 1416 1417 public Queues setQueues(Queues nue) { 1418 Queues stored = new Queues(q, validateQ, typesQ, afterTypesQ); 1419 this.q = nue.q; 1420 this.typesQ = nue.typesQ; 1421 this.afterTypesQ = nue.afterTypesQ; 1422 this.validateQ = nue.validateQ; 1423 return stored; 1424 } 1425 1426 static class Queues { 1427 private final ListBuffer<Runnable> q; 1428 private final ListBuffer<Runnable> validateQ; 1429 private final ListBuffer<Runnable> typesQ; 1430 private final ListBuffer<Runnable> afterTypesQ; 1431 1432 public Queues() { 1433 this(new ListBuffer<Runnable>(), new ListBuffer<Runnable>(), new ListBuffer<Runnable>(), new ListBuffer<Runnable>()); 1434 } 1435 1436 public Queues(ListBuffer<Runnable> q, ListBuffer<Runnable> validateQ, ListBuffer<Runnable> typesQ, ListBuffer<Runnable> afterTypesQ) { 1437 this.q = q; 1438 this.validateQ = validateQ; 1439 this.typesQ = typesQ; 1440 this.afterTypesQ = afterTypesQ; 1441 } 1442 } 1443 }