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.
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  * The Class-File API performs checks to ensure arguments are representable in
277  * the {@code class} file format.  A value that is lost when it is built to a
278  * {@code class} file and re-parsed to a model is rejected with an {@link
279  * IllegalArgumentException}.  For example, a negative value or a value over
280  * {@code 65535} is lost when built to a {@link ##u2 u2} item, with
281  * the range {@code [0, 65535]}.  In particular, any variable-sized table
282  * exceeding its maximum representable size is rejected.
283  * <p>
284  * No consistency checks are performed while building or transforming classfiles
285  * (except for null and representable arguments checks). All builders and
286  * classfile elements factory methods accepts the provided information without
287  * implicit validation, as long as they are representable in the {@code class}
288  * file format.  However, fatal inconsistencies (like invalid code sequence or
289  * unresolved labels) affects internal tools and may cause exceptions later in
290  * the classfile building process.  These fatal exceptions are thrown as
291  * {@code IllegalArgumentException}.
292  * <p>
293  * Using nominal descriptors assures the right serial form is applied by the
294  * ClassFile API library based on the actual context. Also these nominal
295  * descriptors are validated during their construction, so it is not possible to
296  * create them with invalid content by mistake. Following example pass class
297  * name to the {@link ClassDesc#of} method for validation
298  * and the library performs automatic conversion to the right internal form of
299  * the class name when serialized in the constant pool as a class entry.
300  * {@snippet lang=java :
301  * var validClassEntry = constantPoolBuilder.classEntry(ClassDesc.of("mypackage.MyClass"));
302  * }
303  * <p>
304  * On the other hand it is possible to use builders methods and factories accepting
305  * constant pool entries directly. Constant pool entries can be constructed also
306  * directly from raw values, with no additional conversions or validations, as
307  * long as they are representable.  Following example uses intentionally wrong
308  * class name form, which is applied without any validation or conversion.
309  * {@snippet lang=java :
310  * var invalidClassEntry = constantPoolBuilder.classEntry(
311  *                             constantPoolBuilder.utf8Entry("mypackage.MyClass"));
312  * }
313  * <p>
314  * More complex verification of a classfile can be achieved by invocation of
315  * {@link ClassFile#verify}.
316  *
317  * <h2>Transforming classfiles</h2>
318  * ClassFile Processing APIs are most frequently used to combine reading and
319  * writing into transformation, where a classfile is read, localized changes are
320  * made, but much of the classfile is passed through unchanged.  For each kind
321  * of builder, {@code XxxBuilder} has a method {@code with(XxxElement)} so that
322  * elements that we wish to pass through unchanged can be handed directly back
323  * to the builder.
324  * <p>
325  * If we wanted to strip out methods whose names starts with "debug", we could
326  * get an existing {@link ClassModel}, build a new classfile that
327  * provides a {@link ClassBuilder}, iterate the elements of the
328  * original {@link ClassModel}, and pass through all of them to
329  * the builder except the methods we want to drop:
330  * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods1"}
331  * <p>
332  * This hands every class element, except for those corresponding to methods
333  * whose names start with {@code debug}, back to the builder.  Transformations
334  * can of course be more complicated, diving into method bodies and instructions
335  * and transforming those as well, but the same structure is repeated at every
336  * level, since every entity has corresponding model, builder, and element
337  * abstractions.
338  * <p>
339  * Transformation can be viewed as a "flatMap" operation on the sequence of
340  * elements; for every element, we could pass it through unchanged, drop it, or
341  * replace it with one or more elements.  Because transformation is such a
342  * common operation on classfiles, each model type has a corresponding {@code
343  * XxxTransform} type (which describes a transform on a sequence of {@code
344  * XxxElement}) and each builder type has {@code transformYyy} methods for transforming
345  * its child models.  A transform is simply a functional interface that takes a
346  * builder and an element, and an implementation "flatMap"s elements
347  * into the builder.  We could express the above as:
348  * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods2"}
349  * <p>
350  * {@code ClassTransform.dropping} convenience method allow us to simplify the same
351  * transformation construction and express the above as:
352  * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods3"}
353  *
354  * <h3>Lifting transforms</h3>
355  * While the example using transformations are only slightly shorter, the
356  * advantage of expressing transformation in this way is that the transform
357  * operations can be more easily combined.  Suppose we want to redirect
358  * invocations of static methods on {@code Foo} to the corresponding method on
359  * {@code Bar} instead.  We could express this as a transformation on {@link
360  * CodeElement}:
361  * {@snippet lang="java" class="PackageSnippets" region="fooToBarTransform"}
362  * <p>
363  * We can then <em>lift</em> this transformation on code elements into a
364  * transformation on method elements.  This intercepts method elements that
365  * correspond to a {@code Code} attribute, dives into its code elements, and
366  * applies the code transform to them, and passes other method elements through
367  * unchanged:
368  * {@snippet lang=java :
369  * MethodTransform mt = MethodTransform.transformingCode(fooToBar);
370  * }
371  * <p>
372  * and further lift the transform on method elements into one on class
373  * elements:
374  * {@snippet lang=java :
375  * ClassTransform ct = ClassTransform.transformingMethods(mt);
376  * }
377  * <p>
378  * or lift the code transform into the class transform directly:
379  * {@snippet lang=java :
380  * ClassTransform ct = ClassTransform.transformingMethodBodies(fooToBar);
381  * }
382  * <p>
383  * and then transform the classfile:
384  * {@snippet lang=java :
385  * var cc = ClassFile.of();
386  * byte[] newBytes = cc.transformClass(cc.parse(bytes), ct);
387  * }
388  * <p>
389  * This is much more concise (and less error-prone) than the equivalent
390  * expressed by traversing the classfile structure directly:
391  * {@snippet lang="java" class="PackageSnippets" region="fooToBarUnrolled"}
392  *
393  * <h3>Composing transforms</h3>
394  * Transforms on the same type of element can be composed in sequence, where the
395  * output of the first is fed to the input of the second.  Suppose we want to
396  * instrument all method calls, where we print the name of a method before
397  * calling it:
398  * {@snippet lang="java" class="PackageSnippets" region="instrumentCallsTransform"}
399  * <p>
400  * Then we can compose {@code fooToBar} and {@code instrumentCalls} with {@link
401  * CodeTransform#andThen(CodeTransform)}:
402  *
403  * {@snippet lang=java :
404  * var cc = ClassFile.of();
405  * byte[] newBytes = cc.transformClass(cc.parse(bytes),
406  *                                ClassTransform.transformingMethods(
407  *                                    MethodTransform.transformingCode(
408  *                                        fooToBar.andThen(instrumentCalls))));
409  * }
410  *
411  * Transform {@code instrumentCalls} will receive all code elements produced by
412  * transform {@code forToBar}, either those code elements from the original classfile
413  * or replacements (replacing static invocations to {@code Foo} with those to {@code Bar}).
414  *
415  * <h3>Constant pool sharing</h3>
416  * Transformation doesn't merely handle the logistics of reading, transforming
417  * elements, and writing.  Most of the time when we are transforming a
418  * classfile, we are making relatively minor changes.  To optimize such cases,
419  * transformation seeds the new classfile with a copy of the constant pool from
420  * the original classfile; this enables significant optimizations (methods and
421  * attributes that are not transformed can be processed by bulk-copying their
422  * bytes, rather than parsing them and regenerating their contents.)  If
423  * constant pool sharing is not desired it can be suppressed
424  * with the {@link ClassFile.ConstantPoolSharingOption} option.
425  * Such suppression may be beneficial when transformation removes many elements,
426  * resulting in many unreferenced constant pool entries.
427  *
428  * <h3>Transformation handling of unknown classfile elements</h3>
429  * Custom classfile transformations might be unaware of classfile elements
430  * introduced by future JDK releases. To achieve deterministic stability,
431  * classfile transforms interested in consuming all classfile elements should be
432  * implemented strictly to throw exceptions if running on a newer JDK, if the
433  * transformed class file is a newer version, or if a new and unknown classfile
434  * element appears. As for example in the following strict compatibility-checking
435  * transformation snippets:
436  * {@snippet lang="java" class="PackageSnippets" region="strictTransform1"}
437  * {@snippet lang="java" class="PackageSnippets" region="strictTransform2"}
438  * {@snippet lang="java" class="PackageSnippets" region="strictTransform3"}
439  * <p>
440  * Conversely, classfile transforms that are only interested in consuming a portion
441  * of classfile elements do not need to concern with new and unknown classfile
442  * elements and may pass them through. Following example shows such future-proof
443  * code transformation:
444  * {@snippet lang="java" class="PackageSnippets" region="benevolentTransform"}
445  *
446  * <h2>API conventions</h2>
447  * <p>
448  * The API is largely derived from a <a href="#data_model"><em>data model</em></a>
449  * for the classfile format, which defines each element kind (which includes models and
450  * attributes) and its properties.  For each element kind, there is a
451  * corresponding interface to describe that element, and factory methods to
452  * create that element.  Some element kinds also have convenience methods on the
453  * corresponding builder (e.g., {@link
454  * CodeBuilder#invokevirtual(ClassDesc,
455  * String, MethodTypeDesc)}).
456  * <p>
457  * Most symbolic information in elements is represented by constant pool entries
458  * (for example, the owner of a field is represented by a {@link
459  * ClassEntry}.) Factories and builders also
460  * accept nominal descriptors from {@link java.lang.constant} (e.g., {@link
461  * ClassDesc}.)
462  *
463  * <h3 id="data-types">Conventional data types</h3>
464  * Chapter {@jvms 4} of the <cite>Java Virtual Machine Specification</cite>
465  * defines a few conventional data types in the {@code class} file format.
466  * They are consistently represented as {@code int} in the API model.
467  * Out-of-bound values provided for these data types to the API result in {@link
468  * IllegalArgumentException}.
469  * <dl>
470  * <dt id="u1">{@code u1}</dt>
471  * <dd>One-byte {@linkplain Byte#toUnsignedInt(byte) unsigned} integer, in the
472  * range {@code [0, 255]}.
473  * <br>See {@link java.io.DataInput#readUnsignedByte()}.</dd>
474  * <dt id="u2">{@code u2}</dt>
475  * <dd>Two-byte {@linkplain Short#toUnsignedInt(short) unsigned} integer, in the
476  * range {@code [0, 65535]}.
477  * <br>Equivalent to a Java {@link Character char}.  Frequently used for flag
478  * fields and indices and sizes of list structures.
479  * <br>See {@link java.io.DataInput#readUnsignedShort()}.</dd>
480  * <dt id="u4">{@code u4}</dt>
481  * <dd>Four-byte {@linkplain Integer#toUnsignedLong(int) unsigned} integer, in
482  * the range {@code [0, 4294967295]}.
483  * <br>See {@link java.io.DataInput#readInt()}.</dd>
484  * </dl>
485  *
486  * <h2><a id="data_model"></a>Data model</h2>
487  * We define each kind of element by its name, an optional arity indicator (zero
488  * or more, zero or one, exactly one), and a list of components.  The elements
489  * of a class are fields, methods, and the attributes that can appear on
490  * classes:
491  *
492  * {@snippet lang="text" :
493  * ClassElement =
494  *     FieldModel*(UtfEntry name, Utf8Entry descriptor)
495  *     | MethodModel*(UtfEntry name, Utf8Entry descriptor)
496  *     | ModuleAttribute?(int flags, ModuleEntry moduleName, UtfEntry moduleVersion,
497  *                        List<ModuleRequireInfo> requires, List<ModuleOpenInfo> opens,
498  *                        List<ModuleExportInfo> exports, List<ModuleProvidesInfo> provides,
499  *                        List<ClassEntry> uses)
500  *     | ModulePackagesAttribute?(List<PackageEntry> packages)
501  *     | ModuleTargetAttribute?(Utf8Entry targetPlatform)
502  *     | ModuleHashesAttribute?(Utf8Entry algorithm, List<HashInfo> hashes)
503  *     | ModuleResolutionAttribute?(int resolutionFlags)
504  *     | SourceFileAttribute?(Utf8Entry sourceFile)
505  *     | SourceDebugExtensionsAttribute?(byte[] contents)
506  *     | CompilationIDAttribute?(Utf8Entry compilationId)
507  *     | SourceIDAttribute?(Utf8Entry sourceId)
508  *     | NestHostAttribute?(ClassEntry nestHost)
509  *     | NestMembersAttribute?(List<ClassEntry> nestMembers)
510  *     | RecordAttribute?(List<RecordComponent> components)
511  *     | EnclosingMethodAttribute?(ClassEntry className, NameAndTypeEntry method)
512  *     | InnerClassesAttribute?(List<InnerClassInfo> classes)
513  *     | PermittedSubclassesAttribute?(List<ClassEntry> permittedSubclasses)
514  *     | DeclarationElement*
515  * }
516  *
517  * where {@code DeclarationElement} are the elements that are common to all declarations
518  * (classes,  methods, fields) and so are factored out:
519  *
520  * {@snippet lang="text" :
521  * DeclarationElement =
522  *     SignatureAttribute?(Utf8Entry signature)
523  *     | SyntheticAttribute?()
524  *     | DeprecatedAttribute?()
525  *     | RuntimeInvisibleAnnotationsAttribute?(List<Annotation> annotations)
526  *     | RuntimeVisibleAnnotationsAttribute?(List<Annotation> annotations)
527  *     | CustomAttribute*
528  *     | UnknownAttribute*
529  * }
530  *
531  * Fields and methods are models with their own elements.  The elements of fields
532  * and methods are fairly simple; most of the complexity of methods lives in the
533  * {@link CodeModel} (which models the {@code Code} attribute
534  * along with the code-related attributes: stack map table, local variable table,
535  * line number table, etc.)
536  *
537  * {@snippet lang="text" :
538  * FieldElement =
539  *     DeclarationElement
540  *     | ConstantValueAttribute?(ConstantValueEntry constant)
541  *
542  * MethodElement =
543  *     DeclarationElement
544  *     | CodeModel?()
545  *     | AnnotationDefaultAttribute?(ElementValue defaultValue)
546  *     | MethodParametersAttribute?(List<MethodParameterInfo> parameters)
547  *     | ExceptionsAttribute?(List<ClassEntry> exceptions)
548  * }
549  *
550  * {@link CodeModel} is unique in that its elements are <em>ordered</em>.
551  * Elements of {@code Code} include ordinary bytecodes, as well as a number of pseudo-instructions
552  * representing branch targets, line number metadata, local variable metadata, and
553  * catch blocks.
554  *
555  * {@snippet lang="text" :
556  * CodeElement = Instruction | PseudoInstruction
557  *
558  * Instruction =
559  *     LoadInstruction(TypeKind type, int slot)
560  *     | StoreInstruction(TypeKind type, int slot)
561  *     | IncrementInstruction(int slot, int constant)
562  *     | BranchInstruction(Opcode opcode, Label target)
563  *     | LookupSwitchInstruction(Label defaultTarget, List<SwitchCase> cases)
564  *     | TableSwitchInstruction(Label defaultTarget, int low, int high,
565  *                              List<SwitchCase> cases)
566  *     | ReturnInstruction(TypeKind kind)
567  *     | ThrowInstruction()
568  *     | FieldInstruction(Opcode opcode, FieldRefEntry field)
569  *     | InvokeInstruction(Opcode opcode, MemberRefEntry method, boolean isInterface)
570  *     | InvokeDynamicInstruction(InvokeDynamicEntry invokedynamic)
571  *     | NewObjectInstruction(ClassEntry className)
572  *     | NewReferenceArrayInstruction(ClassEntry componentType)
573  *     | NewPrimitiveArrayInstruction(TypeKind typeKind)
574  *     | NewMultiArrayInstruction(ClassEntry componentType, int dims)
575  *     | ArrayLoadInstruction(Opcode opcode)
576  *     | ArrayStoreInstruction(Opcode opcode)
577  *     | TypeCheckInstruction(Opcode opcode, ClassEntry className)
578  *     | ConvertInstruction(TypeKind from, TypeKind to)
579  *     | OperatorInstruction(Opcode opcode)
580  *     | ConstantInstruction(ConstantDesc constant)
581  *     | StackInstruction(Opcode opcode)
582  *     | MonitorInstruction(Opcode opcode)
583  *     | NopInstruction()
584  *
585  * PseudoInstruction =
586  *     | LabelTarget(Label label)
587  *     | LineNumber(int line)
588  *     | ExceptionCatch(Label tryStart, Label tryEnd, Label handler, ClassEntry exception)
589  *     | LocalVariable(int slot, UtfEntry name, Utf8Entry type, Label startScope, Label endScope)
590  *     | LocalVariableType(int slot, Utf8Entry name, Utf8Entry type, Label startScope, Label endScope)
591  *     | CharacterRange(int rangeStart, int rangeEnd, int flags, Label startScope, Label endScope)
592  * }
593  *
594  * @since 24
595  */
596 package java.lang.classfile;
597 
598 import java.lang.classfile.attribute.SignatureAttribute;
599 import java.lang.classfile.attribute.UnknownAttribute;
600 import java.lang.classfile.constantpool.ClassEntry;
601 import java.lang.classfile.constantpool.PoolEntry;
602 import java.lang.classfile.constantpool.Utf8Entry;
603 import java.lang.classfile.instruction.InvokeInstruction;
604 import java.lang.constant.ClassDesc;
605 import java.lang.constant.MethodTypeDesc;
606 import java.util.function.Function;