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