1 /*
  2  * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 /**
 27  * <h2>Provides classfile parsing, generation, and transformation library.</h2>
 28  * The {@code java.lang.classfile} package contains API models for reading,
 29  * writing, and modifying Java class files, as specified in Chapter {@jvms 4} of
 30  * the <cite>Java Virtual Machine Specification</cite>.  This package, {@link
 31  * java.lang.classfile.attribute}, {@link java.lang.classfile.constantpool},
 32  * and {@link java.lang.classfile.instruction} form the Class-File API.
 33  *
 34  * <h2>Reading classfiles</h2>
 35  * The main class for reading classfiles is {@link ClassModel}; we
 36  * convert bytes into a {@link ClassModel} with {@link
 37  * ClassFile#parse(byte[])}:
 38  *
 39  * {@snippet lang=java :
 40  * ClassModel cm = ClassFile.of().parse(bytes);
 41  * }
 42  *
 43  * There are several additional overloads of {@code parse} that let you specify
 44  * various processing options.
 45  * <p>
 46  * A {@link ClassModel} is an immutable description of a class
 47  * file.  It provides accessor methods to get at class metadata (e.g., {@link
 48  * ClassModel#thisClass()}, {@link ClassModel#flags()}),
 49  * as well as subordinate classfile entities ({@link ClassModel#fields()},
 50  * {@link ClassModel#attributes()}). A {@link
 51  * ClassModel} is inflated lazily; most parts of the classfile are
 52  * not parsed until they are actually needed.  Due to the laziness, these models
 53  * may not be thread safe.  Additionally, invocations to accessor methods on
 54  * models may lead to {@link IllegalArgumentException} due to malformed {@code
 55  * class} file format, as parsing happens lazily.
 56  * <p>
 57  * We can enumerate the names of the fields and methods in a class by:
 58  * {@snippet lang="java" class="PackageSnippets" region="enumerateFieldsMethods1"}
 59  * <p>
 60  * When we enumerate the methods, we get a {@link MethodModel} for each method; like a
 61  * {@code ClassModel}, it gives us access to method metadata and
 62  * the ability to descend into subordinate entities such as the bytecodes of the
 63  * method body. In this way, a {@code ClassModel} is the root of a
 64  * tree, with children for fields, methods, and attributes, and {@code MethodModel} in
 65  * turn has its own children (attributes, {@code CodeModel}, etc.)
 66  * <p>
 67  * Methods like {@link ClassModel#methods} allows us to traverse the class structure
 68  * explicitly, going straight to the parts we are interested in.  This is useful
 69  * for certain kinds of analysis, but if we wanted to process the whole
 70  * classfile, we may want something more organized.  A {@link
 71  * ClassModel} also provides us with a view of the classfile as a
 72  * series of class <em>elements</em>, which may include methods, fields, attributes,
 73  * and more, and which can be distinguished with pattern matching.  We could
 74  * rewrite the above example as:
 75  * {@snippet lang="java" class="PackageSnippets" region="enumerateFieldsMethods2"}
 76  * <p>
 77  * The models returned as elements from traversing {@code ClassModel} can in
 78  * turn be sources of elements.  If we wanted to
 79  * traverse a classfile and enumerate all the classes for which we access fields
 80  * and methods, we can pick out the class elements that describe methods, then
 81  * in turn pick out the method elements that describe the code attribute, and
 82  * finally pick out the code elements that describe field access and invocation
 83  * instructions:
 84  * {@snippet lang="java" class="PackageSnippets" region="gatherDependencies1"}
 85  * <p>
 86  * This same query could alternately be processed as a stream pipeline over
 87  * class elements:
 88  * {@snippet lang="java" class="PackageSnippets" region="gatherDependencies2"}
 89  *
 90  * <h3>Models and elements</h3>
 91  * The view of classfiles presented by this API is framed in terms of
 92  * <em>models</em> and <em>elements</em>.  Models represent complex structures,
 93  * such as classes, methods, fields, record elements, or the code body of a
 94  * method.  Models can be explored either via random-access navigation (such as
 95  * the {@link ClassModel#methods()} accessor) or as a linear
 96  * sequence of <em>elements</em>. (Elements can in turn also be models; a {@link
 97  * FieldModel} is also an element of a class.) For each model type
 98  * (e.g., {@link MethodModel}), there is a corresponding element
 99  * type ({@link MethodElement}).  Models and elements are immutable
100  * and are inflated lazily so creating a model does not necessarily require
101  * processing its entire content.
102  *
103  * <h3>The constant pool</h3>
104  * Much of the interesting content in a classfile lives in the <em>constant
105  * pool</em>. {@link ClassModel} provides a lazily-inflated,
106  * read-only view of the constant pool via {@link ClassModel#constantPool()}.
107  * Descriptions of classfile content is often exposed in the form of various
108  * subtypes of {@link PoolEntry}, such as {@link
109  * ClassEntry} or {@link Utf8Entry}.
110  * <p>
111  * Constant pool entries are also exposed through models and elements; in the
112  * above traversal example, the {@link InvokeInstruction}
113  * element exposed a method for {@code owner} that corresponds to a {@code
114  * Constant_Class_info} entry in the constant pool.
115  *
116  * <h3>Attributes</h3>
117  * Much of the contents of a classfile is stored in attributes; attributes are
118  * found on classes, methods, fields, record components, and on the {@code Code}
119  * attribute.  Most attributes are surfaced as elements; for example, {@link
120  * SignatureAttribute} is a {@link
121  * ClassElement}, {@link MethodElement}, and {@link
122  * FieldElement} since it can appear in all of those places, and is
123  * included when iterating the elements of the corresponding model.
124  * <p>
125  * Some attributes are not surfaced as elements; these are attributes that are
126  * tightly coupled to -- and logically part of -- other parts of the class file.
127  * These include the {@code BootstrapMethods}, {@code LineNumberTable}, {@code
128  * StackMapTable}, {@code LocalVariableTable}, and {@code
129  * LocalVariableTypeTable} attributes.  These are processed by the library and
130  * treated as part of the structure they are coupled to (the entries of the
131  * {@code BootstrapMethods} attribute are treated as part of the constant pool;
132  * line numbers and local variable metadata are modeled as elements of {@link
133  * CodeModel}.)
134  * <p>
135  * The {@code Code} attribute, in addition to being modeled as a {@link
136  * MethodElement}, is also a model in its own right ({@link
137  * CodeModel}) due to its complex structure.
138  * <p>
139  * Each standard attribute has an interface (in {@code java.lang.classfile.attribute})
140  * which exposes the contents of the attribute and provides factories to
141  * construct the attribute.  For example, the {@code Signature} attribute is
142  * defined by the {@link SignatureAttribute} class, and
143  * provides accessors for {@link SignatureAttribute#signature()}
144  * as well as factories taking {@link Utf8Entry} or
145  * {@link String}.
146  *
147  * <h3>Custom attributes</h3>
148  * Attributes are converted between their classfile form and their corresponding
149  * object form via an {@link AttributeMapper}.  An {@code
150  * AttributeMapper} provides the
151  * {@link AttributeMapper#readAttribute(AttributedElement,
152  * ClassReader, int)} method for mapping from the classfile format
153  * to an attribute instance, and the
154  * {@link AttributeMapper#writeAttribute(BufWriter,
155  * Attribute)} method for mapping back to the classfile format.  It also
156  * contains metadata including the attribute name, the set of classfile entities
157  * where the attribute is applicable, and whether multiple attributes of the
158  * same kind are allowed on a single entity.
159  * <p>
160  * There are built-in attribute mappers (in {@link Attributes}) for
161  * each of the attribute types defined in section {@jvms 4.7} of <cite>The Java Virtual
162  * Machine Specification</cite>, as well as several common nonstandard attributes used by the
163  * JDK such as {@code CharacterRangeTable}.
164  * <p>
165  * Unrecognized attributes are delivered as elements of type {@link
166  * UnknownAttribute}, which provide access only to the
167  * {@code byte[]} contents of the attribute.
168  * <p>
169  * For nonstandard attributes, user-provided attribute mappers can be specified
170  * through the use of the {@link
171  * ClassFile.AttributeMapperOption#of(Function)}}
172  * classfile option.  Implementations of custom attributes should extend {@link
173  * CustomAttribute}.
174  *
175  * <h3 id="options">Options</h3>
176  * <p>
177  * {@link ClassFile#of(ClassFile.Option[])}
178  * accepts a list of options.  {@link ClassFile.Option} is a base interface
179  * for some statically enumerated options, as well as factories for more complex options,
180  * including:
181  * <ul>
182  *   <li>{@link ClassFile.AttributeMapperOption#of(Function)}
183  * -- specify format of custom attributes</li>
184  *   <li>{@link ClassFile.AttributesProcessingOption}
185  * -- unrecognized or problematic original attributes (default is {@code PASS_ALL_ATTRIBUTES})</li>
186  *   <li>{@link ClassFile.ClassHierarchyResolverOption#of(ClassHierarchyResolver)}
187  * -- specify a custom class hierarchy resolver used by stack map generation</li>
188  *   <li>{@link ClassFile.ConstantPoolSharingOption}}
189  * -- share constant pool when transforming (default is {@code SHARED_POOL})</li>
190  *   <li>{@link ClassFile.DeadCodeOption}}
191  * -- patch out unreachable code (default is {@code PATCH_DEAD_CODE})</li>
192  *   <li>{@link ClassFile.DeadLabelsOption}}
193  * -- filter unresolved labels (default is {@code FAIL_ON_DEAD_LABELS})</li>
194  *   <li>{@link ClassFile.DebugElementsOption}
195  * -- processing of debug information, such as local variable metadata (default is {@code PASS_DEBUG}) </li>
196  *   <li>{@link ClassFile.LineNumbersOption}
197  * -- processing of line numbers (default is {@code PASS_LINE_NUMBERS}) </li>
198  *   <li>{@link ClassFile.ShortJumpsOption}
199  * -- automatically rewrite short jumps to long when necessary (default is {@code FIX_SHORT_JUMPS})</li>
200  *   <li>{@link ClassFile.StackMapsOption}
201  * -- generate stackmaps (default is {@code STACK_MAPS_WHEN_REQUIRED})</li>
202  * </ul>
203  * <p>
204  * {@link ClassFile.AttributeMapperOption} and {@link ClassFile.ClassHierarchyResolverOption}
205  * are critical to the correctness of {@code class} file parsing and generation.
206  * The attribute mapper is required to parse custom attributes.  A correct
207  * resolver is required to generate {@code class} files that refer to classes
208  * not available to the system class loader in its bytecode, or in corner cases,
209  * when generation wishes to avoid loading system classes, such as in agents.
210  * <p>
211  * Most options allow you to request that certain parts of the classfile be
212  * skipped during traversal, such as debug information or unrecognized
213  * attributes.  Some options allow you to suppress generation of portions of the
214  * classfile, such as stack maps.  Many of these options are to access
215  * performance tradeoffs; processing debug information and line numbers has a
216  * cost (both in writing and reading.)  If you don't need this information, you
217  * can suppress it with options to gain some performance.
218  *
219  * <h2>Writing classfiles</h2>
220  * ClassFile generation is accomplished through <em>builders</em>.  For each
221  * entity type that has a model, there is also a corresponding builder type;
222  * classes are built through {@link ClassBuilder}, methods through
223  * {@link MethodBuilder}, etc.
224  * <p>
225  * Rather than creating builders directly, builders are provided as an argument
226  * to a user-provided lambda.  To generate the familiar "hello world" program,
227  * we ask for a class builder, and use that class builder to create method
228  * builders for the constructor and {@code main} method, and in turn use the
229  * method builders to create a {@code Code} attribute and use the code builders
230  * to generate the instructions:
231  * {@snippet lang="java" class="PackageSnippets" region="helloWorld1"}
232  * <p>
233  * The convenience methods {@code ClassBuilder.buildMethodBody} allows us to ask
234  * {@link ClassBuilder} to create code builders to build method bodies directly,
235  * skipping the method builder custom lambda:
236  * {@snippet lang="java" class="PackageSnippets" region="helloWorld2"}
237  * <p>
238  * Builders often support multiple ways of expressing the same entity at
239  * different levels of abstraction.  For example, the {@code invokevirtual}
240  * instruction invoking {@code println} could have been generated with {@link
241  * CodeBuilder#invokevirtual(ClassDesc,
242  * String, MethodTypeDesc) CodeBuilder.invokevirtual}, {@link
243  * CodeBuilder#invoke(Opcode,
244  * ClassDesc, String, MethodTypeDesc,
245  * boolean) CodeBuilder.invoke}, or {@link
246  * CodeBuilder#with(ClassFileElement)
247  * CodeBuilder.with}.
248  * <p>
249  * The convenience method {@code CodeBuilder.invokevirtual} behaves as if it calls
250  * the convenience method {@code CodeBuilder.invoke}, which in turn behaves
251  * as if it calls method {@code CodeBuilder.with}. This composing of method calls on the
252  * builder enables the composing of transforms (as described later).
253  * <p>
254  * Unless otherwise noted, passing a {@code null} argument to a constructor
255  * or method of any Class-File API class or interface will cause a {@link
256  * NullPointerException} to be thrown. Additionally,
257  * invoking a method with an array or collection containing a {@code null} element
258  * will cause a {@code NullPointerException}, unless otherwise specified. </p>
259  *
260  * <h3>Symbolic information</h3>
261  * To describe symbolic information for classes and types, the API uses the
262  * nominal descriptor abstractions from {@link java.lang.constant} such as {@link
263  * ClassDesc} and {@link MethodTypeDesc},
264  * which is less error-prone than using raw strings.
265  * <p>
266  * If a constant pool entry has a nominal representation then it provides a
267  * method returning the corresponding nominal descriptor type e.g.
268  * method {@link ClassEntry#asSymbol} returns
269  * {@code ClassDesc}.
270  * <p>
271  * Where appropriate builders provide two methods for building an element with
272  * symbolic information, one accepting nominal descriptors, and the other
273  * accepting constant pool entries.
274  *
275  * <h3>Consistency checks, syntax checks and verification</h3>
276  * No consistency checks are performed while building or transforming classfiles
277  * (except for null arguments checks). All builders and classfile elements factory
278  * methods accepts the provided information without implicit validation.
279  * However, fatal inconsistencies (like for example invalid code sequence or
280  * unresolved labels) affects internal tools and may cause exceptions later in
281  * the classfile building process.  These fatal exceptions are thrown as
282  * {@link IllegalArgumentException}.
283  * <p>
284  * Using nominal descriptors assures the right serial form is applied by the
285  * ClassFile API library based on the actual context. Also these nominal
286  * descriptors are validated during their construction, so it is not possible to
287  * create them with invalid content by mistake. Following example pass class
288  * name to the {@link ClassDesc#of} method for validation
289  * and the library performs automatic conversion to the right internal form of
290  * the class name when serialized in the constant pool as a class entry.
291  * {@snippet lang=java :
292  * var validClassEntry = constantPoolBuilder.classEntry(ClassDesc.of("mypackage.MyClass"));
293  * }
294  * <p>
295  * On the other hand it is possible to use builders methods and factories accepting
296  * constant pool entries directly. Constant pool entries can be constructed also
297  * directly from raw values, with no additional conversions or validations.
298  * Following example uses intentionally wrong class name form and it is applied
299  * without any validation or conversion.
300  * {@snippet lang=java :
301  * var invalidClassEntry = constantPoolBuilder.classEntry(
302  *                             constantPoolBuilder.utf8Entry("mypackage.MyClass"));
303  * }
304  * <p>
305  * More complex verification of a classfile can be achieved by invocation of
306  * {@link ClassFile#verify}.
307  *
308  * <h2>Transforming classfiles</h2>
309  * ClassFile Processing APIs are most frequently used to combine reading and
310  * writing into transformation, where a classfile is read, localized changes are
311  * made, but much of the classfile is passed through unchanged.  For each kind
312  * of builder, {@code XxxBuilder} has a method {@code with(XxxElement)} so that
313  * elements that we wish to pass through unchanged can be handed directly back
314  * to the builder.
315  * <p>
316  * If we wanted to strip out methods whose names starts with "debug", we could
317  * get an existing {@link ClassModel}, build a new classfile that
318  * provides a {@link ClassBuilder}, iterate the elements of the
319  * original {@link ClassModel}, and pass through all of them to
320  * the builder except the methods we want to drop:
321  * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods1"}
322  * <p>
323  * This hands every class element, except for those corresponding to methods
324  * whose names start with {@code debug}, back to the builder.  Transformations
325  * can of course be more complicated, diving into method bodies and instructions
326  * and transforming those as well, but the same structure is repeated at every
327  * level, since every entity has corresponding model, builder, and element
328  * abstractions.
329  * <p>
330  * Transformation can be viewed as a "flatMap" operation on the sequence of
331  * elements; for every element, we could pass it through unchanged, drop it, or
332  * replace it with one or more elements.  Because transformation is such a
333  * common operation on classfiles, each model type has a corresponding {@code
334  * XxxTransform} type (which describes a transform on a sequence of {@code
335  * XxxElement}) and each builder type has {@code transformYyy} methods for transforming
336  * its child models.  A transform is simply a functional interface that takes a
337  * builder and an element, and an implementation "flatMap"s elements
338  * into the builder.  We could express the above as:
339  * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods2"}
340  * <p>
341  * {@code ClassTransform.dropping} convenience method allow us to simplify the same
342  * transformation construction and express the above as:
343  * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods3"}
344  *
345  * <h3>Lifting transforms</h3>
346  * While the example using transformations are only slightly shorter, the
347  * advantage of expressing transformation in this way is that the transform
348  * operations can be more easily combined.  Suppose we want to redirect
349  * invocations of static methods on {@code Foo} to the corresponding method on
350  * {@code Bar} instead.  We could express this as a transformation on {@link
351  * CodeElement}:
352  * {@snippet lang="java" class="PackageSnippets" region="fooToBarTransform"}
353  * <p>
354  * We can then <em>lift</em> this transformation on code elements into a
355  * transformation on method elements.  This intercepts method elements that
356  * correspond to a {@code Code} attribute, dives into its code elements, and
357  * applies the code transform to them, and passes other method elements through
358  * unchanged:
359  * {@snippet lang=java :
360  * MethodTransform mt = MethodTransform.transformingCode(fooToBar);
361  * }
362  * <p>
363  * and further lift the transform on method elements into one on class
364  * elements:
365  * {@snippet lang=java :
366  * ClassTransform ct = ClassTransform.transformingMethods(mt);
367  * }
368  * <p>
369  * or lift the code transform into the class transform directly:
370  * {@snippet lang=java :
371  * ClassTransform ct = ClassTransform.transformingMethodBodies(fooToBar);
372  * }
373  * <p>
374  * and then transform the classfile:
375  * {@snippet lang=java :
376  * var cc = ClassFile.of();
377  * byte[] newBytes = cc.transformClass(cc.parse(bytes), ct);
378  * }
379  * <p>
380  * This is much more concise (and less error-prone) than the equivalent
381  * expressed by traversing the classfile structure directly:
382  * {@snippet lang="java" class="PackageSnippets" region="fooToBarUnrolled"}
383  *
384  * <h3>Composing transforms</h3>
385  * Transforms on the same type of element can be composed in sequence, where the
386  * output of the first is fed to the input of the second.  Suppose we want to
387  * instrument all method calls, where we print the name of a method before
388  * calling it:
389  * {@snippet lang="java" class="PackageSnippets" region="instrumentCallsTransform"}
390  * <p>
391  * Then we can compose {@code fooToBar} and {@code instrumentCalls} with {@link
392  * CodeTransform#andThen(CodeTransform)}:
393  *
394  * {@snippet lang=java :
395  * var cc = ClassFile.of();
396  * byte[] newBytes = cc.transformClass(cc.parse(bytes),
397  *                                ClassTransform.transformingMethods(
398  *                                    MethodTransform.transformingCode(
399  *                                        fooToBar.andThen(instrumentCalls))));
400  * }
401  *
402  * Transform {@code instrumentCalls} will receive all code elements produced by
403  * transform {@code forToBar}, either those code elements from the original classfile
404  * or replacements (replacing static invocations to {@code Foo} with those to {@code Bar}).
405  *
406  * <h3>Constant pool sharing</h3>
407  * Transformation doesn't merely handle the logistics of reading, transforming
408  * elements, and writing.  Most of the time when we are transforming a
409  * classfile, we are making relatively minor changes.  To optimize such cases,
410  * transformation seeds the new classfile with a copy of the constant pool from
411  * the original classfile; this enables significant optimizations (methods and
412  * attributes that are not transformed can be processed by bulk-copying their
413  * bytes, rather than parsing them and regenerating their contents.)  If
414  * constant pool sharing is not desired it can be suppressed
415  * with the {@link ClassFile.ConstantPoolSharingOption} option.
416  * Such suppression may be beneficial when transformation removes many elements,
417  * resulting in many unreferenced constant pool entries.
418  *
419  * <h3>Transformation handling of unknown classfile elements</h3>
420  * Custom classfile transformations might be unaware of classfile elements
421  * introduced by future JDK releases. To achieve deterministic stability,
422  * classfile transforms interested in consuming all classfile elements should be
423  * implemented strictly to throw exceptions if running on a newer JDK, if the
424  * transformed class file is a newer version, or if a new and unknown classfile
425  * element appears. As for example in the following strict compatibility-checking
426  * transformation snippets:
427  * {@snippet lang="java" class="PackageSnippets" region="strictTransform1"}
428  * {@snippet lang="java" class="PackageSnippets" region="strictTransform2"}
429  * {@snippet lang="java" class="PackageSnippets" region="strictTransform3"}
430  * <p>
431  * Conversely, classfile transforms that are only interested in consuming a portion
432  * of classfile elements do not need to concern with new and unknown classfile
433  * elements and may pass them through. Following example shows such future-proof
434  * code transformation:
435  * {@snippet lang="java" class="PackageSnippets" region="benevolentTransform"}
436  *
437  * <h2>API conventions</h2>
438  * <p>
439  * The API is largely derived from a <a href="#data_model"><em>data model</em></a>
440  * for the classfile format, which defines each element kind (which includes models and
441  * attributes) and its properties.  For each element kind, there is a
442  * corresponding interface to describe that element, and factory methods to
443  * create that element.  Some element kinds also have convenience methods on the
444  * corresponding builder (e.g., {@link
445  * CodeBuilder#invokevirtual(ClassDesc,
446  * String, MethodTypeDesc)}).
447  * <p>
448  * Most symbolic information in elements is represented by constant pool entries
449  * (for example, the owner of a field is represented by a {@link
450  * ClassEntry}.) Factories and builders also
451  * accept nominal descriptors from {@link java.lang.constant} (e.g., {@link
452  * ClassDesc}.)
453  *
454  * <h2><a id="data_model"></a>Data model</h2>
455  * We define each kind of element by its name, an optional arity indicator (zero
456  * or more, zero or one, exactly one), and a list of components.  The elements
457  * of a class are fields, methods, and the attributes that can appear on
458  * classes:
459  *
460  * {@snippet lang="text" :
461  * ClassElement =
462  *     FieldModel*(UtfEntry name, Utf8Entry descriptor)
463  *     | MethodModel*(UtfEntry name, Utf8Entry descriptor)
464  *     | ModuleAttribute?(int flags, ModuleEntry moduleName, UtfEntry moduleVersion,
465  *                        List<ModuleRequireInfo> requires, List<ModuleOpenInfo> opens,
466  *                        List<ModuleExportInfo> exports, List<ModuleProvidesInfo> provides,
467  *                        List<ClassEntry> uses)
468  *     | ModulePackagesAttribute?(List<PackageEntry> packages)
469  *     | ModuleTargetAttribute?(Utf8Entry targetPlatform)
470  *     | ModuleHashesAttribute?(Utf8Entry algorithm, List<HashInfo> hashes)
471  *     | ModuleResolutionAttribute?(int resolutionFlags)
472  *     | SourceFileAttribute?(Utf8Entry sourceFile)
473  *     | SourceDebugExtensionsAttribute?(byte[] contents)
474  *     | CompilationIDAttribute?(Utf8Entry compilationId)
475  *     | SourceIDAttribute?(Utf8Entry sourceId)
476  *     | NestHostAttribute?(ClassEntry nestHost)
477  *     | NestMembersAttribute?(List<ClassEntry> nestMembers)
478  *     | RecordAttribute?(List<RecordComponent> components)
479  *     | EnclosingMethodAttribute?(ClassEntry className, NameAndTypeEntry method)
480  *     | InnerClassesAttribute?(List<InnerClassInfo> classes)
481  *     | PermittedSubclassesAttribute?(List<ClassEntry> permittedSubclasses)
482  *     | LoadableDescriptorsAttribute?(List<Utf8Entry> loadableDescriptors)
483  *     | DeclarationElement*
484  * }
485  *
486  * where {@code DeclarationElement} are the elements that are common to all declarations
487  * (classes,  methods, fields) and so are factored out:
488  *
489  * {@snippet lang="text" :
490  * DeclarationElement =
491  *     SignatureAttribute?(Utf8Entry signature)
492  *     | SyntheticAttribute?()
493  *     | DeprecatedAttribute?()
494  *     | RuntimeInvisibleAnnotationsAttribute?(List<Annotation> annotations)
495  *     | RuntimeVisibleAnnotationsAttribute?(List<Annotation> annotations)
496  *     | CustomAttribute*
497  *     | UnknownAttribute*
498  * }
499  *
500  * Fields and methods are models with their own elements.  The elements of fields
501  * and methods are fairly simple; most of the complexity of methods lives in the
502  * {@link CodeModel} (which models the {@code Code} attribute
503  * along with the code-related attributes: stack map table, local variable table,
504  * line number table, etc.)
505  *
506  * {@snippet lang="text" :
507  * FieldElement =
508  *     DeclarationElement
509  *     | ConstantValueAttribute?(ConstantValueEntry constant)
510  *
511  * MethodElement =
512  *     DeclarationElement
513  *     | CodeModel?()
514  *     | AnnotationDefaultAttribute?(ElementValue defaultValue)
515  *     | MethodParametersAttribute?(List<MethodParameterInfo> parameters)
516  *     | ExceptionsAttribute?(List<ClassEntry> exceptions)
517  * }
518  *
519  * {@link CodeModel} is unique in that its elements are <em>ordered</em>.
520  * Elements of {@code Code} include ordinary bytecodes, as well as a number of pseudo-instructions
521  * representing branch targets, line number metadata, local variable metadata, and
522  * catch blocks.
523  *
524  * {@snippet lang="text" :
525  * CodeElement = Instruction | PseudoInstruction
526  *
527  * Instruction =
528  *     LoadInstruction(TypeKind type, int slot)
529  *     | StoreInstruction(TypeKind type, int slot)
530  *     | IncrementInstruction(int slot, int constant)
531  *     | BranchInstruction(Opcode opcode, Label target)
532  *     | LookupSwitchInstruction(Label defaultTarget, List<SwitchCase> cases)
533  *     | TableSwitchInstruction(Label defaultTarget, int low, int high,
534  *                              List<SwitchCase> cases)
535  *     | ReturnInstruction(TypeKind kind)
536  *     | ThrowInstruction()
537  *     | FieldInstruction(Opcode opcode, FieldRefEntry field)
538  *     | InvokeInstruction(Opcode opcode, MemberRefEntry method, boolean isInterface)
539  *     | InvokeDynamicInstruction(InvokeDynamicEntry invokedynamic)
540  *     | NewObjectInstruction(ClassEntry className)
541  *     | NewReferenceArrayInstruction(ClassEntry componentType)
542  *     | NewPrimitiveArrayInstruction(TypeKind typeKind)
543  *     | NewMultiArrayInstruction(ClassEntry componentType, int dims)
544  *     | ArrayLoadInstruction(Opcode opcode)
545  *     | ArrayStoreInstruction(Opcode opcode)
546  *     | TypeCheckInstruction(Opcode opcode, ClassEntry className)
547  *     | ConvertInstruction(TypeKind from, TypeKind to)
548  *     | OperatorInstruction(Opcode opcode)
549  *     | ConstantInstruction(ConstantDesc constant)
550  *     | StackInstruction(Opcode opcode)
551  *     | MonitorInstruction(Opcode opcode)
552  *     | NopInstruction()
553  *
554  * PseudoInstruction =
555  *     | LabelTarget(Label label)
556  *     | LineNumber(int line)
557  *     | ExceptionCatch(Label tryStart, Label tryEnd, Label handler, ClassEntry exception)
558  *     | LocalVariable(int slot, UtfEntry name, Utf8Entry type, Label startScope, Label endScope)
559  *     | LocalVariableType(int slot, Utf8Entry name, Utf8Entry type, Label startScope, Label endScope)
560  *     | CharacterRange(int rangeStart, int rangeEnd, int flags, Label startScope, Label endScope)
561  * }
562  *
563  * @since 24
564  */
565 package java.lang.classfile;
566 
567 import java.lang.classfile.attribute.SignatureAttribute;
568 import java.lang.classfile.attribute.UnknownAttribute;
569 import java.lang.classfile.constantpool.ClassEntry;
570 import java.lang.classfile.constantpool.PoolEntry;
571 import java.lang.classfile.constantpool.Utf8Entry;
572 import java.lang.classfile.instruction.InvokeInstruction;
573 import java.lang.constant.ClassDesc;
574 import java.lang.constant.MethodTypeDesc;
575 import java.util.function.Function;