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