1 /* 2 * Copyright (c) 1999, 2023, 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.jvm; 27 28 import java.io.*; 29 import java.net.URI; 30 import java.net.URISyntaxException; 31 import java.nio.CharBuffer; 32 import java.nio.file.ClosedFileSystemException; 33 import java.util.Arrays; 34 import java.util.EnumSet; 35 import java.util.HashMap; 36 import java.util.HashSet; 37 import java.util.Map; 38 import java.util.Set; 39 import java.util.function.IntFunction; 40 import java.util.function.Predicate; 41 import java.util.stream.IntStream; 42 43 import javax.lang.model.element.Modifier; 44 import javax.lang.model.element.NestingKind; 45 import javax.tools.JavaFileManager; 46 import javax.tools.JavaFileObject; 47 48 import com.sun.tools.javac.code.Source; 49 import com.sun.tools.javac.code.Source.Feature; 50 import com.sun.tools.javac.comp.Annotate; 51 import com.sun.tools.javac.comp.Annotate.AnnotationTypeCompleter; 52 import com.sun.tools.javac.code.*; 53 import com.sun.tools.javac.code.Directive.*; 54 import com.sun.tools.javac.code.Lint.LintCategory; 55 import com.sun.tools.javac.code.Scope.WriteableScope; 56 import com.sun.tools.javac.code.Symbol.*; 57 import com.sun.tools.javac.code.Symtab; 58 import com.sun.tools.javac.code.Type.*; 59 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata; 60 import com.sun.tools.javac.file.BaseFileManager; 61 import com.sun.tools.javac.file.PathFileObject; 62 import com.sun.tools.javac.jvm.ClassFile.Version; 63 import com.sun.tools.javac.jvm.PoolConstant.NameAndType; 64 import com.sun.tools.javac.main.Option; 65 import com.sun.tools.javac.resources.CompilerProperties.Errors; 66 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 67 import com.sun.tools.javac.resources.CompilerProperties.Warnings; 68 import com.sun.tools.javac.util.*; 69 import com.sun.tools.javac.util.ByteBuffer.UnderflowException; 70 import com.sun.tools.javac.util.DefinedBy.Api; 71 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 72 import com.sun.tools.javac.util.JCDiagnostic.Fragment; 73 74 import static com.sun.tools.javac.code.Flags.*; 75 import static com.sun.tools.javac.code.Kinds.Kind.*; 76 77 import com.sun.tools.javac.code.Scope.LookupKind; 78 79 import static com.sun.tools.javac.code.TypeTag.ARRAY; 80 import static com.sun.tools.javac.code.TypeTag.CLASS; 81 import static com.sun.tools.javac.code.TypeTag.TYPEVAR; 82 import static com.sun.tools.javac.jvm.ClassFile.*; 83 import static com.sun.tools.javac.jvm.ClassFile.Version.*; 84 85 import static com.sun.tools.javac.main.Option.PARAMETERS; 86 87 /** This class provides operations to read a classfile into an internal 88 * representation. The internal representation is anchored in a 89 * ClassSymbol which contains in its scope symbol representations 90 * for all other definitions in the classfile. Top-level Classes themselves 91 * appear as members of the scopes of PackageSymbols. 92 * 93 * <p><b>This is NOT part of any supported API. 94 * If you write code that depends on this, you do so at your own risk. 95 * This code and its internal interfaces are subject to change or 96 * deletion without notice.</b> 97 */ 98 public class ClassReader { 99 /** The context key for the class reader. */ 100 protected static final Context.Key<ClassReader> classReaderKey = new Context.Key<>(); 101 102 public static final int INITIAL_BUFFER_SIZE = 0x0fff0; 103 104 private final Annotate annotate; 105 106 /** Switch: verbose output. 107 */ 108 boolean verbose; 109 110 /** Switch: allow modules. 111 */ 112 boolean allowModules; 113 114 /** Switch: allow sealed 115 */ 116 boolean allowSealedTypes; 117 118 /** Switch: allow records 119 */ 120 boolean allowRecords; 121 122 /** Lint option: warn about classfile issues 123 */ 124 boolean lintClassfile; 125 126 /** Switch: warn (instead of error) on illegal UTF-8 127 */ 128 boolean warnOnIllegalUtf8; 129 130 /** Switch: preserve parameter names from the variable table. 131 */ 132 public boolean saveParameterNames; 133 134 /** 135 * The currently selected profile. 136 */ 137 public final Profile profile; 138 139 /** The log to use for verbose output 140 */ 141 final Log log; 142 143 /** The symbol table. */ 144 Symtab syms; 145 146 Types types; 147 148 /** The name table. */ 149 final Names names; 150 151 /** Access to files 152 */ 153 private final JavaFileManager fileManager; 154 155 /** Factory for diagnostics 156 */ 157 JCDiagnostic.Factory diagFactory; 158 159 DeferredCompletionFailureHandler dcfh; 160 161 /** 162 * Support for preview language features. 163 */ 164 Preview preview; 165 166 /** The current scope where type variables are entered. 167 */ 168 protected WriteableScope typevars; 169 170 private List<InterimUsesDirective> interimUses = List.nil(); 171 private List<InterimProvidesDirective> interimProvides = List.nil(); 172 173 /** The path name of the class file currently being read. 174 */ 175 protected JavaFileObject currentClassFile = null; 176 177 /** The class or method currently being read. 178 */ 179 protected Symbol currentOwner = null; 180 181 /** The module containing the class currently being read. 182 */ 183 protected ModuleSymbol currentModule = null; 184 185 /** The buffer containing the currently read class file. 186 */ 187 ByteBuffer buf = new ByteBuffer(INITIAL_BUFFER_SIZE); 188 189 /** The current input pointer. 190 */ 191 protected int bp; 192 193 /** The pool reader. 194 */ 195 PoolReader poolReader; 196 197 /** The major version number of the class file being read. */ 198 int majorVersion; 199 /** The minor version number of the class file being read. */ 200 int minorVersion; 201 202 /** UTF-8 validation level */ 203 Convert.Validation utf8validation; 204 205 /** A table to hold the constant pool indices for method parameter 206 * names, as given in LocalVariableTable attributes. 207 */ 208 int[] parameterNameIndicesLvt; 209 210 /** 211 * A table to hold the constant pool indices for method parameter 212 * names, as given in the MethodParameters attribute. 213 */ 214 int[] parameterNameIndicesMp; 215 216 /** 217 * A table to hold the access flags of the method parameters. 218 */ 219 int[] parameterAccessFlags; 220 221 /** 222 * A table to hold annotations for method parameters. 223 */ 224 ParameterAnnotations[] parameterAnnotations; 225 226 /** 227 * A holder for parameter annotations. 228 */ 229 static class ParameterAnnotations { 230 List<CompoundAnnotationProxy> proxies; 231 232 void add(List<CompoundAnnotationProxy> newAnnotations) { 233 if (proxies == null) { 234 proxies = newAnnotations; 235 } else { 236 proxies = proxies.prependList(newAnnotations); 237 } 238 } 239 } 240 241 /** 242 * The set of attribute names for which warnings have been generated for the current class 243 */ 244 Set<Name> warnedAttrs = new HashSet<>(); 245 246 /** 247 * The prototype @Target Attribute.Compound if this class is an annotation annotated with 248 * {@code @Target} 249 */ 250 CompoundAnnotationProxy target; 251 252 /** 253 * The prototype @Repeatable Attribute.Compound if this class is an annotation annotated with 254 * {@code @Repeatable} 255 */ 256 CompoundAnnotationProxy repeatable; 257 258 /** Get the ClassReader instance for this invocation. */ 259 public static ClassReader instance(Context context) { 260 ClassReader instance = context.get(classReaderKey); 261 if (instance == null) 262 instance = new ClassReader(context); 263 return instance; 264 } 265 266 /** Construct a new class reader. */ 267 @SuppressWarnings("this-escape") 268 protected ClassReader(Context context) { 269 context.put(classReaderKey, this); 270 annotate = Annotate.instance(context); 271 names = Names.instance(context); 272 syms = Symtab.instance(context); 273 types = Types.instance(context); 274 fileManager = context.get(JavaFileManager.class); 275 if (fileManager == null) 276 throw new AssertionError("FileManager initialization error"); 277 diagFactory = JCDiagnostic.Factory.instance(context); 278 dcfh = DeferredCompletionFailureHandler.instance(context); 279 280 log = Log.instance(context); 281 282 Options options = Options.instance(context); 283 verbose = options.isSet(Option.VERBOSE); 284 285 Source source = Source.instance(context); 286 preview = Preview.instance(context); 287 allowModules = Feature.MODULES.allowedInSource(source); 288 allowRecords = Feature.RECORDS.allowedInSource(source); 289 allowSealedTypes = Feature.SEALED_CLASSES.allowedInSource(source); 290 warnOnIllegalUtf8 = Feature.WARN_ON_ILLEGAL_UTF8.allowedInSource(source); 291 292 saveParameterNames = options.isSet(PARAMETERS); 293 294 profile = Profile.instance(context); 295 296 typevars = WriteableScope.create(syms.noSymbol); 297 298 lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE); 299 300 initAttributeReaders(); 301 } 302 303 /** Add member to class unless it is synthetic. 304 */ 305 private void enterMember(ClassSymbol c, Symbol sym) { 306 // Synthetic members are not entered -- reason lost to history (optimization?). 307 // Lambda methods must be entered because they may have inner classes (which reference them) 308 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda)) 309 c.members_field.enter(sym); 310 } 311 312 /* ********************************************************************** 313 * Error Diagnoses 314 ***********************************************************************/ 315 316 public ClassFinder.BadClassFile badClassFile(String key, Object... args) { 317 return badClassFile(diagFactory.fragment(key, args)); 318 } 319 320 public ClassFinder.BadClassFile badClassFile(Fragment fragment) { 321 return badClassFile(diagFactory.fragment(fragment)); 322 } 323 324 public ClassFinder.BadClassFile badClassFile(JCDiagnostic diagnostic) { 325 return new ClassFinder.BadClassFile ( 326 currentOwner.enclClass(), 327 currentClassFile, 328 diagnostic, 329 diagFactory, 330 dcfh); 331 } 332 333 public ClassFinder.BadEnclosingMethodAttr badEnclosingMethod(Symbol sym) { 334 return new ClassFinder.BadEnclosingMethodAttr ( 335 currentOwner.enclClass(), 336 currentClassFile, 337 diagFactory.fragment(Fragments.BadEnclosingMethod(sym)), 338 diagFactory, 339 dcfh); 340 } 341 342 /* ********************************************************************** 343 * Buffer Access 344 ***********************************************************************/ 345 346 /** Read a character. 347 */ 348 char nextChar() { 349 char res; 350 try { 351 res = buf.getChar(bp); 352 } catch (UnderflowException e) { 353 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 354 } 355 bp += 2; 356 return res; 357 } 358 359 /** Read a byte. 360 */ 361 int nextByte() { 362 try { 363 return buf.getByte(bp++) & 0xFF; 364 } catch (UnderflowException e) { 365 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 366 } 367 } 368 369 /** Read an integer. 370 */ 371 int nextInt() { 372 int res; 373 try { 374 res = buf.getInt(bp); 375 } catch (UnderflowException e) { 376 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 377 } 378 bp += 4; 379 return res; 380 } 381 382 /* ********************************************************************** 383 * Constant Pool Access 384 ***********************************************************************/ 385 386 /** Read module_flags. 387 */ 388 Set<ModuleFlags> readModuleFlags(int flags) { 389 Set<ModuleFlags> set = EnumSet.noneOf(ModuleFlags.class); 390 for (ModuleFlags f : ModuleFlags.values()) { 391 if ((flags & f.value) != 0) 392 set.add(f); 393 } 394 return set; 395 } 396 397 /** Read resolution_flags. 398 */ 399 Set<ModuleResolutionFlags> readModuleResolutionFlags(int flags) { 400 Set<ModuleResolutionFlags> set = EnumSet.noneOf(ModuleResolutionFlags.class); 401 for (ModuleResolutionFlags f : ModuleResolutionFlags.values()) { 402 if ((flags & f.value) != 0) 403 set.add(f); 404 } 405 return set; 406 } 407 408 /** Read exports_flags. 409 */ 410 Set<ExportsFlag> readExportsFlags(int flags) { 411 Set<ExportsFlag> set = EnumSet.noneOf(ExportsFlag.class); 412 for (ExportsFlag f: ExportsFlag.values()) { 413 if ((flags & f.value) != 0) 414 set.add(f); 415 } 416 return set; 417 } 418 419 /** Read opens_flags. 420 */ 421 Set<OpensFlag> readOpensFlags(int flags) { 422 Set<OpensFlag> set = EnumSet.noneOf(OpensFlag.class); 423 for (OpensFlag f: OpensFlag.values()) { 424 if ((flags & f.value) != 0) 425 set.add(f); 426 } 427 return set; 428 } 429 430 /** Read requires_flags. 431 */ 432 Set<RequiresFlag> readRequiresFlags(int flags) { 433 Set<RequiresFlag> set = EnumSet.noneOf(RequiresFlag.class); 434 for (RequiresFlag f: RequiresFlag.values()) { 435 if ((flags & f.value) != 0) 436 set.add(f); 437 } 438 return set; 439 } 440 441 /* ********************************************************************** 442 * Reading Types 443 ***********************************************************************/ 444 445 /** The unread portion of the currently read type is 446 * signature[sigp..siglimit-1]. 447 */ 448 byte[] signature; 449 int sigp; 450 int siglimit; 451 boolean sigEnterPhase = false; 452 453 /** Convert signature to type, where signature is a byte array segment. 454 */ 455 Type sigToType(byte[] sig, int offset, int len) { 456 signature = sig; 457 sigp = offset; 458 siglimit = offset + len; 459 return sigToType(); 460 } 461 462 /** Convert signature to type, where signature is implicit. 463 */ 464 Type sigToType() { 465 switch ((char) signature[sigp]) { 466 case 'T': 467 sigp++; 468 int start = sigp; 469 while (signature[sigp] != ';') sigp++; 470 sigp++; 471 return sigEnterPhase 472 ? Type.noType 473 : findTypeVar(readName(signature, start, sigp - 1 - start)); 474 case '+': { 475 sigp++; 476 Type t = sigToType(); 477 return new WildcardType(t, BoundKind.EXTENDS, syms.boundClass); 478 } 479 case '*': 480 sigp++; 481 return new WildcardType(syms.objectType, BoundKind.UNBOUND, 482 syms.boundClass); 483 case '-': { 484 sigp++; 485 Type t = sigToType(); 486 return new WildcardType(t, BoundKind.SUPER, syms.boundClass); 487 } 488 case 'B': 489 sigp++; 490 return syms.byteType; 491 case 'C': 492 sigp++; 493 return syms.charType; 494 case 'D': 495 sigp++; 496 return syms.doubleType; 497 case 'F': 498 sigp++; 499 return syms.floatType; 500 case 'I': 501 sigp++; 502 return syms.intType; 503 case 'J': 504 sigp++; 505 return syms.longType; 506 case 'L': 507 { 508 // int oldsigp = sigp; 509 Type t = classSigToType(); 510 if (sigp < siglimit && signature[sigp] == '.') 511 throw badClassFile("deprecated inner class signature syntax " + 512 "(please recompile from source)"); 513 /* 514 System.err.println(" decoded " + 515 new String(signature, oldsigp, sigp-oldsigp) + 516 " => " + t + " outer " + t.outer()); 517 */ 518 return t; 519 } 520 case 'S': 521 sigp++; 522 return syms.shortType; 523 case 'V': 524 sigp++; 525 return syms.voidType; 526 case 'Z': 527 sigp++; 528 return syms.booleanType; 529 case '[': 530 sigp++; 531 return new ArrayType(sigToType(), syms.arrayClass); 532 case '(': 533 sigp++; 534 List<Type> argtypes = sigToTypes(')'); 535 Type restype = sigToType(); 536 List<Type> thrown = List.nil(); 537 while (sigp < siglimit && signature[sigp] == '^') { 538 sigp++; 539 thrown = thrown.prepend(sigToType()); 540 } 541 // if there is a typevar in the throws clause we should state it. 542 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) { 543 if (l.head.hasTag(TYPEVAR)) { 544 l.head.tsym.flags_field |= THROWS; 545 } 546 } 547 return new MethodType(argtypes, 548 restype, 549 thrown.reverse(), 550 syms.methodClass); 551 case '<': 552 typevars = typevars.dup(currentOwner); 553 Type poly = new ForAll(sigToTypeParams(), sigToType()); 554 typevars = typevars.leave(); 555 return poly; 556 default: 557 throw badClassFile("bad.signature", quoteBadSignature()); 558 } 559 } 560 561 byte[] signatureBuffer = new byte[0]; 562 int sbp = 0; 563 /** Convert class signature to type, where signature is implicit. 564 */ 565 Type classSigToType() { 566 if (signature[sigp] != 'L') 567 throw badClassFile("bad.class.signature", quoteBadSignature()); 568 sigp++; 569 Type outer = Type.noType; 570 int startSbp = sbp; 571 572 while (true) { 573 final byte c = signature[sigp++]; 574 switch (c) { 575 576 case ';': { // end 577 ClassSymbol t = enterClass(readName(signatureBuffer, 578 startSbp, 579 sbp - startSbp)); 580 581 try { 582 return (outer == Type.noType) ? 583 t.erasure(types) : 584 new ClassType(outer, List.nil(), t); 585 } finally { 586 sbp = startSbp; 587 } 588 } 589 590 case '<': // generic arguments 591 ClassSymbol t = enterClass(readName(signatureBuffer, 592 startSbp, 593 sbp - startSbp)); 594 List<Type> actuals = sigToTypes('>'); 595 List<Type> formals = ((ClassType)t.type.tsym.type).typarams_field; 596 if (formals != null) { 597 if (actuals.isEmpty()) 598 actuals = formals; 599 } 600 /* actualsCp is final as it will be captured by the inner class below. We could avoid defining 601 * this additional local variable and depend on field ClassType::typarams_field which `actuals` is 602 * assigned to but then we would have a dependendy on the internal representation of ClassType which 603 * could change in the future 604 */ 605 final List<Type> actualsCp = actuals; 606 outer = new ClassType(outer, actuals, t) { 607 boolean completed = false; 608 boolean typeArgsSet = false; 609 @Override @DefinedBy(Api.LANGUAGE_MODEL) 610 public Type getEnclosingType() { 611 if (!completed) { 612 completed = true; 613 tsym.apiComplete(); 614 Type enclosingType = tsym.type.getEnclosingType(); 615 if (enclosingType != Type.noType) { 616 List<Type> typeArgs = 617 super.getEnclosingType().allparams(); 618 List<Type> typeParams = 619 enclosingType.allparams(); 620 if (typeParams.length() != typeArgs.length()) { 621 // no "rare" types 622 super.setEnclosingType(types.erasure(enclosingType)); 623 } else { 624 super.setEnclosingType(types.subst(enclosingType, 625 typeParams, 626 typeArgs)); 627 } 628 } else { 629 super.setEnclosingType(Type.noType); 630 } 631 } 632 return super.getEnclosingType(); 633 } 634 @Override 635 public void setEnclosingType(Type outer) { 636 throw new UnsupportedOperationException(); 637 } 638 639 @Override 640 public List<Type> getTypeArguments() { 641 if (!typeArgsSet) { 642 typeArgsSet = true; 643 List<Type> formalsCp = ((ClassType)t.type.tsym.type).typarams_field; 644 if (formalsCp != null && !formalsCp.isEmpty()) { 645 if (actualsCp.length() == formalsCp.length()) { 646 List<Type> a = actualsCp; 647 List<Type> f = formalsCp; 648 while (a.nonEmpty()) { 649 a.head = a.head.withTypeVar(f.head); 650 a = a.tail; 651 f = f.tail; 652 } 653 } 654 } 655 } 656 return super.getTypeArguments(); 657 } 658 }; 659 switch (signature[sigp++]) { 660 case ';': 661 if (sigp < siglimit && signature[sigp] == '.') { 662 // support old-style GJC signatures 663 // The signature produced was 664 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>; 665 // rather than say 666 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>; 667 // so we skip past ".Lfoo/Outer$" 668 sigp += (sbp - startSbp) + // "foo/Outer" 669 3; // ".L" and "$" 670 signatureBuffer[sbp++] = (byte)'$'; 671 break; 672 } else { 673 sbp = startSbp; 674 return outer; 675 } 676 case '.': 677 signatureBuffer[sbp++] = (byte)'$'; 678 break; 679 default: 680 throw new AssertionError(signature[sigp-1]); 681 } 682 continue; 683 684 case '.': 685 //we have seen an enclosing non-generic class 686 if (outer != Type.noType) { 687 t = enterClass(readName(signatureBuffer, 688 startSbp, 689 sbp - startSbp)); 690 outer = new ClassType(outer, List.nil(), t); 691 } 692 signatureBuffer[sbp++] = (byte)'$'; 693 continue; 694 case '/': 695 signatureBuffer[sbp++] = (byte)'.'; 696 continue; 697 default: 698 signatureBuffer[sbp++] = c; 699 continue; 700 } 701 } 702 } 703 704 /** Quote a bogus signature for display inside an error message. 705 */ 706 String quoteBadSignature() { 707 String sigString; 708 try { 709 sigString = Convert.utf2string(signature, sigp, siglimit - sigp, Convert.Validation.NONE); 710 } catch (InvalidUtfException e) { 711 throw new AssertionError(e); 712 } 713 if (sigString.length() > 32) 714 sigString = sigString.substring(0, 32) + "..."; 715 return "\"" + sigString + "\""; 716 } 717 718 /** Convert (implicit) signature to list of types 719 * until `terminator' is encountered. 720 */ 721 List<Type> sigToTypes(char terminator) { 722 List<Type> head = List.of(null); 723 List<Type> tail = head; 724 while (signature[sigp] != terminator) 725 tail = tail.setTail(List.of(sigToType())); 726 sigp++; 727 return head.tail; 728 } 729 730 /** Convert signature to type parameters, where signature is a byte 731 * array segment. 732 */ 733 List<Type> sigToTypeParams(byte[] sig, int offset, int len) { 734 signature = sig; 735 sigp = offset; 736 siglimit = offset + len; 737 return sigToTypeParams(); 738 } 739 740 /** Convert signature to type parameters, where signature is implicit. 741 */ 742 List<Type> sigToTypeParams() { 743 List<Type> tvars = List.nil(); 744 if (signature[sigp] == '<') { 745 sigp++; 746 int start = sigp; 747 sigEnterPhase = true; 748 while (signature[sigp] != '>') 749 tvars = tvars.prepend(sigToTypeParam()); 750 sigEnterPhase = false; 751 sigp = start; 752 while (signature[sigp] != '>') 753 sigToTypeParam(); 754 sigp++; 755 } 756 return tvars.reverse(); 757 } 758 759 /** Convert (implicit) signature to type parameter. 760 */ 761 Type sigToTypeParam() { 762 int start = sigp; 763 while (signature[sigp] != ':') sigp++; 764 Name name = readName(signature, start, sigp - start); 765 TypeVar tvar; 766 if (sigEnterPhase) { 767 tvar = new TypeVar(name, currentOwner, syms.botType); 768 typevars.enter(tvar.tsym); 769 } else { 770 tvar = (TypeVar)findTypeVar(name); 771 } 772 List<Type> bounds = List.nil(); 773 boolean allInterfaces = false; 774 if (signature[sigp] == ':' && signature[sigp+1] == ':') { 775 sigp++; 776 allInterfaces = true; 777 } 778 while (signature[sigp] == ':') { 779 sigp++; 780 bounds = bounds.prepend(sigToType()); 781 } 782 if (!sigEnterPhase) { 783 types.setBounds(tvar, bounds.reverse(), allInterfaces); 784 } 785 return tvar; 786 } 787 788 /** Find type variable with given name in `typevars' scope. 789 */ 790 Type findTypeVar(Name name) { 791 Symbol s = typevars.findFirst(name); 792 if (s != null) { 793 return s.type; 794 } else { 795 if (readingClassAttr) { 796 // While reading the class attribute, the supertypes 797 // might refer to a type variable from an enclosing element 798 // (method or class). 799 // If the type variable is defined in the enclosing class, 800 // we can actually find it in 801 // currentOwner.owner.type.getTypeArguments() 802 // However, until we have read the enclosing method attribute 803 // we don't know for sure if this owner is correct. It could 804 // be a method and there is no way to tell before reading the 805 // enclosing method attribute. 806 TypeVar t = new TypeVar(name, currentOwner, syms.botType); 807 missingTypeVariables = missingTypeVariables.prepend(t); 808 // System.err.println("Missing type var " + name); 809 return t; 810 } 811 throw badClassFile("undecl.type.var", name); 812 } 813 } 814 815 private Name readName(byte[] buf, int off, int len) { 816 try { 817 return names.fromUtf(buf, off, len, utf8validation); 818 } catch (InvalidUtfException e) { 819 if (warnOnIllegalUtf8) { 820 log.warning(Warnings.InvalidUtf8InClassfile(currentClassFile, 821 Fragments.BadUtf8ByteSequenceAt(sigp))); 822 return names.fromUtfLax(buf, off, len); 823 } 824 throw badClassFile(Fragments.BadUtf8ByteSequenceAt(sigp)); 825 } 826 } 827 828 /* ********************************************************************** 829 * Reading Attributes 830 ***********************************************************************/ 831 832 protected enum AttributeKind { CLASS, MEMBER } 833 834 protected abstract class AttributeReader { 835 protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) { 836 this.name = name; 837 this.version = version; 838 this.kinds = kinds; 839 } 840 841 protected boolean accepts(AttributeKind kind) { 842 if (kinds.contains(kind)) { 843 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor)) 844 return true; 845 846 if (lintClassfile && !warnedAttrs.contains(name)) { 847 JavaFileObject prev = log.useSource(currentClassFile); 848 try { 849 log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, 850 Warnings.FutureAttr(name, version.major, version.minor, majorVersion, minorVersion)); 851 } finally { 852 log.useSource(prev); 853 } 854 warnedAttrs.add(name); 855 } 856 } 857 return false; 858 } 859 860 protected abstract void read(Symbol sym, int attrLen); 861 862 protected final Name name; 863 protected final ClassFile.Version version; 864 protected final Set<AttributeKind> kinds; 865 } 866 867 protected Set<AttributeKind> CLASS_ATTRIBUTE = 868 EnumSet.of(AttributeKind.CLASS); 869 protected Set<AttributeKind> MEMBER_ATTRIBUTE = 870 EnumSet.of(AttributeKind.MEMBER); 871 protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE = 872 EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER); 873 874 protected Map<Name, AttributeReader> attributeReaders = new HashMap<>(); 875 876 private void initAttributeReaders() { 877 AttributeReader[] readers = { 878 // v45.3 attributes 879 880 new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) { 881 protected void read(Symbol sym, int attrLen) { 882 if (saveParameterNames) 883 ((MethodSymbol)sym).code = readCode(sym); 884 else 885 bp = bp + attrLen; 886 } 887 }, 888 889 new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) { 890 protected void read(Symbol sym, int attrLen) { 891 Object v = poolReader.getConstant(nextChar()); 892 // Ignore ConstantValue attribute if field not final. 893 if ((sym.flags() & FINAL) == 0) { 894 return; 895 } 896 VarSymbol var = (VarSymbol) sym; 897 switch (var.type.getTag()) { 898 case BOOLEAN: 899 case BYTE: 900 case CHAR: 901 case SHORT: 902 case INT: 903 checkType(var, Integer.class, v); 904 break; 905 case LONG: 906 checkType(var, Long.class, v); 907 break; 908 case FLOAT: 909 checkType(var, Float.class, v); 910 break; 911 case DOUBLE: 912 checkType(var, Double.class, v); 913 break; 914 case CLASS: 915 if (var.type.tsym == syms.stringType.tsym) { 916 checkType(var, String.class, v); 917 } else { 918 throw badClassFile("bad.constant.value.type", var.type); 919 } 920 break; 921 default: 922 // ignore ConstantValue attribute if type is not primitive or String 923 return; 924 } 925 if (v instanceof Integer intVal && !var.type.getTag().checkRange(intVal)) { 926 throw badClassFile("bad.constant.range", v, var, var.type); 927 } 928 var.setData(v); 929 } 930 931 void checkType(Symbol var, Class<?> clazz, Object value) { 932 if (!clazz.isInstance(value)) { 933 throw badClassFile("bad.constant.value", value, var, clazz.getSimpleName()); 934 } 935 } 936 }, 937 938 new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 939 protected void read(Symbol sym, int attrLen) { 940 Symbol s = sym.owner.kind == MDL ? sym.owner : sym; 941 942 s.flags_field |= DEPRECATED; 943 } 944 }, 945 946 new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 947 protected void read(Symbol sym, int attrLen) { 948 int nexceptions = nextChar(); 949 List<Type> thrown = List.nil(); 950 for (int j = 0; j < nexceptions; j++) 951 thrown = thrown.prepend(poolReader.getClass(nextChar()).type); 952 if (sym.type.getThrownTypes().isEmpty()) 953 sym.type.asMethodType().thrown = thrown.reverse(); 954 } 955 }, 956 957 new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) { 958 protected void read(Symbol sym, int attrLen) { 959 ClassSymbol c = (ClassSymbol) sym; 960 if (currentModule.module_info == c) { 961 //prevent entering the classes too soon: 962 skipInnerClasses(); 963 } else { 964 readInnerClasses(c); 965 } 966 } 967 }, 968 969 new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 970 protected void read(Symbol sym, int attrLen) { 971 int newbp = bp + attrLen; 972 if (saveParameterNames) { 973 // Pick up parameter names from the variable table. 974 // Parameter names are not explicitly identified as such, 975 // but all parameter name entries in the LocalVariableTable 976 // have a start_pc of 0. Therefore, we record the name 977 // indices of all slots with a start_pc of zero in the 978 // parameterNameIndices array. 979 // Note that this implicitly honors the JVMS spec that 980 // there may be more than one LocalVariableTable, and that 981 // there is no specified ordering for the entries. 982 int numEntries = nextChar(); 983 for (int i = 0; i < numEntries; i++) { 984 int start_pc = nextChar(); 985 int length = nextChar(); 986 int nameIndex = nextChar(); 987 int sigIndex = nextChar(); 988 int register = nextChar(); 989 if (start_pc == 0) { 990 // ensure array large enough 991 if (register >= parameterNameIndicesLvt.length) { 992 int newSize = 993 Math.max(register + 1, parameterNameIndicesLvt.length + 8); 994 parameterNameIndicesLvt = 995 Arrays.copyOf(parameterNameIndicesLvt, newSize); 996 } 997 parameterNameIndicesLvt[register] = nameIndex; 998 } 999 } 1000 } 1001 bp = newbp; 1002 } 1003 }, 1004 1005 new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) { 1006 protected void read(Symbol sym, int attrLen) { 1007 ClassSymbol c = (ClassSymbol) sym; 1008 Name n = poolReader.getName(nextChar()); 1009 c.sourcefile = new SourceFileObject(n); 1010 // If the class is a toplevel class, originating from a Java source file, 1011 // but the class name does not match the file name, then it is 1012 // an auxiliary class. 1013 String sn = n.toString(); 1014 if (c.owner.kind == PCK && 1015 sn.endsWith(".java") && 1016 !sn.equals(c.name.toString()+".java")) { 1017 c.flags_field |= AUXILIARY; 1018 } 1019 } 1020 }, 1021 1022 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 1023 protected void read(Symbol sym, int attrLen) { 1024 sym.flags_field |= SYNTHETIC; 1025 } 1026 }, 1027 1028 // standard v49 attributes 1029 1030 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) { 1031 protected void read(Symbol sym, int attrLen) { 1032 int newbp = bp + attrLen; 1033 readEnclosingMethodAttr(sym); 1034 bp = newbp; 1035 } 1036 }, 1037 1038 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1039 protected void read(Symbol sym, int attrLen) { 1040 if (sym.kind == TYP) { 1041 ClassSymbol c = (ClassSymbol) sym; 1042 readingClassAttr = true; 1043 try { 1044 ClassType ct1 = (ClassType)c.type; 1045 Assert.check(c == currentOwner); 1046 ct1.typarams_field = poolReader.getName(nextChar()) 1047 .map(ClassReader.this::sigToTypeParams); 1048 ct1.supertype_field = sigToType(); 1049 ListBuffer<Type> is = new ListBuffer<>(); 1050 while (sigp != siglimit) is.append(sigToType()); 1051 ct1.interfaces_field = is.toList(); 1052 } finally { 1053 readingClassAttr = false; 1054 } 1055 } else { 1056 List<Type> thrown = sym.type.getThrownTypes(); 1057 sym.type = poolReader.getType(nextChar()); 1058 //- System.err.println(" # " + sym.type); 1059 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty()) 1060 sym.type.asMethodType().thrown = thrown; 1061 1062 } 1063 } 1064 }, 1065 1066 // v49 annotation attributes 1067 1068 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1069 protected void read(Symbol sym, int attrLen) { 1070 attachAnnotationDefault(sym); 1071 } 1072 }, 1073 1074 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1075 protected void read(Symbol sym, int attrLen) { 1076 attachAnnotations(sym); 1077 } 1078 }, 1079 1080 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1081 protected void read(Symbol sym, int attrLen) { 1082 readParameterAnnotations(sym); 1083 } 1084 }, 1085 1086 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1087 protected void read(Symbol sym, int attrLen) { 1088 attachAnnotations(sym); 1089 } 1090 }, 1091 1092 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1093 protected void read(Symbol sym, int attrLen) { 1094 readParameterAnnotations(sym); 1095 } 1096 }, 1097 1098 // additional "legacy" v49 attributes, superseded by flags 1099 1100 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1101 protected void read(Symbol sym, int attrLen) { 1102 sym.flags_field |= ANNOTATION; 1103 } 1104 }, 1105 1106 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) { 1107 protected void read(Symbol sym, int attrLen) { 1108 sym.flags_field |= BRIDGE; 1109 } 1110 }, 1111 1112 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1113 protected void read(Symbol sym, int attrLen) { 1114 sym.flags_field |= ENUM; 1115 } 1116 }, 1117 1118 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1119 protected void read(Symbol sym, int attrLen) { 1120 sym.flags_field |= VARARGS; 1121 } 1122 }, 1123 1124 new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) { 1125 protected void read(Symbol sym, int attrLen) { 1126 attachTypeAnnotations(sym); 1127 } 1128 }, 1129 1130 new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) { 1131 protected void read(Symbol sym, int attrLen) { 1132 attachTypeAnnotations(sym); 1133 } 1134 }, 1135 1136 // The following attributes for a Code attribute are not currently handled 1137 // StackMapTable 1138 // SourceDebugExtension 1139 // LineNumberTable 1140 // LocalVariableTypeTable 1141 1142 // standard v52 attributes 1143 1144 new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) { 1145 protected void read(Symbol sym, int attrlen) { 1146 int newbp = bp + attrlen; 1147 if (saveParameterNames) { 1148 int numEntries = nextByte(); 1149 parameterNameIndicesMp = new int[numEntries]; 1150 parameterAccessFlags = new int[numEntries]; 1151 int index = 0; 1152 for (int i = 0; i < numEntries; i++) { 1153 int nameIndex = nextChar(); 1154 int flags = nextChar(); 1155 if ((flags & (Flags.MANDATED | Flags.SYNTHETIC)) != 0) { 1156 continue; 1157 } 1158 parameterNameIndicesMp[index] = nameIndex; 1159 parameterAccessFlags[index] = flags; 1160 index++; 1161 } 1162 } 1163 bp = newbp; 1164 } 1165 }, 1166 1167 // standard v53 attributes 1168 1169 new AttributeReader(names.Module, V53, CLASS_ATTRIBUTE) { 1170 @Override 1171 protected boolean accepts(AttributeKind kind) { 1172 return super.accepts(kind) && allowModules; 1173 } 1174 protected void read(Symbol sym, int attrLen) { 1175 if (sym.kind == TYP && sym.owner.kind == MDL) { 1176 ModuleSymbol msym = (ModuleSymbol) sym.owner; 1177 ListBuffer<Directive> directives = new ListBuffer<>(); 1178 1179 Name moduleName = poolReader.peekModuleName(nextChar(), ClassReader.this::readName); 1180 if (currentModule.name != moduleName) { 1181 throw badClassFile("module.name.mismatch", moduleName, currentModule.name); 1182 } 1183 1184 Set<ModuleFlags> moduleFlags = readModuleFlags(nextChar()); 1185 msym.flags.addAll(moduleFlags); 1186 msym.version = optPoolEntry(nextChar(), poolReader::getName, null); 1187 1188 ListBuffer<RequiresDirective> requires = new ListBuffer<>(); 1189 int nrequires = nextChar(); 1190 for (int i = 0; i < nrequires; i++) { 1191 ModuleSymbol rsym = poolReader.getModule(nextChar()); 1192 Set<RequiresFlag> flags = readRequiresFlags(nextChar()); 1193 if (rsym == syms.java_base && majorVersion >= V54.major) { 1194 if (flags.contains(RequiresFlag.TRANSITIVE)) { 1195 throw badClassFile("bad.requires.flag", RequiresFlag.TRANSITIVE); 1196 } 1197 if (flags.contains(RequiresFlag.STATIC_PHASE)) { 1198 throw badClassFile("bad.requires.flag", RequiresFlag.STATIC_PHASE); 1199 } 1200 } 1201 nextChar(); // skip compiled version 1202 requires.add(new RequiresDirective(rsym, flags)); 1203 } 1204 msym.requires = requires.toList(); 1205 directives.addAll(msym.requires); 1206 1207 ListBuffer<ExportsDirective> exports = new ListBuffer<>(); 1208 int nexports = nextChar(); 1209 for (int i = 0; i < nexports; i++) { 1210 PackageSymbol p = poolReader.getPackage(nextChar()); 1211 Set<ExportsFlag> flags = readExportsFlags(nextChar()); 1212 int nto = nextChar(); 1213 List<ModuleSymbol> to; 1214 if (nto == 0) { 1215 to = null; 1216 } else { 1217 ListBuffer<ModuleSymbol> lb = new ListBuffer<>(); 1218 for (int t = 0; t < nto; t++) 1219 lb.append(poolReader.getModule(nextChar())); 1220 to = lb.toList(); 1221 } 1222 exports.add(new ExportsDirective(p, to, flags)); 1223 } 1224 msym.exports = exports.toList(); 1225 directives.addAll(msym.exports); 1226 ListBuffer<OpensDirective> opens = new ListBuffer<>(); 1227 int nopens = nextChar(); 1228 if (nopens != 0 && msym.flags.contains(ModuleFlags.OPEN)) { 1229 throw badClassFile("module.non.zero.opens", currentModule.name); 1230 } 1231 for (int i = 0; i < nopens; i++) { 1232 PackageSymbol p = poolReader.getPackage(nextChar()); 1233 Set<OpensFlag> flags = readOpensFlags(nextChar()); 1234 int nto = nextChar(); 1235 List<ModuleSymbol> to; 1236 if (nto == 0) { 1237 to = null; 1238 } else { 1239 ListBuffer<ModuleSymbol> lb = new ListBuffer<>(); 1240 for (int t = 0; t < nto; t++) 1241 lb.append(poolReader.getModule(nextChar())); 1242 to = lb.toList(); 1243 } 1244 opens.add(new OpensDirective(p, to, flags)); 1245 } 1246 msym.opens = opens.toList(); 1247 directives.addAll(msym.opens); 1248 1249 msym.directives = directives.toList(); 1250 1251 ListBuffer<InterimUsesDirective> uses = new ListBuffer<>(); 1252 int nuses = nextChar(); 1253 for (int i = 0; i < nuses; i++) { 1254 Name srvc = poolReader.peekClassName(nextChar(), this::classNameMapper); 1255 uses.add(new InterimUsesDirective(srvc)); 1256 } 1257 interimUses = uses.toList(); 1258 1259 ListBuffer<InterimProvidesDirective> provides = new ListBuffer<>(); 1260 int nprovides = nextChar(); 1261 for (int p = 0; p < nprovides; p++) { 1262 Name srvc = poolReader.peekClassName(nextChar(), this::classNameMapper); 1263 int nimpls = nextChar(); 1264 ListBuffer<Name> impls = new ListBuffer<>(); 1265 for (int i = 0; i < nimpls; i++) { 1266 impls.append(poolReader.peekClassName(nextChar(), this::classNameMapper)); 1267 provides.add(new InterimProvidesDirective(srvc, impls.toList())); 1268 } 1269 } 1270 interimProvides = provides.toList(); 1271 } 1272 } 1273 1274 private Name classNameMapper(byte[] arr, int offset, int length) throws InvalidUtfException { 1275 byte[] buf = ClassFile.internalize(arr, offset, length); 1276 try { 1277 return names.fromUtf(buf, 0, buf.length, utf8validation); 1278 } catch (InvalidUtfException e) { 1279 if (warnOnIllegalUtf8) { 1280 log.warning(Warnings.InvalidUtf8InClassfile(currentClassFile, 1281 Fragments.BadUtf8ByteSequenceAt(e.getOffset()))); 1282 return names.fromUtfLax(buf, 0, buf.length); 1283 } 1284 throw e; 1285 } 1286 } 1287 }, 1288 1289 new AttributeReader(names.ModuleResolution, V53, CLASS_ATTRIBUTE) { 1290 @Override 1291 protected boolean accepts(AttributeKind kind) { 1292 return super.accepts(kind) && allowModules; 1293 } 1294 protected void read(Symbol sym, int attrLen) { 1295 if (sym.kind == TYP && sym.owner.kind == MDL) { 1296 ModuleSymbol msym = (ModuleSymbol) sym.owner; 1297 msym.resolutionFlags.addAll(readModuleResolutionFlags(nextChar())); 1298 } 1299 } 1300 }, 1301 1302 new AttributeReader(names.Record, V58, CLASS_ATTRIBUTE) { 1303 @Override 1304 protected boolean accepts(AttributeKind kind) { 1305 return super.accepts(kind) && allowRecords; 1306 } 1307 protected void read(Symbol sym, int attrLen) { 1308 if (sym.kind == TYP) { 1309 sym.flags_field |= RECORD; 1310 } 1311 int componentCount = nextChar(); 1312 ListBuffer<RecordComponent> components = new ListBuffer<>(); 1313 for (int i = 0; i < componentCount; i++) { 1314 Name name = poolReader.getName(nextChar()); 1315 Type type = poolReader.getType(nextChar()); 1316 RecordComponent c = new RecordComponent(name, type, sym); 1317 readAttrs(c, AttributeKind.MEMBER); 1318 components.add(c); 1319 } 1320 ((ClassSymbol) sym).setRecordComponents(components.toList()); 1321 } 1322 }, 1323 new AttributeReader(names.PermittedSubclasses, V59, CLASS_ATTRIBUTE) { 1324 @Override 1325 protected boolean accepts(AttributeKind kind) { 1326 return super.accepts(kind) && allowSealedTypes; 1327 } 1328 protected void read(Symbol sym, int attrLen) { 1329 if (sym.kind == TYP) { 1330 ListBuffer<Symbol> subtypes = new ListBuffer<>(); 1331 int numberOfPermittedSubtypes = nextChar(); 1332 for (int i = 0; i < numberOfPermittedSubtypes; i++) { 1333 subtypes.add(poolReader.getClass(nextChar())); 1334 } 1335 ((ClassSymbol)sym).setPermittedSubclasses(subtypes.toList()); 1336 } 1337 } 1338 }, 1339 }; 1340 1341 for (AttributeReader r: readers) 1342 attributeReaders.put(r.name, r); 1343 } 1344 1345 protected void readEnclosingMethodAttr(Symbol sym) { 1346 // sym is a nested class with an "Enclosing Method" attribute 1347 // remove sym from it's current owners scope and place it in 1348 // the scope specified by the attribute 1349 sym.owner.members().remove(sym); 1350 ClassSymbol self = (ClassSymbol)sym; 1351 ClassSymbol c = poolReader.getClass(nextChar()); 1352 NameAndType nt = optPoolEntry(nextChar(), poolReader::getNameAndType, null); 1353 1354 if (c.members_field == null || c.kind != TYP) 1355 throw badClassFile("bad.enclosing.class", self, c); 1356 1357 MethodSymbol m = findMethod(nt, c.members_field, self.flags()); 1358 if (nt != null && m == null) 1359 throw badEnclosingMethod(self); 1360 1361 self.name = simpleBinaryName(self.flatname, c.flatname) ; 1362 self.owner = m != null ? m : c; 1363 if (self.name.isEmpty()) 1364 self.fullname = names.empty; 1365 else 1366 self.fullname = ClassSymbol.formFullName(self.name, self.owner); 1367 1368 if (m != null) { 1369 ((ClassType)sym.type).setEnclosingType(m.type); 1370 } else if ((self.flags_field & STATIC) == 0) { 1371 ((ClassType)sym.type).setEnclosingType(c.type); 1372 } else { 1373 ((ClassType)sym.type).setEnclosingType(Type.noType); 1374 } 1375 enterTypevars(self, self.type); 1376 if (!missingTypeVariables.isEmpty()) { 1377 ListBuffer<Type> typeVars = new ListBuffer<>(); 1378 for (Type typevar : missingTypeVariables) { 1379 typeVars.append(findTypeVar(typevar.tsym.name)); 1380 } 1381 foundTypeVariables = typeVars.toList(); 1382 } else { 1383 foundTypeVariables = List.nil(); 1384 } 1385 } 1386 1387 // See java.lang.Class 1388 private Name simpleBinaryName(Name self, Name enclosing) { 1389 if (!self.startsWith(enclosing)) { 1390 throw badClassFile("bad.enclosing.method", self); 1391 } 1392 1393 String simpleBinaryName = self.toString().substring(enclosing.toString().length()); 1394 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$') 1395 throw badClassFile("bad.enclosing.method", self); 1396 int index = 1; 1397 while (index < simpleBinaryName.length() && 1398 isAsciiDigit(simpleBinaryName.charAt(index))) 1399 index++; 1400 return names.fromString(simpleBinaryName.substring(index)); 1401 } 1402 1403 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) { 1404 if (nt == null) 1405 return null; 1406 1407 MethodType type = nt.type.asMethodType(); 1408 1409 for (Symbol sym : scope.getSymbolsByName(nt.name)) { 1410 if (sym.kind == MTH && isSameBinaryType(sym.type.asMethodType(), type)) 1411 return (MethodSymbol)sym; 1412 } 1413 1414 if (nt.name != names.init) 1415 // not a constructor 1416 return null; 1417 if ((flags & INTERFACE) != 0) 1418 // no enclosing instance 1419 return null; 1420 if (nt.type.getParameterTypes().isEmpty()) 1421 // no parameters 1422 return null; 1423 1424 // A constructor of an inner class. 1425 // Remove the first argument (the enclosing instance) 1426 nt = new NameAndType(nt.name, new MethodType(nt.type.getParameterTypes().tail, 1427 nt.type.getReturnType(), 1428 nt.type.getThrownTypes(), 1429 syms.methodClass)); 1430 // Try searching again 1431 return findMethod(nt, scope, flags); 1432 } 1433 1434 /** Similar to Types.isSameType but avoids completion */ 1435 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) { 1436 List<Type> types1 = types.erasure(mt1.getParameterTypes()) 1437 .prepend(types.erasure(mt1.getReturnType())); 1438 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType()); 1439 while (!types1.isEmpty() && !types2.isEmpty()) { 1440 if (types1.head.tsym != types2.head.tsym) 1441 return false; 1442 types1 = types1.tail; 1443 types2 = types2.tail; 1444 } 1445 return types1.isEmpty() && types2.isEmpty(); 1446 } 1447 1448 /** 1449 * Character.isDigit answers <tt>true</tt> to some non-ascii 1450 * digits. This one does not. <b>copied from java.lang.Class</b> 1451 */ 1452 private static boolean isAsciiDigit(char c) { 1453 return '0' <= c && c <= '9'; 1454 } 1455 1456 /** Read member attributes. 1457 */ 1458 void readMemberAttrs(Symbol sym) { 1459 readAttrs(sym, AttributeKind.MEMBER); 1460 } 1461 1462 void readAttrs(Symbol sym, AttributeKind kind) { 1463 char ac = nextChar(); 1464 for (int i = 0; i < ac; i++) { 1465 Name attrName = poolReader.getName(nextChar()); 1466 int attrLen = nextInt(); 1467 AttributeReader r = attributeReaders.get(attrName); 1468 if (r != null && r.accepts(kind)) 1469 r.read(sym, attrLen); 1470 else { 1471 bp = bp + attrLen; 1472 } 1473 } 1474 } 1475 1476 private boolean readingClassAttr = false; 1477 private List<Type> missingTypeVariables = List.nil(); 1478 private List<Type> foundTypeVariables = List.nil(); 1479 1480 /** Read class attributes. 1481 */ 1482 void readClassAttrs(ClassSymbol c) { 1483 readAttrs(c, AttributeKind.CLASS); 1484 } 1485 1486 /** Read code block. 1487 */ 1488 Code readCode(Symbol owner) { 1489 nextChar(); // max_stack 1490 nextChar(); // max_locals 1491 final int code_length = nextInt(); 1492 bp += code_length; 1493 final char exception_table_length = nextChar(); 1494 bp += exception_table_length * 8; 1495 readMemberAttrs(owner); 1496 return null; 1497 } 1498 1499 /* ********************************************************************** 1500 * Reading Java-language annotations 1501 ***********************************************************************/ 1502 1503 /** 1504 * Save annotations. 1505 */ 1506 List<CompoundAnnotationProxy> readAnnotations() { 1507 int numAttributes = nextChar(); 1508 ListBuffer<CompoundAnnotationProxy> annotations = new ListBuffer<>(); 1509 for (int i = 0; i < numAttributes; i++) { 1510 annotations.append(readCompoundAnnotation()); 1511 } 1512 return annotations.toList(); 1513 } 1514 1515 /** Attach annotations. 1516 */ 1517 void attachAnnotations(final Symbol sym) { 1518 attachAnnotations(sym, readAnnotations()); 1519 } 1520 1521 /** 1522 * Attach annotations. 1523 */ 1524 void attachAnnotations(final Symbol sym, List<CompoundAnnotationProxy> annotations) { 1525 if (annotations.isEmpty()) { 1526 return; 1527 } 1528 ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<>(); 1529 for (CompoundAnnotationProxy proxy : annotations) { 1530 if (proxy.type.tsym.flatName() == syms.proprietaryType.tsym.flatName()) 1531 sym.flags_field |= PROPRIETARY; 1532 else if (proxy.type.tsym.flatName() == syms.profileType.tsym.flatName()) { 1533 if (profile != Profile.DEFAULT) { 1534 for (Pair<Name, Attribute> v : proxy.values) { 1535 if (v.fst == names.value && v.snd instanceof Attribute.Constant constant) { 1536 if (constant.type == syms.intType && ((Integer) constant.value) > profile.value) { 1537 sym.flags_field |= NOT_IN_PROFILE; 1538 } 1539 } 1540 } 1541 } 1542 } else if (proxy.type.tsym.flatName() == syms.previewFeatureInternalType.tsym.flatName()) { 1543 sym.flags_field |= PREVIEW_API; 1544 setFlagIfAttributeTrue(proxy, sym, names.reflective, PREVIEW_REFLECTIVE); 1545 } else if (proxy.type.tsym.flatName() == syms.valueBasedInternalType.tsym.flatName()) { 1546 Assert.check(sym.kind == TYP); 1547 sym.flags_field |= VALUE_BASED; 1548 } else if (proxy.type.tsym.flatName() == syms.restrictedInternalType.tsym.flatName()) { 1549 Assert.check(sym.kind == MTH); 1550 sym.flags_field |= RESTRICTED; 1551 } else { 1552 if (proxy.type.tsym == syms.annotationTargetType.tsym) { 1553 target = proxy; 1554 } else if (proxy.type.tsym == syms.repeatableType.tsym) { 1555 repeatable = proxy; 1556 } else if (proxy.type.tsym == syms.deprecatedType.tsym) { 1557 sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION); 1558 setFlagIfAttributeTrue(proxy, sym, names.forRemoval, DEPRECATED_REMOVAL); 1559 } else if (proxy.type.tsym == syms.previewFeatureType.tsym) { 1560 sym.flags_field |= PREVIEW_API; 1561 setFlagIfAttributeTrue(proxy, sym, names.reflective, PREVIEW_REFLECTIVE); 1562 } else if (proxy.type.tsym == syms.valueBasedType.tsym && sym.kind == TYP) { 1563 sym.flags_field |= VALUE_BASED; 1564 } else if (proxy.type.tsym == syms.restrictedType.tsym) { 1565 Assert.check(sym.kind == MTH); 1566 sym.flags_field |= RESTRICTED; 1567 } 1568 proxies.append(proxy); 1569 } 1570 } 1571 annotate.normal(new AnnotationCompleter(sym, proxies.toList())); 1572 } 1573 //where: 1574 private void setFlagIfAttributeTrue(CompoundAnnotationProxy proxy, Symbol sym, Name attribute, long flag) { 1575 for (Pair<Name, Attribute> v : proxy.values) { 1576 if (v.fst == attribute && v.snd instanceof Attribute.Constant constant) { 1577 if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) { 1578 sym.flags_field |= flag; 1579 } 1580 } 1581 } 1582 } 1583 1584 /** Read parameter annotations. 1585 */ 1586 void readParameterAnnotations(Symbol meth) { 1587 int numParameters; 1588 try { 1589 numParameters = buf.getByte(bp++) & 0xFF; 1590 } catch (UnderflowException e) { 1591 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 1592 } 1593 if (parameterAnnotations == null) { 1594 parameterAnnotations = new ParameterAnnotations[numParameters]; 1595 } else if (parameterAnnotations.length != numParameters) { 1596 throw badClassFile("bad.runtime.invisible.param.annotations", meth); 1597 } 1598 for (int pnum = 0; pnum < numParameters; pnum++) { 1599 if (parameterAnnotations[pnum] == null) { 1600 parameterAnnotations[pnum] = new ParameterAnnotations(); 1601 } 1602 parameterAnnotations[pnum].add(readAnnotations()); 1603 } 1604 } 1605 1606 void attachTypeAnnotations(final Symbol sym) { 1607 int numAttributes = nextChar(); 1608 if (numAttributes != 0) { 1609 ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>(); 1610 for (int i = 0; i < numAttributes; i++) 1611 proxies.append(readTypeAnnotation()); 1612 annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList())); 1613 } 1614 } 1615 1616 /** Attach the default value for an annotation element. 1617 */ 1618 void attachAnnotationDefault(final Symbol sym) { 1619 final MethodSymbol meth = (MethodSymbol)sym; // only on methods 1620 final Attribute value = readAttributeValue(); 1621 1622 // The default value is set later during annotation. It might 1623 // be the case that the Symbol sym is annotated _after_ the 1624 // repeating instances that depend on this default value, 1625 // because of this we set an interim value that tells us this 1626 // element (most likely) has a default. 1627 // 1628 // Set interim value for now, reset just before we do this 1629 // properly at annotate time. 1630 meth.defaultValue = value; 1631 annotate.normal(new AnnotationDefaultCompleter(meth, value)); 1632 } 1633 1634 Type readTypeOrClassSymbol(int i) { 1635 return readTypeToProxy(i); 1636 } 1637 Type readTypeToProxy(int i) { 1638 if (currentModule.module_info == currentOwner) { 1639 return new ProxyType(i); 1640 } else { 1641 return poolReader.getType(i); 1642 } 1643 } 1644 1645 CompoundAnnotationProxy readCompoundAnnotation() { 1646 Type t; 1647 if (currentModule.module_info == currentOwner) { 1648 int cpIndex = nextChar(); 1649 t = new ProxyType(cpIndex); 1650 } else { 1651 t = readTypeOrClassSymbol(nextChar()); 1652 } 1653 int numFields = nextChar(); 1654 ListBuffer<Pair<Name,Attribute>> pairs = new ListBuffer<>(); 1655 for (int i=0; i<numFields; i++) { 1656 Name name = poolReader.getName(nextChar()); 1657 Attribute value = readAttributeValue(); 1658 pairs.append(new Pair<>(name, value)); 1659 } 1660 return new CompoundAnnotationProxy(t, pairs.toList()); 1661 } 1662 1663 TypeAnnotationProxy readTypeAnnotation() { 1664 TypeAnnotationPosition position = readPosition(); 1665 CompoundAnnotationProxy proxy = readCompoundAnnotation(); 1666 1667 return new TypeAnnotationProxy(proxy, position); 1668 } 1669 1670 TypeAnnotationPosition readPosition() { 1671 int tag = nextByte(); // TargetType tag is a byte 1672 1673 if (!TargetType.isValidTargetTypeValue(tag)) 1674 throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag)); 1675 1676 TargetType type = TargetType.fromTargetTypeValue(tag); 1677 1678 switch (type) { 1679 // instanceof 1680 case INSTANCEOF: { 1681 final int offset = nextChar(); 1682 final TypeAnnotationPosition position = 1683 TypeAnnotationPosition.instanceOf(readTypePath()); 1684 position.offset = offset; 1685 return position; 1686 } 1687 // new expression 1688 case NEW: { 1689 final int offset = nextChar(); 1690 final TypeAnnotationPosition position = 1691 TypeAnnotationPosition.newObj(readTypePath()); 1692 position.offset = offset; 1693 return position; 1694 } 1695 // constructor/method reference receiver 1696 case CONSTRUCTOR_REFERENCE: { 1697 final int offset = nextChar(); 1698 final TypeAnnotationPosition position = 1699 TypeAnnotationPosition.constructorRef(readTypePath()); 1700 position.offset = offset; 1701 return position; 1702 } 1703 case METHOD_REFERENCE: { 1704 final int offset = nextChar(); 1705 final TypeAnnotationPosition position = 1706 TypeAnnotationPosition.methodRef(readTypePath()); 1707 position.offset = offset; 1708 return position; 1709 } 1710 // local variable 1711 case LOCAL_VARIABLE: { 1712 final int table_length = nextChar(); 1713 final int[] newLvarOffset = new int[table_length]; 1714 final int[] newLvarLength = new int[table_length]; 1715 final int[] newLvarIndex = new int[table_length]; 1716 1717 for (int i = 0; i < table_length; ++i) { 1718 newLvarOffset[i] = nextChar(); 1719 newLvarLength[i] = nextChar(); 1720 newLvarIndex[i] = nextChar(); 1721 } 1722 1723 final TypeAnnotationPosition position = 1724 TypeAnnotationPosition.localVariable(readTypePath()); 1725 position.lvarOffset = newLvarOffset; 1726 position.lvarLength = newLvarLength; 1727 position.lvarIndex = newLvarIndex; 1728 return position; 1729 } 1730 // resource variable 1731 case RESOURCE_VARIABLE: { 1732 final int table_length = nextChar(); 1733 final int[] newLvarOffset = new int[table_length]; 1734 final int[] newLvarLength = new int[table_length]; 1735 final int[] newLvarIndex = new int[table_length]; 1736 1737 for (int i = 0; i < table_length; ++i) { 1738 newLvarOffset[i] = nextChar(); 1739 newLvarLength[i] = nextChar(); 1740 newLvarIndex[i] = nextChar(); 1741 } 1742 1743 final TypeAnnotationPosition position = 1744 TypeAnnotationPosition.resourceVariable(readTypePath()); 1745 position.lvarOffset = newLvarOffset; 1746 position.lvarLength = newLvarLength; 1747 position.lvarIndex = newLvarIndex; 1748 return position; 1749 } 1750 // exception parameter 1751 case EXCEPTION_PARAMETER: { 1752 final int exception_index = nextChar(); 1753 final TypeAnnotationPosition position = 1754 TypeAnnotationPosition.exceptionParameter(readTypePath()); 1755 position.setExceptionIndex(exception_index); 1756 return position; 1757 } 1758 // method receiver 1759 case METHOD_RECEIVER: 1760 return TypeAnnotationPosition.methodReceiver(readTypePath()); 1761 // type parameter 1762 case CLASS_TYPE_PARAMETER: { 1763 final int parameter_index = nextByte(); 1764 return TypeAnnotationPosition 1765 .typeParameter(readTypePath(), parameter_index); 1766 } 1767 case METHOD_TYPE_PARAMETER: { 1768 final int parameter_index = nextByte(); 1769 return TypeAnnotationPosition 1770 .methodTypeParameter(readTypePath(), parameter_index); 1771 } 1772 // type parameter bound 1773 case CLASS_TYPE_PARAMETER_BOUND: { 1774 final int parameter_index = nextByte(); 1775 final int bound_index = nextByte(); 1776 return TypeAnnotationPosition 1777 .typeParameterBound(readTypePath(), parameter_index, 1778 bound_index); 1779 } 1780 case METHOD_TYPE_PARAMETER_BOUND: { 1781 final int parameter_index = nextByte(); 1782 final int bound_index = nextByte(); 1783 return TypeAnnotationPosition 1784 .methodTypeParameterBound(readTypePath(), parameter_index, 1785 bound_index); 1786 } 1787 // class extends or implements clause 1788 case CLASS_EXTENDS: { 1789 final int type_index = nextChar(); 1790 return TypeAnnotationPosition.classExtends(readTypePath(), 1791 type_index); 1792 } 1793 // throws 1794 case THROWS: { 1795 final int type_index = nextChar(); 1796 return TypeAnnotationPosition.methodThrows(readTypePath(), 1797 type_index); 1798 } 1799 // method parameter 1800 case METHOD_FORMAL_PARAMETER: { 1801 final int parameter_index = nextByte(); 1802 return TypeAnnotationPosition.methodParameter(readTypePath(), 1803 parameter_index); 1804 } 1805 // type cast 1806 case CAST: { 1807 final int offset = nextChar(); 1808 final int type_index = nextByte(); 1809 final TypeAnnotationPosition position = 1810 TypeAnnotationPosition.typeCast(readTypePath(), type_index); 1811 position.offset = offset; 1812 return position; 1813 } 1814 // method/constructor/reference type argument 1815 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: { 1816 final int offset = nextChar(); 1817 final int type_index = nextByte(); 1818 final TypeAnnotationPosition position = TypeAnnotationPosition 1819 .constructorInvocationTypeArg(readTypePath(), type_index); 1820 position.offset = offset; 1821 return position; 1822 } 1823 case METHOD_INVOCATION_TYPE_ARGUMENT: { 1824 final int offset = nextChar(); 1825 final int type_index = nextByte(); 1826 final TypeAnnotationPosition position = TypeAnnotationPosition 1827 .methodInvocationTypeArg(readTypePath(), type_index); 1828 position.offset = offset; 1829 return position; 1830 } 1831 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: { 1832 final int offset = nextChar(); 1833 final int type_index = nextByte(); 1834 final TypeAnnotationPosition position = TypeAnnotationPosition 1835 .constructorRefTypeArg(readTypePath(), type_index); 1836 position.offset = offset; 1837 return position; 1838 } 1839 case METHOD_REFERENCE_TYPE_ARGUMENT: { 1840 final int offset = nextChar(); 1841 final int type_index = nextByte(); 1842 final TypeAnnotationPosition position = TypeAnnotationPosition 1843 .methodRefTypeArg(readTypePath(), type_index); 1844 position.offset = offset; 1845 return position; 1846 } 1847 // We don't need to worry about these 1848 case METHOD_RETURN: 1849 return TypeAnnotationPosition.methodReturn(readTypePath()); 1850 case FIELD: 1851 return TypeAnnotationPosition.field(readTypePath()); 1852 case UNKNOWN: 1853 throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!"); 1854 default: 1855 throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + type); 1856 } 1857 } 1858 1859 List<TypeAnnotationPosition.TypePathEntry> readTypePath() { 1860 int len = nextByte(); 1861 ListBuffer<Integer> loc = new ListBuffer<>(); 1862 for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i) 1863 loc = loc.append(nextByte()); 1864 1865 return TypeAnnotationPosition.getTypePathFromBinary(loc.toList()); 1866 1867 } 1868 1869 /** 1870 * Helper function to read an optional pool entry (with given function); this is used while parsing 1871 * InnerClasses and EnclosingMethod attributes, as well as when parsing supertype descriptor, 1872 * as per JVMS. 1873 */ 1874 <Z> Z optPoolEntry(int index, IntFunction<Z> poolFunc, Z defaultValue) { 1875 return (index == 0) ? 1876 defaultValue : 1877 poolFunc.apply(index); 1878 } 1879 1880 Attribute readAttributeValue() { 1881 char c; 1882 try { 1883 c = (char)buf.getByte(bp++); 1884 } catch (UnderflowException e) { 1885 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 1886 } 1887 switch (c) { 1888 case 'B': 1889 return new Attribute.Constant(syms.byteType, poolReader.getConstant(nextChar())); 1890 case 'C': 1891 return new Attribute.Constant(syms.charType, poolReader.getConstant(nextChar())); 1892 case 'D': 1893 return new Attribute.Constant(syms.doubleType, poolReader.getConstant(nextChar())); 1894 case 'F': 1895 return new Attribute.Constant(syms.floatType, poolReader.getConstant(nextChar())); 1896 case 'I': 1897 return new Attribute.Constant(syms.intType, poolReader.getConstant(nextChar())); 1898 case 'J': 1899 return new Attribute.Constant(syms.longType, poolReader.getConstant(nextChar())); 1900 case 'S': 1901 return new Attribute.Constant(syms.shortType, poolReader.getConstant(nextChar())); 1902 case 'Z': 1903 return new Attribute.Constant(syms.booleanType, poolReader.getConstant(nextChar())); 1904 case 's': 1905 return new Attribute.Constant(syms.stringType, poolReader.getName(nextChar()).toString()); 1906 case 'e': 1907 return new EnumAttributeProxy(readTypeToProxy(nextChar()), poolReader.getName(nextChar())); 1908 case 'c': 1909 return new ClassAttributeProxy(readTypeOrClassSymbol(nextChar())); 1910 case '[': { 1911 int n = nextChar(); 1912 ListBuffer<Attribute> l = new ListBuffer<>(); 1913 for (int i=0; i<n; i++) 1914 l.append(readAttributeValue()); 1915 return new ArrayAttributeProxy(l.toList()); 1916 } 1917 case '@': 1918 return readCompoundAnnotation(); 1919 default: 1920 throw new AssertionError("unknown annotation tag '" + c + "'"); 1921 } 1922 } 1923 1924 interface ProxyVisitor extends Attribute.Visitor { 1925 void visitEnumAttributeProxy(EnumAttributeProxy proxy); 1926 void visitClassAttributeProxy(ClassAttributeProxy proxy); 1927 void visitArrayAttributeProxy(ArrayAttributeProxy proxy); 1928 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy); 1929 } 1930 1931 static class EnumAttributeProxy extends Attribute { 1932 Type enumType; 1933 Name enumerator; 1934 public EnumAttributeProxy(Type enumType, Name enumerator) { 1935 super(null); 1936 this.enumType = enumType; 1937 this.enumerator = enumerator; 1938 } 1939 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); } 1940 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1941 public String toString() { 1942 return "/*proxy enum*/" + enumType + "." + enumerator; 1943 } 1944 } 1945 1946 static class ClassAttributeProxy extends Attribute { 1947 Type classType; 1948 public ClassAttributeProxy(Type classType) { 1949 super(null); 1950 this.classType = classType; 1951 } 1952 public void accept(Visitor v) { ((ProxyVisitor)v).visitClassAttributeProxy(this); } 1953 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1954 public String toString() { 1955 return "/*proxy class*/" + classType + ".class"; 1956 } 1957 } 1958 1959 static class ArrayAttributeProxy extends Attribute { 1960 List<Attribute> values; 1961 ArrayAttributeProxy(List<Attribute> values) { 1962 super(null); 1963 this.values = values; 1964 } 1965 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); } 1966 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1967 public String toString() { 1968 return "{" + values + "}"; 1969 } 1970 } 1971 1972 /** A temporary proxy representing a compound attribute. 1973 */ 1974 static class CompoundAnnotationProxy extends Attribute { 1975 final List<Pair<Name,Attribute>> values; 1976 public CompoundAnnotationProxy(Type type, 1977 List<Pair<Name,Attribute>> values) { 1978 super(type); 1979 this.values = values; 1980 } 1981 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); } 1982 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1983 public String toString() { 1984 StringBuilder buf = new StringBuilder(); 1985 buf.append("@"); 1986 buf.append(type.tsym.getQualifiedName()); 1987 buf.append("/*proxy*/{"); 1988 boolean first = true; 1989 for (List<Pair<Name,Attribute>> v = values; 1990 v.nonEmpty(); v = v.tail) { 1991 Pair<Name,Attribute> value = v.head; 1992 if (!first) buf.append(","); 1993 first = false; 1994 buf.append(value.fst); 1995 buf.append("="); 1996 buf.append(value.snd); 1997 } 1998 buf.append("}"); 1999 return buf.toString(); 2000 } 2001 } 2002 2003 /** A temporary proxy representing a type annotation. 2004 */ 2005 static class TypeAnnotationProxy { 2006 final CompoundAnnotationProxy compound; 2007 final TypeAnnotationPosition position; 2008 public TypeAnnotationProxy(CompoundAnnotationProxy compound, 2009 TypeAnnotationPosition position) { 2010 this.compound = compound; 2011 this.position = position; 2012 } 2013 } 2014 2015 class AnnotationDeproxy implements ProxyVisitor { 2016 private ClassSymbol requestingOwner; 2017 2018 AnnotationDeproxy(ClassSymbol owner) { 2019 this.requestingOwner = owner; 2020 } 2021 2022 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) { 2023 // also must fill in types!!!! 2024 ListBuffer<Attribute.Compound> buf = new ListBuffer<>(); 2025 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) { 2026 buf.append(deproxyCompound(l.head)); 2027 } 2028 return buf.toList(); 2029 } 2030 2031 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) { 2032 Type annotationType = resolvePossibleProxyType(a.type); 2033 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf = new ListBuffer<>(); 2034 for (List<Pair<Name,Attribute>> l = a.values; 2035 l.nonEmpty(); 2036 l = l.tail) { 2037 MethodSymbol meth = findAccessMethod(annotationType, l.head.fst); 2038 buf.append(new Pair<>(meth, deproxy(meth.type.getReturnType(), l.head.snd))); 2039 } 2040 return new Attribute.Compound(annotationType, buf.toList()); 2041 } 2042 2043 MethodSymbol findAccessMethod(Type container, Name name) { 2044 CompletionFailure failure = null; 2045 try { 2046 for (Symbol sym : container.tsym.members().getSymbolsByName(name)) { 2047 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0) 2048 return (MethodSymbol) sym; 2049 } 2050 } catch (CompletionFailure ex) { 2051 failure = ex; 2052 } 2053 // The method wasn't found: emit a warning and recover 2054 JavaFileObject prevSource = log.useSource(requestingOwner.classfile); 2055 try { 2056 if (lintClassfile) { 2057 if (failure == null) { 2058 log.warning(Warnings.AnnotationMethodNotFound(container, name)); 2059 } else { 2060 log.warning(Warnings.AnnotationMethodNotFoundReason(container, 2061 name, 2062 failure.getDetailValue()));//diagnostic, if present 2063 } 2064 } 2065 } finally { 2066 log.useSource(prevSource); 2067 } 2068 // Construct a new method type and symbol. Use bottom 2069 // type (typeof null) as return type because this type is 2070 // a subtype of all reference types and can be converted 2071 // to primitive types by unboxing. 2072 MethodType mt = new MethodType(List.nil(), 2073 syms.botType, 2074 List.nil(), 2075 syms.methodClass); 2076 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym); 2077 } 2078 2079 Attribute result; 2080 Type type; 2081 Attribute deproxy(Type t, Attribute a) { 2082 Type oldType = type; 2083 try { 2084 type = t; 2085 a.accept(this); 2086 return result; 2087 } finally { 2088 type = oldType; 2089 } 2090 } 2091 2092 // implement Attribute.Visitor below 2093 2094 public void visitConstant(Attribute.Constant value) { 2095 // assert value.type == type; 2096 result = value; 2097 } 2098 2099 public void visitClass(Attribute.Class clazz) { 2100 result = clazz; 2101 } 2102 2103 public void visitEnum(Attribute.Enum e) { 2104 throw new AssertionError(); // shouldn't happen 2105 } 2106 2107 public void visitCompound(Attribute.Compound compound) { 2108 throw new AssertionError(); // shouldn't happen 2109 } 2110 2111 public void visitArray(Attribute.Array array) { 2112 throw new AssertionError(); // shouldn't happen 2113 } 2114 2115 public void visitError(Attribute.Error e) { 2116 throw new AssertionError(); // shouldn't happen 2117 } 2118 2119 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) { 2120 // type.tsym.flatName() should == proxy.enumFlatName 2121 Type enumType = resolvePossibleProxyType(proxy.enumType); 2122 TypeSymbol enumTypeSym = enumType.tsym; 2123 VarSymbol enumerator = null; 2124 CompletionFailure failure = null; 2125 try { 2126 for (Symbol sym : enumTypeSym.members().getSymbolsByName(proxy.enumerator)) { 2127 if (sym.kind == VAR) { 2128 enumerator = (VarSymbol)sym; 2129 break; 2130 } 2131 } 2132 } 2133 catch (CompletionFailure ex) { 2134 failure = ex; 2135 } 2136 if (enumerator == null) { 2137 if (failure != null) { 2138 log.warning(Warnings.UnknownEnumConstantReason(currentClassFile, 2139 enumTypeSym, 2140 proxy.enumerator, 2141 failure.getDiagnostic())); 2142 } else { 2143 log.warning(Warnings.UnknownEnumConstant(currentClassFile, 2144 enumTypeSym, 2145 proxy.enumerator)); 2146 } 2147 result = new Attribute.Enum(enumTypeSym.type, 2148 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym)); 2149 } else { 2150 result = new Attribute.Enum(enumTypeSym.type, enumerator); 2151 } 2152 } 2153 2154 @Override 2155 public void visitClassAttributeProxy(ClassAttributeProxy proxy) { 2156 Type classType = resolvePossibleProxyType(proxy.classType); 2157 result = new Attribute.Class(types, classType); 2158 } 2159 2160 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) { 2161 int length = proxy.values.length(); 2162 Attribute[] ats = new Attribute[length]; 2163 Type elemtype = types.elemtype(type); 2164 int i = 0; 2165 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) { 2166 ats[i++] = deproxy(elemtype, p.head); 2167 } 2168 result = new Attribute.Array(type, ats); 2169 } 2170 2171 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) { 2172 result = deproxyCompound(proxy); 2173 } 2174 2175 Type resolvePossibleProxyType(Type t) { 2176 if (t instanceof ProxyType proxyType) { 2177 Assert.check(requestingOwner.owner.kind == MDL); 2178 ModuleSymbol prevCurrentModule = currentModule; 2179 currentModule = (ModuleSymbol) requestingOwner.owner; 2180 try { 2181 return proxyType.resolve(); 2182 } finally { 2183 currentModule = prevCurrentModule; 2184 } 2185 } else { 2186 return t; 2187 } 2188 } 2189 } 2190 2191 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Runnable { 2192 final MethodSymbol sym; 2193 final Attribute value; 2194 final JavaFileObject classFile = currentClassFile; 2195 2196 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) { 2197 super(currentOwner.kind == MTH 2198 ? currentOwner.enclClass() : (ClassSymbol)currentOwner); 2199 this.sym = sym; 2200 this.value = value; 2201 } 2202 2203 @Override 2204 public void run() { 2205 JavaFileObject previousClassFile = currentClassFile; 2206 try { 2207 // Reset the interim value set earlier in 2208 // attachAnnotationDefault(). 2209 sym.defaultValue = null; 2210 currentClassFile = classFile; 2211 sym.defaultValue = deproxy(sym.type.getReturnType(), value); 2212 } finally { 2213 currentClassFile = previousClassFile; 2214 } 2215 } 2216 2217 @Override 2218 public String toString() { 2219 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value; 2220 } 2221 } 2222 2223 class AnnotationCompleter extends AnnotationDeproxy implements Runnable { 2224 final Symbol sym; 2225 final List<CompoundAnnotationProxy> l; 2226 final JavaFileObject classFile; 2227 2228 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) { 2229 super(currentOwner.kind == MTH 2230 ? currentOwner.enclClass() : (ClassSymbol)currentOwner); 2231 if (sym.kind == TYP && sym.owner.kind == MDL) { 2232 this.sym = sym.owner; 2233 } else { 2234 this.sym = sym; 2235 } 2236 this.l = l; 2237 this.classFile = currentClassFile; 2238 } 2239 2240 @Override 2241 public void run() { 2242 JavaFileObject previousClassFile = currentClassFile; 2243 try { 2244 currentClassFile = classFile; 2245 List<Attribute.Compound> newList = deproxyCompoundList(l); 2246 for (Attribute.Compound attr : newList) { 2247 if (attr.type.tsym == syms.deprecatedType.tsym) { 2248 sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION); 2249 Attribute forRemoval = attr.member(names.forRemoval); 2250 if (forRemoval instanceof Attribute.Constant constant) { 2251 if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) { 2252 sym.flags_field |= DEPRECATED_REMOVAL; 2253 } 2254 } 2255 } 2256 } 2257 if (sym.annotationsPendingCompletion()) { 2258 sym.setDeclarationAttributes(newList); 2259 } else { 2260 sym.appendAttributes(newList); 2261 } 2262 } finally { 2263 currentClassFile = previousClassFile; 2264 } 2265 } 2266 2267 @Override 2268 public String toString() { 2269 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l; 2270 } 2271 } 2272 2273 class TypeAnnotationCompleter extends AnnotationCompleter { 2274 2275 List<TypeAnnotationProxy> proxies; 2276 2277 TypeAnnotationCompleter(Symbol sym, 2278 List<TypeAnnotationProxy> proxies) { 2279 super(sym, List.nil()); 2280 this.proxies = proxies; 2281 } 2282 2283 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) { 2284 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>(); 2285 for (TypeAnnotationProxy proxy: proxies) { 2286 Attribute.Compound compound = deproxyCompound(proxy.compound); 2287 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position); 2288 buf.add(typeCompound); 2289 } 2290 return buf.toList(); 2291 } 2292 2293 @Override 2294 public void run() { 2295 JavaFileObject previousClassFile = currentClassFile; 2296 try { 2297 currentClassFile = classFile; 2298 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies); 2299 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes())); 2300 addTypeAnnotationsToSymbol(sym, newList); 2301 } finally { 2302 currentClassFile = previousClassFile; 2303 } 2304 } 2305 } 2306 2307 /** 2308 * Rewrites types in the given symbol to include type annotations. 2309 * 2310 * <p>The list of type annotations includes annotations for all types in the signature of the 2311 * symbol. Associating the annotations with the correct type requires interpreting the JVMS 2312 * 4.7.20-A target_type to locate the correct type to rewrite, and then interpreting the JVMS 2313 * 4.7.20.2 type_path to associate the annotation with the correct contained type. 2314 */ 2315 private void addTypeAnnotationsToSymbol(Symbol s, List<Attribute.TypeCompound> attributes) { 2316 try { 2317 new TypeAnnotationSymbolVisitor(attributes).visit(s, null); 2318 } catch (CompletionFailure ex) { 2319 JavaFileObject prev = log.useSource(currentClassFile); 2320 try { 2321 log.error(Errors.CantAttachTypeAnnotations(attributes, s.owner, s.name, ex.getDetailValue())); 2322 } finally { 2323 log.useSource(prev); 2324 } 2325 } 2326 } 2327 2328 private static class TypeAnnotationSymbolVisitor 2329 extends Types.DefaultSymbolVisitor<Void, Void> { 2330 2331 private final List<Attribute.TypeCompound> attributes; 2332 2333 private TypeAnnotationSymbolVisitor(List<Attribute.TypeCompound> attributes) { 2334 this.attributes = attributes; 2335 } 2336 2337 @Override 2338 public Void visitClassSymbol(Symbol.ClassSymbol s, Void unused) { 2339 ClassType t = (ClassType) s.type; 2340 int i = 0; 2341 ListBuffer<Type> interfaces = new ListBuffer<>(); 2342 for (Type itf : t.interfaces_field) { 2343 interfaces.add(addTypeAnnotations(itf, classExtends(i++))); 2344 } 2345 t.interfaces_field = interfaces.toList(); 2346 t.supertype_field = addTypeAnnotations(t.supertype_field, classExtends(65535)); 2347 if (t.typarams_field != null) { 2348 t.typarams_field = 2349 rewriteTypeParameters( 2350 t.typarams_field, TargetType.CLASS_TYPE_PARAMETER_BOUND); 2351 } 2352 return null; 2353 } 2354 2355 @Override 2356 public Void visitMethodSymbol(Symbol.MethodSymbol s, Void unused) { 2357 Type t = s.type; 2358 if (t.hasTag(TypeTag.FORALL)) { 2359 Type.ForAll fa = (Type.ForAll) t; 2360 fa.tvars = rewriteTypeParameters(fa.tvars, TargetType.METHOD_TYPE_PARAMETER_BOUND); 2361 t = fa.qtype; 2362 } 2363 MethodType mt = (MethodType) t; 2364 ListBuffer<Type> argtypes = new ListBuffer<>(); 2365 int i = 0; 2366 for (Symbol.VarSymbol param : s.params) { 2367 param.type = addTypeAnnotations(param.type, methodFormalParameter(i++)); 2368 argtypes.add(param.type); 2369 } 2370 mt.argtypes = argtypes.toList(); 2371 ListBuffer<Type> thrown = new ListBuffer<>(); 2372 i = 0; 2373 for (Type thrownType : mt.thrown) { 2374 thrown.add(addTypeAnnotations(thrownType, thrownType(i++))); 2375 } 2376 mt.thrown = thrown.toList(); 2377 /* possible information loss if the type of the method is void then we can't add type 2378 * annotations to it 2379 */ 2380 if (!mt.restype.hasTag(TypeTag.VOID)) { 2381 mt.restype = addTypeAnnotations(mt.restype, TargetType.METHOD_RETURN); 2382 } 2383 2384 Type recvtype = mt.recvtype != null ? mt.recvtype : s.implicitReceiverType(); 2385 if (recvtype != null) { 2386 Type annotated = addTypeAnnotations(recvtype, TargetType.METHOD_RECEIVER); 2387 if (annotated != recvtype) { 2388 mt.recvtype = annotated; 2389 } 2390 } 2391 return null; 2392 } 2393 2394 @Override 2395 public Void visitVarSymbol(Symbol.VarSymbol s, Void unused) { 2396 s.type = addTypeAnnotations(s.type, TargetType.FIELD); 2397 return null; 2398 } 2399 2400 @Override 2401 public Void visitSymbol(Symbol s, Void unused) { 2402 return null; 2403 } 2404 2405 private List<Type> rewriteTypeParameters(List<Type> tvars, TargetType boundType) { 2406 ListBuffer<Type> tvarbuf = new ListBuffer<>(); 2407 int typeVariableIndex = 0; 2408 for (Type tvar : tvars) { 2409 Type bound = tvar.getUpperBound(); 2410 if (bound.isCompound()) { 2411 ClassType ct = (ClassType) bound; 2412 int boundIndex = 0; 2413 if (ct.supertype_field != null) { 2414 ct.supertype_field = 2415 addTypeAnnotations( 2416 ct.supertype_field, 2417 typeParameterBound( 2418 boundType, typeVariableIndex, boundIndex++)); 2419 } 2420 ListBuffer<Type> itfbuf = new ListBuffer<>(); 2421 for (Type itf : ct.interfaces_field) { 2422 itfbuf.add( 2423 addTypeAnnotations( 2424 itf, 2425 typeParameterBound( 2426 boundType, typeVariableIndex, boundIndex++))); 2427 } 2428 ct.interfaces_field = itfbuf.toList(); 2429 } else { 2430 bound = 2431 addTypeAnnotations( 2432 bound, 2433 typeParameterBound( 2434 boundType, 2435 typeVariableIndex, 2436 bound.isInterface() ? 1 : 0)); 2437 } 2438 ((TypeVar) tvar).setUpperBound(bound); 2439 tvarbuf.add(tvar); 2440 typeVariableIndex++; 2441 } 2442 return tvarbuf.toList(); 2443 } 2444 2445 private Type addTypeAnnotations(Type type, TargetType targetType) { 2446 return addTypeAnnotations(type, pos -> pos.type == targetType); 2447 } 2448 2449 private Type addTypeAnnotations(Type type, Predicate<TypeAnnotationPosition> filter) { 2450 Assert.checkNonNull(type); 2451 2452 // Find type annotations that match the given target type 2453 ListBuffer<Attribute.TypeCompound> filtered = new ListBuffer<>(); 2454 for (Attribute.TypeCompound attribute : this.attributes) { 2455 if (filter.test(attribute.position)) { 2456 filtered.add(attribute); 2457 } 2458 } 2459 if (filtered.isEmpty()) { 2460 return type; 2461 } 2462 2463 // Group the matching annotations by their type path. Each group of annotations will be 2464 // added to a type at that location. 2465 Map<List<TypeAnnotationPosition.TypePathEntry>, ListBuffer<Attribute.TypeCompound>> 2466 attributesByPath = new HashMap<>(); 2467 for (Attribute.TypeCompound attribute : filtered.toList()) { 2468 attributesByPath 2469 .computeIfAbsent(attribute.position.location, k -> new ListBuffer<>()) 2470 .add(attribute); 2471 } 2472 2473 // Rewrite the type and add the annotations 2474 type = new TypeAnnotationStructuralTypeMapping(attributesByPath).visit(type, List.nil()); 2475 2476 return type; 2477 } 2478 2479 private static Predicate<TypeAnnotationPosition> typeParameterBound( 2480 TargetType targetType, int parameterIndex, int boundIndex) { 2481 return pos -> 2482 pos.type == targetType 2483 && pos.parameter_index == parameterIndex 2484 && pos.bound_index == boundIndex; 2485 } 2486 2487 private static Predicate<TypeAnnotationPosition> methodFormalParameter(int index) { 2488 return pos -> 2489 pos.type == TargetType.METHOD_FORMAL_PARAMETER && pos.parameter_index == index; 2490 } 2491 2492 private static Predicate<TypeAnnotationPosition> thrownType(int index) { 2493 return pos -> pos.type == TargetType.THROWS && pos.type_index == index; 2494 } 2495 2496 private static Predicate<TypeAnnotationPosition> classExtends(int index) { 2497 return pos -> pos.type == TargetType.CLASS_EXTENDS && pos.type_index == index; 2498 } 2499 } 2500 2501 /** 2502 * A type mapping that rewrites the type to include type annotations. 2503 * 2504 * <p>This logic is similar to {@link Type.StructuralTypeMapping}, but also tracks the path to 2505 * the contained types being rewritten, and so cannot easily share the existing logic. 2506 */ 2507 private static final class TypeAnnotationStructuralTypeMapping 2508 extends Types.TypeMapping<List<TypeAnnotationPosition.TypePathEntry>> { 2509 2510 private final Map<List<TypeAnnotationPosition.TypePathEntry>, 2511 ListBuffer<Attribute.TypeCompound>> attributesByPath; 2512 2513 private TypeAnnotationStructuralTypeMapping( 2514 Map<List<TypeAnnotationPosition.TypePathEntry>, ListBuffer<Attribute.TypeCompound>> 2515 attributesByPath) { 2516 this.attributesByPath = attributesByPath; 2517 } 2518 2519 2520 @Override 2521 public Type visitClassType(ClassType t, List<TypeAnnotationPosition.TypePathEntry> path) { 2522 // As described in JVMS 4.7.20.2, type annotations on nested types are located with 2523 // 'left-to-right' steps starting on 'the outermost part of the type for which a type 2524 // annotation is admissible'. So the current path represents the outermost containing 2525 // type of the type being visited, and we add type path steps for every contained nested 2526 // type. 2527 Type outer = t.getEnclosingType(); 2528 Type outer1 = outer != Type.noType ? visit(outer, path) : outer; 2529 for (Type curr = t.getEnclosingType(); 2530 curr != Type.noType; 2531 curr = curr.getEnclosingType()) { 2532 path = path.append(TypeAnnotationPosition.TypePathEntry.INNER_TYPE); 2533 } 2534 List<Type> typarams = t.getTypeArguments(); 2535 List<Type> typarams1 = rewriteTypeParams(path, typarams); 2536 if (outer1 != outer || typarams != typarams1) { 2537 t = new ClassType(outer1, typarams1, t.tsym, t.getMetadata()); 2538 } 2539 return reannotate(t, path); 2540 } 2541 2542 private List<Type> rewriteTypeParams( 2543 List<TypeAnnotationPosition.TypePathEntry> path, List<Type> typarams) { 2544 var i = IntStream.iterate(0, x -> x + 1).iterator(); 2545 return typarams.map(typaram -> visit(typaram, 2546 path.append(new TypeAnnotationPosition.TypePathEntry( 2547 TypeAnnotationPosition.TypePathEntryKind.TYPE_ARGUMENT, i.nextInt())))); 2548 } 2549 2550 @Override 2551 public Type visitWildcardType( 2552 WildcardType wt, List<TypeAnnotationPosition.TypePathEntry> path) { 2553 Type t = wt.type; 2554 if (t != null) { 2555 t = visit(t, path.append(TypeAnnotationPosition.TypePathEntry.WILDCARD)); 2556 } 2557 if (t != wt.type) { 2558 wt = new WildcardType(t, wt.kind, wt.tsym, wt.bound, wt.getMetadata()); 2559 } 2560 return reannotate(wt, path); 2561 } 2562 2563 @Override 2564 public Type visitArrayType(ArrayType t, List<TypeAnnotationPosition.TypePathEntry> path) { 2565 Type elemtype = t.elemtype; 2566 Type elemtype1 = 2567 visit(elemtype, path.append(TypeAnnotationPosition.TypePathEntry.ARRAY)); 2568 if (elemtype1 != elemtype) { 2569 t = new ArrayType(elemtype1, t.tsym, t.getMetadata()); 2570 } 2571 return reannotate(t, path); 2572 } 2573 2574 @Override 2575 public Type visitType(Type t, List<TypeAnnotationPosition.TypePathEntry> path) { 2576 return reannotate(t, path); 2577 } 2578 2579 Type reannotate(Type type, List<TypeAnnotationPosition.TypePathEntry> path) { 2580 List<Attribute.TypeCompound> attributes = attributesForPath(path); 2581 if (attributes.isEmpty()) { 2582 return type; 2583 } 2584 // Runtime-visible and -invisible annotations are completed separately, so if the same 2585 // type has annotations from both it will get annotated twice. 2586 TypeMetadata.Annotations existing = type.getMetadata(TypeMetadata.Annotations.class); 2587 if (existing != null) { 2588 existing.annotationBuffer().addAll(attributes); 2589 return type; 2590 } 2591 return type.annotatedType(attributes); 2592 } 2593 2594 List<Attribute.TypeCompound> attributesForPath( 2595 List<TypeAnnotationPosition.TypePathEntry> path) { 2596 ListBuffer<Attribute.TypeCompound> attributes = attributesByPath.remove(path); 2597 return attributes != null ? attributes.toList() : List.nil(); 2598 } 2599 } 2600 2601 /* ********************************************************************** 2602 * Reading Symbols 2603 ***********************************************************************/ 2604 2605 /** Read a field. 2606 */ 2607 VarSymbol readField() { 2608 char rawFlags = nextChar(); 2609 long flags = adjustFieldFlags(rawFlags); 2610 Name name = poolReader.getName(nextChar()); 2611 Type type = poolReader.getType(nextChar()); 2612 VarSymbol v = new VarSymbol(flags, name, type, currentOwner); 2613 readMemberAttrs(v); 2614 if (Integer.bitCount(rawFlags & (PUBLIC | PRIVATE | PROTECTED)) > 1 || 2615 Integer.bitCount(rawFlags & (FINAL | VOLATILE)) > 1) 2616 throw badClassFile("illegal.flag.combo", Flags.toString((long)rawFlags), "field", v); 2617 return v; 2618 } 2619 2620 /** Read a method. 2621 */ 2622 MethodSymbol readMethod() { 2623 char rawFlags = nextChar(); 2624 long flags = adjustMethodFlags(rawFlags); 2625 Name name = poolReader.getName(nextChar()); 2626 Type type = poolReader.getType(nextChar()); 2627 if (currentOwner.isInterface() && 2628 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) { 2629 if (majorVersion > Version.V52.major || 2630 (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) { 2631 if ((flags & (STATIC | PRIVATE)) == 0) { 2632 currentOwner.flags_field |= DEFAULT; 2633 flags |= DEFAULT | ABSTRACT; 2634 } 2635 } else { 2636 //protect against ill-formed classfiles 2637 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface", 2638 Integer.toString(majorVersion), 2639 Integer.toString(minorVersion)); 2640 } 2641 } 2642 validateMethodType(name, type); 2643 if (name == names.init && currentOwner.hasOuterInstance()) { 2644 // Sometimes anonymous classes don't have an outer 2645 // instance, however, there is no reliable way to tell so 2646 // we never strip this$n 2647 // ditto for local classes. Local classes that have an enclosing method set 2648 // won't pass the "hasOuterInstance" check above, but those that don't have an 2649 // enclosing method (i.e. from initializers) will pass that check. 2650 boolean local = !currentOwner.owner.members().includes(currentOwner, LookupKind.NON_RECURSIVE); 2651 if (!currentOwner.name.isEmpty() && !local) 2652 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()), 2653 type.getReturnType(), 2654 type.getThrownTypes(), 2655 syms.methodClass); 2656 } 2657 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner); 2658 if (types.isSignaturePolymorphic(m)) { 2659 m.flags_field |= SIGNATURE_POLYMORPHIC; 2660 } 2661 if (saveParameterNames) 2662 initParameterNames(m); 2663 Symbol prevOwner = currentOwner; 2664 currentOwner = m; 2665 try { 2666 readMemberAttrs(m); 2667 } finally { 2668 currentOwner = prevOwner; 2669 } 2670 validateMethodType(name, m.type); 2671 setParameters(m, type); 2672 2673 if (Integer.bitCount(rawFlags & (PUBLIC | PRIVATE | PROTECTED)) > 1) 2674 throw badClassFile("illegal.flag.combo", Flags.toString((long)rawFlags), "method", m); 2675 if ((flags & VARARGS) != 0) { 2676 final Type last = type.getParameterTypes().last(); 2677 if (last == null || !last.hasTag(ARRAY)) { 2678 m.flags_field &= ~VARARGS; 2679 throw badClassFile("malformed.vararg.method", m); 2680 } 2681 } 2682 2683 return m; 2684 } 2685 2686 void validateMethodType(Name name, Type t) { 2687 if ((!t.hasTag(TypeTag.METHOD) && !t.hasTag(TypeTag.FORALL)) || 2688 (name == names.init && !t.getReturnType().hasTag(TypeTag.VOID))) { 2689 throw badClassFile("method.descriptor.invalid", name); 2690 } 2691 } 2692 2693 private List<Type> adjustMethodParams(long flags, List<Type> args) { 2694 if (args.isEmpty()) { 2695 return args; 2696 } 2697 boolean isVarargs = (flags & VARARGS) != 0; 2698 if (isVarargs) { 2699 Type varargsElem = args.last(); 2700 ListBuffer<Type> adjustedArgs = new ListBuffer<>(); 2701 for (Type t : args) { 2702 adjustedArgs.append(t != varargsElem ? 2703 t : 2704 ((ArrayType)t).makeVarargs()); 2705 } 2706 args = adjustedArgs.toList(); 2707 } 2708 return args.tail; 2709 } 2710 2711 /** 2712 * Init the parameter names array. 2713 * Parameter names are currently inferred from the names in the 2714 * LocalVariableTable attributes of a Code attribute. 2715 * (Note: this means parameter names are currently not available for 2716 * methods without a Code attribute.) 2717 * This method initializes an array in which to store the name indexes 2718 * of parameter names found in LocalVariableTable attributes. It is 2719 * slightly supersized to allow for additional slots with a start_pc of 0. 2720 */ 2721 void initParameterNames(MethodSymbol sym) { 2722 // make allowance for synthetic parameters. 2723 final int excessSlots = 4; 2724 int expectedParameterSlots = 2725 Code.width(sym.type.getParameterTypes()) + excessSlots; 2726 if (parameterNameIndicesLvt == null 2727 || parameterNameIndicesLvt.length < expectedParameterSlots) { 2728 parameterNameIndicesLvt = new int[expectedParameterSlots]; 2729 } else 2730 Arrays.fill(parameterNameIndicesLvt, 0); 2731 } 2732 2733 /** 2734 * Set the parameters for a method symbol, including any names and 2735 * annotations that were read. 2736 * 2737 * <p>The type of the symbol may have changed while reading the 2738 * method attributes (see the Signature attribute). This may be 2739 * because of generic information or because anonymous synthetic 2740 * parameters were added. The original type (as read from the 2741 * method descriptor) is used to help guess the existence of 2742 * anonymous synthetic parameters. 2743 */ 2744 void setParameters(MethodSymbol sym, Type jvmType) { 2745 int firstParamLvt = ((sym.flags() & STATIC) == 0) ? 1 : 0; 2746 // the code in readMethod may have skipped the first 2747 // parameter when setting up the MethodType. If so, we 2748 // make a corresponding allowance here for the position of 2749 // the first parameter. Note that this assumes the 2750 // skipped parameter has a width of 1 -- i.e. it is not 2751 // a double width type (long or double.) 2752 if (sym.name == names.init && currentOwner.hasOuterInstance()) { 2753 // Sometimes anonymous classes don't have an outer 2754 // instance, however, there is no reliable way to tell so 2755 // we never strip this$n 2756 if (!currentOwner.name.isEmpty()) 2757 firstParamLvt += 1; 2758 } 2759 2760 if (sym.type != jvmType) { 2761 // reading the method attributes has caused the 2762 // symbol's type to be changed. (i.e. the Signature 2763 // attribute.) This may happen if there are hidden 2764 // (synthetic) parameters in the descriptor, but not 2765 // in the Signature. The position of these hidden 2766 // parameters is unspecified; for now, assume they are 2767 // at the beginning, and so skip over them. The 2768 // primary case for this is two hidden parameters 2769 // passed into Enum constructors. 2770 int skip = Code.width(jvmType.getParameterTypes()) 2771 - Code.width(sym.type.getParameterTypes()); 2772 firstParamLvt += skip; 2773 } 2774 Set<Name> paramNames = new HashSet<>(); 2775 ListBuffer<VarSymbol> params = new ListBuffer<>(); 2776 // we maintain two index pointers, one for the LocalVariableTable attribute 2777 // and the other for the MethodParameters attribute. 2778 // This is needed as the MethodParameters attribute may contain 2779 // name_index = 0 in which case we want to fall back to the LocalVariableTable. 2780 // In such case, we still want to read the flags from the MethodParameters with that index. 2781 int nameIndexLvt = firstParamLvt; 2782 int nameIndexMp = 0; 2783 int annotationIndex = 0; 2784 for (Type t: sym.type.getParameterTypes()) { 2785 VarSymbol param = parameter(nameIndexMp, nameIndexLvt, t, sym, paramNames); 2786 params.append(param); 2787 if (parameterAnnotations != null) { 2788 ParameterAnnotations annotations = parameterAnnotations[annotationIndex]; 2789 if (annotations != null && annotations.proxies != null 2790 && !annotations.proxies.isEmpty()) { 2791 annotate.normal(new AnnotationCompleter(param, annotations.proxies)); 2792 } 2793 } 2794 nameIndexLvt += Code.width(t); 2795 nameIndexMp++; 2796 annotationIndex++; 2797 } 2798 if (parameterAnnotations != null && parameterAnnotations.length != annotationIndex) { 2799 throw badClassFile("bad.runtime.invisible.param.annotations", sym); 2800 } 2801 Assert.checkNull(sym.params); 2802 sym.params = params.toList(); 2803 parameterAnnotations = null; 2804 parameterNameIndicesLvt = null; 2805 parameterNameIndicesMp = null; 2806 parameterAccessFlags = null; 2807 } 2808 2809 /** 2810 * Creates the parameter at the position {@code mpIndex} in the parameter list of the owning method. 2811 * Flags are optionally read from the MethodParameters attribute. 2812 * Names are optionally read from the MethodParameters attribute. If the constant pool index 2813 * of the name is 0, then the name is optionally read from the LocalVariableTable attribute. 2814 * @param mpIndex the index of the parameter in the MethodParameters attribute 2815 * @param lvtIndex the index of the parameter in the LocalVariableTable attribute 2816 */ 2817 private VarSymbol parameter(int mpIndex, int lvtIndex, Type t, MethodSymbol owner, Set<Name> exclude) { 2818 long flags = PARAMETER; 2819 Name argName; 2820 if (parameterAccessFlags != null && mpIndex < parameterAccessFlags.length 2821 && parameterAccessFlags[mpIndex] != 0) { 2822 flags |= parameterAccessFlags[mpIndex]; 2823 } 2824 if (parameterNameIndicesMp != null && mpIndex < parameterNameIndicesMp.length 2825 // if name_index is 0, then we might still get a name from the LocalVariableTable 2826 && parameterNameIndicesMp[mpIndex] != 0) { 2827 argName = optPoolEntry(parameterNameIndicesMp[mpIndex], poolReader::getName, names.empty); 2828 flags |= NAME_FILLED; 2829 } else if (parameterNameIndicesLvt != null && lvtIndex < parameterNameIndicesLvt.length 2830 && parameterNameIndicesLvt[lvtIndex] != 0) { 2831 argName = optPoolEntry(parameterNameIndicesLvt[lvtIndex], poolReader::getName, names.empty); 2832 flags |= NAME_FILLED; 2833 } else { 2834 String prefix = "arg"; 2835 while (true) { 2836 argName = names.fromString(prefix + exclude.size()); 2837 if (!exclude.contains(argName)) 2838 break; 2839 prefix += "$"; 2840 } 2841 } 2842 exclude.add(argName); 2843 return new ParamSymbol(flags, argName, t, owner); 2844 } 2845 2846 /** 2847 * skip n bytes 2848 */ 2849 void skipBytes(int n) { 2850 bp = bp + n; 2851 } 2852 2853 /** Skip a field or method 2854 */ 2855 void skipMember() { 2856 bp = bp + 6; 2857 char ac = nextChar(); 2858 for (int i = 0; i < ac; i++) { 2859 bp = bp + 2; 2860 int attrLen = nextInt(); 2861 bp = bp + attrLen; 2862 } 2863 } 2864 2865 void skipInnerClasses() { 2866 int n = nextChar(); 2867 for (int i = 0; i < n; i++) { 2868 nextChar(); 2869 nextChar(); 2870 nextChar(); 2871 nextChar(); 2872 } 2873 } 2874 2875 /** Enter type variables of this classtype and all enclosing ones in 2876 * `typevars'. 2877 */ 2878 protected void enterTypevars(Symbol sym, Type t) { 2879 if (t.getEnclosingType() != null) { 2880 if (!t.getEnclosingType().hasTag(TypeTag.NONE)) { 2881 enterTypevars(sym.owner, t.getEnclosingType()); 2882 } 2883 } else if (sym.kind == MTH && !sym.isStatic()) { 2884 enterTypevars(sym.owner, sym.owner.type); 2885 } 2886 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail) { 2887 typevars.enter(xs.head.tsym); 2888 } 2889 } 2890 2891 protected ClassSymbol enterClass(Name name) { 2892 return syms.enterClass(currentModule, name); 2893 } 2894 2895 protected ClassSymbol enterClass(Name name, TypeSymbol owner) { 2896 return syms.enterClass(currentModule, name, owner); 2897 } 2898 2899 /** Read contents of a given class symbol `c'. Both external and internal 2900 * versions of an inner class are read. 2901 */ 2902 void readClass(ClassSymbol c) { 2903 ClassType ct = (ClassType)c.type; 2904 2905 // allocate scope for members 2906 c.members_field = WriteableScope.create(c); 2907 2908 // prepare type variable table 2909 typevars = typevars.dup(currentOwner); 2910 if (ct.getEnclosingType().hasTag(CLASS)) 2911 enterTypevars(c.owner, ct.getEnclosingType()); 2912 2913 // read flags, or skip if this is an inner class 2914 long f = nextChar(); 2915 long flags = adjustClassFlags(f); 2916 if ((flags & MODULE) == 0) { 2917 if (c.owner.kind == PCK || c.owner.kind == ERR) c.flags_field = flags; 2918 // read own class name and check that it matches 2919 currentModule = c.packge().modle; 2920 ClassSymbol self = poolReader.getClass(nextChar()); 2921 if (c != self) { 2922 throw badClassFile("class.file.wrong.class", 2923 self.flatname); 2924 } 2925 } else { 2926 if (majorVersion < Version.V53.major) { 2927 throw badClassFile("anachronistic.module.info", 2928 Integer.toString(majorVersion), 2929 Integer.toString(minorVersion)); 2930 } 2931 c.flags_field = flags; 2932 if (c.owner.kind != MDL) { 2933 throw badClassFile("module.info.definition.expected"); 2934 } 2935 currentModule = (ModuleSymbol) c.owner; 2936 int this_class = nextChar(); 2937 // temp, no check on this_class 2938 } 2939 2940 // class attributes must be read before class 2941 // skip ahead to read class attributes 2942 int startbp = bp; 2943 nextChar(); 2944 char interfaceCount = nextChar(); 2945 bp += interfaceCount * 2; 2946 char fieldCount = nextChar(); 2947 for (int i = 0; i < fieldCount; i++) skipMember(); 2948 char methodCount = nextChar(); 2949 for (int i = 0; i < methodCount; i++) skipMember(); 2950 readClassAttrs(c); 2951 2952 if (!c.getPermittedSubclasses().isEmpty()) { 2953 c.flags_field |= SEALED; 2954 } 2955 2956 // reset and read rest of classinfo 2957 bp = startbp; 2958 int n = nextChar(); 2959 if ((flags & MODULE) != 0 && n > 0) { 2960 throw badClassFile("module.info.invalid.super.class"); 2961 } 2962 if (ct.supertype_field == null) 2963 ct.supertype_field = 2964 optPoolEntry(n, idx -> poolReader.getClass(idx).erasure(types), Type.noType); 2965 n = nextChar(); 2966 List<Type> is = List.nil(); 2967 for (int i = 0; i < n; i++) { 2968 Type _inter = poolReader.getClass(nextChar()).erasure(types); 2969 is = is.prepend(_inter); 2970 } 2971 if (ct.interfaces_field == null) 2972 ct.interfaces_field = is.reverse(); 2973 2974 Assert.check(fieldCount == nextChar()); 2975 for (int i = 0; i < fieldCount; i++) enterMember(c, readField()); 2976 Assert.check(methodCount == nextChar()); 2977 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod()); 2978 if (c.isRecord()) { 2979 for (RecordComponent rc: c.getRecordComponents()) { 2980 rc.accessor = lookupMethod(c, rc.name, List.nil()); 2981 } 2982 } 2983 typevars = typevars.leave(); 2984 } 2985 2986 private MethodSymbol lookupMethod(TypeSymbol tsym, Name name, List<Type> argtypes) { 2987 for (Symbol s : tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) { 2988 if (types.isSameTypes(s.type.getParameterTypes(), argtypes)) { 2989 return (MethodSymbol) s; 2990 } 2991 } 2992 return null; 2993 } 2994 2995 /** Read inner class info. For each inner/outer pair allocate a 2996 * member class. 2997 */ 2998 void readInnerClasses(ClassSymbol c) { 2999 int n = nextChar(); 3000 for (int i = 0; i < n; i++) { 3001 nextChar(); // skip inner class symbol 3002 int outerIdx = nextChar(); 3003 int nameIdx = nextChar(); 3004 ClassSymbol outer = optPoolEntry(outerIdx, poolReader::getClass, null); 3005 Name name = optPoolEntry(nameIdx, poolReader::getName, names.empty); 3006 if (name == null) name = names.empty; 3007 long flags = adjustClassFlags(nextChar()); 3008 if (outer != null) { // we have a member class 3009 if (name == names.empty) 3010 name = names.one; 3011 ClassSymbol member = enterClass(name, outer); 3012 if ((flags & STATIC) == 0) { 3013 ((ClassType)member.type).setEnclosingType(outer.type); 3014 if (member.erasure_field != null) 3015 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type)); 3016 } 3017 if (c == outer && member.owner == c) { 3018 member.flags_field = flags; 3019 enterMember(c, member); 3020 } 3021 } 3022 } 3023 } 3024 3025 /** Read a class definition from the bytes in buf. 3026 */ 3027 private void readClassBuffer(ClassSymbol c) throws IOException { 3028 int magic = nextInt(); 3029 if (magic != JAVA_MAGIC) 3030 throw badClassFile("illegal.start.of.class.file"); 3031 3032 minorVersion = nextChar(); 3033 majorVersion = nextChar(); 3034 int maxMajor = Version.MAX().major; 3035 int maxMinor = Version.MAX().minor; 3036 boolean previewClassFile = 3037 minorVersion == ClassFile.PREVIEW_MINOR_VERSION; 3038 if (majorVersion > maxMajor || 3039 majorVersion * 1000 + minorVersion < 3040 Version.MIN().major * 1000 + Version.MIN().minor) { 3041 if (majorVersion == (maxMajor + 1) && !previewClassFile) 3042 log.warning(Warnings.BigMajorVersion(currentClassFile, 3043 majorVersion, 3044 maxMajor)); 3045 else 3046 throw badClassFile("wrong.version", 3047 Integer.toString(majorVersion), 3048 Integer.toString(minorVersion), 3049 Integer.toString(maxMajor), 3050 Integer.toString(maxMinor)); 3051 } 3052 utf8validation = majorVersion < V48.major ? Convert.Validation.PREJDK14 : Convert.Validation.STRICT; 3053 3054 if (previewClassFile) { 3055 if (!preview.isEnabled()) { 3056 log.error(preview.disabledError(currentClassFile, majorVersion)); 3057 } else { 3058 preview.warnPreview(c.classfile, majorVersion); 3059 } 3060 } 3061 3062 poolReader = new PoolReader(this, names, syms); 3063 bp = poolReader.readPool(buf, bp); 3064 if (signatureBuffer.length < bp) { 3065 int ns = Integer.highestOneBit(bp) << 1; 3066 signatureBuffer = new byte[ns]; 3067 } 3068 readClass(c); 3069 } 3070 3071 public void readClassFile(ClassSymbol c) { 3072 currentOwner = c; 3073 currentClassFile = c.classfile; 3074 warnedAttrs.clear(); 3075 filling = true; 3076 target = null; 3077 repeatable = null; 3078 try { 3079 bp = 0; 3080 buf.reset(); 3081 try (InputStream input = c.classfile.openInputStream()) { 3082 buf.appendStream(input); 3083 } 3084 readClassBuffer(c); 3085 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) { 3086 List<Type> missing = missingTypeVariables; 3087 List<Type> found = foundTypeVariables; 3088 missingTypeVariables = List.nil(); 3089 foundTypeVariables = List.nil(); 3090 interimUses = List.nil(); 3091 interimProvides = List.nil(); 3092 filling = false; 3093 ClassType ct = (ClassType)currentOwner.type; 3094 ct.supertype_field = 3095 types.subst(ct.supertype_field, missing, found); 3096 ct.interfaces_field = 3097 types.subst(ct.interfaces_field, missing, found); 3098 ct.typarams_field = 3099 types.substBounds(ct.typarams_field, missing, found); 3100 for (List<Type> types = ct.typarams_field; types.nonEmpty(); types = types.tail) { 3101 types.head.tsym.type = types.head; 3102 } 3103 } else if (missingTypeVariables.isEmpty() != 3104 foundTypeVariables.isEmpty()) { 3105 Name name = missingTypeVariables.head.tsym.name; 3106 throw badClassFile("undecl.type.var", name); 3107 } 3108 3109 if ((c.flags_field & Flags.ANNOTATION) != 0) { 3110 c.setAnnotationTypeMetadata(new AnnotationTypeMetadata(c, new CompleterDeproxy(c, target, repeatable))); 3111 } else { 3112 c.setAnnotationTypeMetadata(AnnotationTypeMetadata.notAnAnnotationType()); 3113 } 3114 3115 if (c == currentModule.module_info) { 3116 if (interimUses.nonEmpty() || interimProvides.nonEmpty()) { 3117 Assert.check(currentModule.isCompleted()); 3118 currentModule.usesProvidesCompleter = 3119 new UsesProvidesCompleter(currentModule, interimUses, interimProvides); 3120 } else { 3121 currentModule.uses = List.nil(); 3122 currentModule.provides = List.nil(); 3123 } 3124 } 3125 } catch (IOException | ClosedFileSystemException ex) { 3126 throw badClassFile("unable.to.access.file", ex.toString()); 3127 } catch (ArrayIndexOutOfBoundsException ex) { 3128 throw badClassFile("bad.class.file", c.flatname); 3129 } finally { 3130 interimUses = List.nil(); 3131 interimProvides = List.nil(); 3132 missingTypeVariables = List.nil(); 3133 foundTypeVariables = List.nil(); 3134 filling = false; 3135 } 3136 } 3137 3138 /** We can only read a single class file at a time; this 3139 * flag keeps track of when we are currently reading a class 3140 * file. 3141 */ 3142 public boolean filling = false; 3143 3144 /* ********************************************************************** 3145 * Adjusting flags 3146 ***********************************************************************/ 3147 3148 long adjustFieldFlags(long flags) { 3149 return flags; 3150 } 3151 3152 long adjustMethodFlags(long flags) { 3153 if ((flags & ACC_BRIDGE) != 0) { 3154 flags &= ~ACC_BRIDGE; 3155 flags |= BRIDGE; 3156 } 3157 if ((flags & ACC_VARARGS) != 0) { 3158 flags &= ~ACC_VARARGS; 3159 flags |= VARARGS; 3160 } 3161 return flags; 3162 } 3163 3164 long adjustClassFlags(long flags) { 3165 if ((flags & ACC_MODULE) != 0) { 3166 flags &= ~ACC_MODULE; 3167 flags |= MODULE; 3168 } 3169 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded 3170 } 3171 3172 /** 3173 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile. 3174 * The attribute is only the last component of the original filename, so is unlikely 3175 * to be valid as is, so operations other than those to access the name throw 3176 * UnsupportedOperationException 3177 */ 3178 private static class SourceFileObject implements JavaFileObject { 3179 3180 /** The file's name. 3181 */ 3182 private final Name name; 3183 3184 public SourceFileObject(Name name) { 3185 this.name = name; 3186 } 3187 3188 @Override @DefinedBy(Api.COMPILER) 3189 public URI toUri() { 3190 try { 3191 return new URI(null, name.toString(), null); 3192 } catch (URISyntaxException e) { 3193 throw new PathFileObject.CannotCreateUriError(name.toString(), e); 3194 } 3195 } 3196 3197 @Override @DefinedBy(Api.COMPILER) 3198 public String getName() { 3199 return name.toString(); 3200 } 3201 3202 @Override @DefinedBy(Api.COMPILER) 3203 public JavaFileObject.Kind getKind() { 3204 return BaseFileManager.getKind(getName()); 3205 } 3206 3207 @Override @DefinedBy(Api.COMPILER) 3208 public InputStream openInputStream() { 3209 throw new UnsupportedOperationException(); 3210 } 3211 3212 @Override @DefinedBy(Api.COMPILER) 3213 public OutputStream openOutputStream() { 3214 throw new UnsupportedOperationException(); 3215 } 3216 3217 @Override @DefinedBy(Api.COMPILER) 3218 public CharBuffer getCharContent(boolean ignoreEncodingErrors) { 3219 throw new UnsupportedOperationException(); 3220 } 3221 3222 @Override @DefinedBy(Api.COMPILER) 3223 public Reader openReader(boolean ignoreEncodingErrors) { 3224 throw new UnsupportedOperationException(); 3225 } 3226 3227 @Override @DefinedBy(Api.COMPILER) 3228 public Writer openWriter() { 3229 throw new UnsupportedOperationException(); 3230 } 3231 3232 @Override @DefinedBy(Api.COMPILER) 3233 public long getLastModified() { 3234 throw new UnsupportedOperationException(); 3235 } 3236 3237 @Override @DefinedBy(Api.COMPILER) 3238 public boolean delete() { 3239 throw new UnsupportedOperationException(); 3240 } 3241 3242 @Override @DefinedBy(Api.COMPILER) 3243 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) { 3244 return true; // fail-safe mode 3245 } 3246 3247 @Override @DefinedBy(Api.COMPILER) 3248 public NestingKind getNestingKind() { 3249 return null; 3250 } 3251 3252 @Override @DefinedBy(Api.COMPILER) 3253 public Modifier getAccessLevel() { 3254 return null; 3255 } 3256 3257 /** 3258 * Check if two file objects are equal. 3259 * SourceFileObjects are just placeholder objects for the value of a 3260 * SourceFile attribute, and do not directly represent specific files. 3261 * Two SourceFileObjects are equal if their names are equal. 3262 */ 3263 @Override 3264 public boolean equals(Object other) { 3265 if (this == other) 3266 return true; 3267 return (other instanceof SourceFileObject sourceFileObject) 3268 && name.equals(sourceFileObject.name); 3269 } 3270 3271 @Override 3272 public int hashCode() { 3273 return name.hashCode(); 3274 } 3275 } 3276 3277 private class CompleterDeproxy implements AnnotationTypeCompleter { 3278 ClassSymbol proxyOn; 3279 CompoundAnnotationProxy target; 3280 CompoundAnnotationProxy repeatable; 3281 3282 public CompleterDeproxy(ClassSymbol c, CompoundAnnotationProxy target, 3283 CompoundAnnotationProxy repeatable) 3284 { 3285 this.proxyOn = c; 3286 this.target = target; 3287 this.repeatable = repeatable; 3288 } 3289 3290 @Override 3291 public void complete(ClassSymbol sym) { 3292 Assert.check(proxyOn == sym); 3293 Attribute.Compound theTarget = null, theRepeatable = null; 3294 AnnotationDeproxy deproxy; 3295 3296 try { 3297 if (target != null) { 3298 deproxy = new AnnotationDeproxy(proxyOn); 3299 theTarget = deproxy.deproxyCompound(target); 3300 } 3301 3302 if (repeatable != null) { 3303 deproxy = new AnnotationDeproxy(proxyOn); 3304 theRepeatable = deproxy.deproxyCompound(repeatable); 3305 } 3306 } catch (Exception e) { 3307 throw new CompletionFailure(sym, 3308 () -> ClassReader.this.diagFactory.fragment(Fragments.ExceptionMessage(e.getMessage())), 3309 dcfh); 3310 } 3311 3312 sym.getAnnotationTypeMetadata().setTarget(theTarget); 3313 sym.getAnnotationTypeMetadata().setRepeatable(theRepeatable); 3314 } 3315 } 3316 3317 private class ProxyType extends Type { 3318 3319 private final Name name; 3320 3321 public ProxyType(int index) { 3322 super(syms.noSymbol, List.nil()); 3323 this.name = poolReader.getName(index); 3324 } 3325 3326 @Override 3327 public TypeTag getTag() { 3328 return TypeTag.NONE; 3329 } 3330 3331 public Type resolve() { 3332 return name.map(ClassReader.this::sigToType); 3333 } 3334 3335 @Override @DefinedBy(Api.LANGUAGE_MODEL) 3336 public String toString() { 3337 return "<ProxyType>"; 3338 } 3339 3340 } 3341 3342 private static final class InterimUsesDirective { 3343 public final Name service; 3344 3345 public InterimUsesDirective(Name service) { 3346 this.service = service; 3347 } 3348 3349 } 3350 3351 private static final class InterimProvidesDirective { 3352 public final Name service; 3353 public final List<Name> impls; 3354 3355 public InterimProvidesDirective(Name service, List<Name> impls) { 3356 this.service = service; 3357 this.impls = impls; 3358 } 3359 3360 } 3361 3362 private final class UsesProvidesCompleter implements Completer { 3363 private final ModuleSymbol currentModule; 3364 private final List<InterimUsesDirective> interimUsesCopy; 3365 private final List<InterimProvidesDirective> interimProvidesCopy; 3366 3367 public UsesProvidesCompleter(ModuleSymbol currentModule, List<InterimUsesDirective> interimUsesCopy, List<InterimProvidesDirective> interimProvidesCopy) { 3368 this.currentModule = currentModule; 3369 this.interimUsesCopy = interimUsesCopy; 3370 this.interimProvidesCopy = interimProvidesCopy; 3371 } 3372 3373 @Override 3374 public void complete(Symbol sym) throws CompletionFailure { 3375 ListBuffer<Directive> directives = new ListBuffer<>(); 3376 directives.addAll(currentModule.directives); 3377 ListBuffer<UsesDirective> uses = new ListBuffer<>(); 3378 for (InterimUsesDirective interim : interimUsesCopy) { 3379 UsesDirective d = new UsesDirective(syms.enterClass(currentModule, interim.service)); 3380 uses.add(d); 3381 directives.add(d); 3382 } 3383 currentModule.uses = uses.toList(); 3384 ListBuffer<ProvidesDirective> provides = new ListBuffer<>(); 3385 for (InterimProvidesDirective interim : interimProvidesCopy) { 3386 ListBuffer<ClassSymbol> impls = new ListBuffer<>(); 3387 for (Name impl : interim.impls) { 3388 impls.append(syms.enterClass(currentModule, impl)); 3389 } 3390 ProvidesDirective d = new ProvidesDirective(syms.enterClass(currentModule, interim.service), 3391 impls.toList()); 3392 provides.add(d); 3393 directives.add(d); 3394 } 3395 currentModule.provides = provides.toList(); 3396 currentModule.directives = directives.toList(); 3397 } 3398 } 3399 }