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