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