1 /*
  2  *  Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
  3  *  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  *  This code is free software; you can redistribute it and/or modify it
  6  *  under the terms of the GNU General Public License version 2 only, as
  7  *  published by the Free Software Foundation.  Oracle designates this
  8  *  particular file as subject to the "Classpath" exception as provided
  9  *  by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  *  This code is distributed in the hope that it will be useful, but WITHOUT
 12  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  *  version 2 for more details (a copy is included in the LICENSE file that
 15  *  accompanied this code).
 16  *
 17  *  You should have received a copy of the GNU General Public License version
 18  *  2 along with this work; if not, write to the Free Software Foundation,
 19  *  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  *   Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  *  or visit www.oracle.com if you need additional information or have any
 23  *  questions.
 24  *
 25  */
 26 package jdk.incubator.foreign;
 27 
 28 import jdk.internal.foreign.LayoutPath;
 29 import jdk.internal.foreign.LayoutPath.PathElementImpl.PathKind;
 30 import jdk.internal.foreign.Utils;
 31 
 32 import java.lang.constant.Constable;
 33 import java.lang.constant.DynamicConstantDesc;
 34 import java.lang.invoke.MethodHandle;
 35 import java.lang.invoke.MethodHandles;
 36 import java.lang.invoke.VarHandle;
 37 import java.nio.ByteOrder;
 38 import java.util.EnumSet;
 39 import java.util.Objects;
 40 import java.util.Optional;
 41 import java.util.OptionalLong;
 42 import java.util.Set;
 43 import java.util.function.Function;
 44 import java.util.function.UnaryOperator;
 45 import java.util.stream.Collectors;
 46 import java.util.stream.Stream;
 47 
 48 /**
 49  * A memory layout can be used to describe the contents of a memory segment.
 50  * There are two leaves in the layout hierarchy, <em>value layouts</em>, which are used to represent values of given size and kind (see
 51  * {@link ValueLayout}) and <em>padding layouts</em> which are used, as the name suggests, to represent a portion of a memory
 52  * segment whose contents should be ignored, and which are primarily present for alignment reasons (see {@link MemoryLayout#paddingLayout(long)}).
 53  * Some common value layout constants are defined in the {@link ValueLayout} class.
 54  * <p>
 55  * More complex layouts can be derived from simpler ones: a <em>sequence layout</em> denotes a repetition of one or more
 56  * element layout (see {@link SequenceLayout}); a <em>group layout</em> denotes an aggregation of (typically) heterogeneous
 57  * member layouts (see {@link GroupLayout}).
 58  * <p>
 59  * For instance, consider the following struct declaration in C:
 60  *
 61  * <blockquote><pre>{@code
 62  typedef struct {
 63      char kind;
 64      int value;
 65  } TaggedValues[5];
 66  * }</pre></blockquote>
 67  *
 68  * The above declaration can be modelled using a layout object, as follows:
 69  *
 70  * <blockquote><pre>{@code
 71 SequenceLayout taggedValues = MemoryLayout.sequenceLayout(5,
 72     MemoryLayout.structLayout(
 73         ValueLayout.JAVA_BYTE.withName("kind"),
 74         MemoryLayout.paddingLayout(24),
 75         ValueLayout.JAVA_INT.withName("value")
 76     )
 77 ).withName("TaggedValues");
 78  * }</pre></blockquote>
 79  * <p>
 80  * All implementations of this interface must be <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>;
 81  * programmers should treat instances that are {@linkplain #equals(Object) equal} as interchangeable and should not
 82  * use instances for synchronization, or unpredictable behavior may occur. For example, in a future release,
 83  * synchronization may fail. The {@code equals} method should be used for comparisons.
 84  * <p>
 85  * Non-platform classes should not implement {@linkplain MemoryLayout} directly.
 86  *
 87  * <p> Unless otherwise specified, passing a {@code null} argument, or an array argument containing one or more {@code null}
 88  * elements to a method in this class causes a {@link NullPointerException NullPointerException} to be thrown. </p>
 89  *
 90  * <h2><a id = "layout-align">Size, alignment and byte order</a></h2>
 91  *
 92  * All layouts have a size; layout size for value and padding layouts is always explicitly denoted; this means that a layout description
 93  * always has the same size in bits, regardless of the platform in which it is used. For derived layouts, the size is computed
 94  * as follows:
 95  * <ul>
 96  *     <li>for a <em>finite</em> sequence layout <em>S</em> whose element layout is <em>E</em> and size is L,
 97  *     the size of <em>S</em> is that of <em>E</em>, multiplied by <em>L</em></li>
 98  *     <li>the size of an <em>unbounded</em> sequence layout is <em>unknown</em></li>
 99  *     <li>for a group layout <em>G</em> with member layouts <em>M1</em>, <em>M2</em>, ... <em>Mn</em> whose sizes are
100  *     <em>S1</em>, <em>S2</em>, ... <em>Sn</em>, respectively, the size of <em>G</em> is either <em>S1 + S2 + ... + Sn</em> or
101  *     <em>max(S1, S2, ... Sn)</em> depending on whether the group is a <em>struct</em> or an <em>union</em>, respectively</li>
102  * </ul>
103  * <p>
104  * Furthermore, all layouts feature a <em>natural alignment</em> which can be inferred as follows:
105  * <ul>
106  *     <li>for a padding layout <em>L</em>, the natural alignment is 1, regardless of its size; that is, in the absence
107  *     of an explicit alignment constraint, a padding layout should not affect the alignment constraint of the group
108  *     layout it is nested into</li>
109  *     <li>for a value layout <em>L</em> whose size is <em>N</em>, the natural alignment of <em>L</em> is <em>N</em></li>
110  *     <li>for a sequence layout <em>S</em> whose element layout is <em>E</em>, the natural alignment of <em>S</em> is that of <em>E</em></li>
111  *     <li>for a group layout <em>G</em> with member layouts <em>M1</em>, <em>M2</em>, ... <em>Mn</em> whose alignments are
112  *     <em>A1</em>, <em>A2</em>, ... <em>An</em>, respectively, the natural alignment of <em>G</em> is <em>max(A1, A2 ... An)</em></li>
113  * </ul>
114  * A layout's natural alignment can be overridden if needed (see {@link MemoryLayout#withBitAlignment(long)}), which can be useful to describe
115  * hyper-aligned layouts.
116  * <p>
117  * All value layouts have an <em>explicit</em> byte order (see {@link java.nio.ByteOrder}) which is set when the layout is created.
118  *
119  * <h2><a id = "layout-paths">Layout paths</a></h2>
120  *
121  * A <em>layout path</em> originates from a <em>root</em> layout (typically a group or a sequence layout) and terminates
122  * at a layout nested within the root layout - this is the layout <em>selected</em> by the layout path.
123  * Layout paths are typically expressed as a sequence of one or more {@link PathElement} instances.
124  * <p>
125  * Layout paths are for example useful in order to obtain {@linkplain MemoryLayout#bitOffset(PathElement...) offsets} of
126  * arbitrarily nested layouts inside another layout, to quickly obtain a {@linkplain #varHandle(PathElement...) memory access handle}
127  * corresponding to the selected layout, to {@linkplain #select(PathElement...) select} an arbitrarily nested layout inside
128  * another layout, or to {@link #map(UnaryOperator, PathElement...) transform} a nested layout element inside
129  * another layout.
130  * <p>
131  * Such <em>layout paths</em> can be constructed programmatically using the methods in this class.
132  * For instance, given the {@code taggedValues} layout instance constructed as above, we can obtain the offset,
133  * in bits, of the member layout named <code>value</code> in the <em>first</em> sequence element, as follows:
134  * <blockquote><pre>{@code
135 long valueOffset = taggedValues.bitOffset(PathElement.sequenceElement(0),
136                                           PathElement.groupElement("value")); // yields 32
137  * }</pre></blockquote>
138  *
139  * Similarly, we can select the member layout named {@code value}, as follows:
140  * <blockquote><pre>{@code
141 MemoryLayout value = taggedValues.select(PathElement.sequenceElement(),
142                                          PathElement.groupElement("value"));
143  * }</pre></blockquote>
144  *
145  * And, we can also replace the layout named {@code value} with another layout, as follows:
146  * <blockquote><pre>{@code
147 MemoryLayout taggedValuesWithHole = taggedValues.map(l -> MemoryLayout.paddingLayout(32),
148                                             PathElement.sequenceElement(), PathElement.groupElement("value"));
149  * }</pre></blockquote>
150  *
151  * That is, the above declaration is identical to the following, more verbose one:
152  * <blockquote><pre>{@code
153 MemoryLayout taggedValuesWithHole = MemoryLayout.sequenceLayout(5,
154     MemoryLayout.structLayout(
155         ValueLayout.JAVA_BYTE.withName("kind"),
156         MemoryLayout.paddingLayout(32),
157         MemoryLayout.paddingLayout(32)
158 ));
159  * }</pre></blockquote>
160  *
161  * Layout paths can feature one or more <em>free dimensions</em>. For instance, a layout path traversing
162  * an unspecified sequence element (that is, where one of the path component was obtained with the
163  * {@link PathElement#sequenceElement()} method) features an additional free dimension, which will have to be bound at runtime.
164  * This is important when obtaining memory access var handle from layouts, as in the following code:
165  *
166  * <blockquote><pre>{@code
167 VarHandle valueHandle = taggedValues.varHandle(PathElement.sequenceElement(),
168                                                PathElement.groupElement("value"));
169  * }</pre></blockquote>
170  *
171  * Since the layout path constructed in the above example features exactly one free dimension (as it doesn't specify
172  * <em>which</em> member layout named {@code value} should be selected from the enclosing sequence layout),
173  * it follows that the memory access var handle {@code valueHandle} will feature an <em>additional</em> {@code long}
174  * access coordinate.
175  *
176  * <p>A layout path with free dimensions can also be used to create an offset-computing method handle, using the
177  * {@link #bitOffset(PathElement...)} or {@link #byteOffsetHandle(PathElement...)} method. Again, free dimensions are
178  * translated into {@code long} parameters of the created method handle. The method handle can be used to compute the
179  * offsets of elements of a sequence at different indices, by supplying these indices when invoking the method handle.
180  * For instance:
181  *
182  * <blockquote><pre>{@code
183 MethodHandle offsetHandle = taggedValues.byteOffsetHandle(PathElement.sequenceElement(),
184                                                           PathElement.groupElement("kind"));
185 long offset1 = (long) offsetHandle.invokeExact(1L); // 8
186 long offset2 = (long) offsetHandle.invokeExact(2L); // 16
187  * }</pre></blockquote>
188  *
189  * <h2>Layout attributes</h2>
190  *
191  * Layouts can be optionally associated with a <em>name</em>. A layout name can be referred to when
192  * constructing <a href="MemoryLayout.html#layout-paths"><em>layout paths</em></a>.
193  *
194  * @implSpec
195  * Implementations of this interface are immutable, thread-safe and <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>.
196  */
197 public sealed interface MemoryLayout extends Constable permits AbstractLayout, SequenceLayout, GroupLayout, PaddingLayout, ValueLayout {
198 
199     /**
200      * Returns an {@link Optional} containing the nominal descriptor for this
201      * layout, if one can be constructed, or an empty {@link Optional}
202      * if one cannot be constructed.
203      *
204      * @return An {@link Optional} containing the resulting nominal descriptor,
205      * or an empty {@link Optional} if one cannot be constructed.
206      */
207     @Override
208     Optional<? extends DynamicConstantDesc<? extends MemoryLayout>> describeConstable();
209 
210     /**
211      * Does this layout have a specified size? A layout does not have a specified size if it is (or contains) a sequence layout whose
212      * size is unspecified (see {@link SequenceLayout#elementCount()}).
213      *
214      * Value layouts (see {@link ValueLayout}) and padding layouts (see {@link MemoryLayout#paddingLayout(long)})
215      * <em>always</em> have a specified size, therefore this method always returns {@code true} in these cases.
216      *
217      * @return {@code true}, if this layout has a specified size.
218      */
219     boolean hasSize();
220 
221     /**
222      * Computes the layout size, in bits.
223      *
224      * @return the layout size, in bits.
225      * @throws UnsupportedOperationException if the layout is, or contains, a sequence layout with unspecified size (see {@link SequenceLayout}).
226      */
227     long bitSize();
228 
229     /**
230      * Computes the layout size, in bytes.
231      *
232      * @return the layout size, in bytes.
233      * @throws UnsupportedOperationException if the layout is, or contains, a sequence layout with unspecified size (see {@link SequenceLayout}),
234      * or if {@code bitSize()} is not a multiple of 8.
235      */
236     long byteSize();
237 
238     /**
239      * Return the <em>name</em> (if any) associated with this layout.
240      *
241      * @return the layout <em>name</em> (if any).
242      * @see MemoryLayout#withName(String)
243      */
244     Optional<String> name();
245 
246     /**
247      * Creates a new layout which features the desired layout <em>name</em>.
248      *
249      * @param name the layout name.
250      * @return a new layout which is the same as this layout, except for the <em>name</em> associated with it.
251      * @see MemoryLayout#name()
252      */
253     MemoryLayout withName(String name);
254 
255     /**
256      * Returns the alignment constraint associated with this layout, expressed in bits. Layout alignment defines a power
257      * of two {@code A} which is the bit-wise alignment of the layout. If {@code A <= 8} then {@code A/8} is the number of
258      * bytes that must be aligned for any pointer that correctly points to this layout. Thus:
259      *
260      * <ul>
261      * <li>{@code A=8} means unaligned (in the usual sense), which is common in packets.</li>
262      * <li>{@code A=64} means word aligned (on LP64), {@code A=32} int aligned, {@code A=16} short aligned, etc.</li>
263      * <li>{@code A=512} is the most strict alignment required by the x86/SV ABI (for AVX-512 data).</li>
264      * </ul>
265      *
266      * If no explicit alignment constraint was set on this layout (see {@link #withBitAlignment(long)}),
267      * then this method returns the <a href="#layout-align">natural alignment</a> constraint (in bits) associated with this layout.
268      *
269      * @return the layout alignment constraint, in bits.
270      */
271     long bitAlignment();
272 
273     /**
274      * Returns the alignment constraint associated with this layout, expressed in bytes. Layout alignment defines a power
275      * of two {@code A} which is the byte-wise alignment of the layout, where {@code A} is the number of bytes that must be aligned
276      * for any pointer that correctly points to this layout. Thus:
277      *
278      * <ul>
279      * <li>{@code A=1} means unaligned (in the usual sense), which is common in packets.</li>
280      * <li>{@code A=8} means word aligned (on LP64), {@code A=4} int aligned, {@code A=2} short aligned, etc.</li>
281      * <li>{@code A=64} is the most strict alignment required by the x86/SV ABI (for AVX-512 data).</li>
282      * </ul>
283      *
284      * If no explicit alignment constraint was set on this layout (see {@link #withBitAlignment(long)}),
285      * then this method returns the <a href="#layout-align">natural alignment</a> constraint (in bytes) associated with this layout.
286      *
287      * @return the layout alignment constraint, in bytes.
288      * @throws UnsupportedOperationException if {@code bitAlignment()} is not a multiple of 8.
289      */
290     default long byteAlignment() {
291         return Utils.bitsToBytesOrThrow(bitAlignment(),
292                 () -> new UnsupportedOperationException("Cannot compute byte alignment; bit alignment is not a multiple of 8"));
293     }
294 
295     /**
296      * Creates a new layout which features the desired alignment constraint.
297      *
298      * @param bitAlignment the layout alignment constraint, expressed in bits.
299      * @return a new layout which is the same as this layout, except for the alignment constraint associated with it.
300      * @throws IllegalArgumentException if {@code bitAlignment} is not a power of two, or if it's less than 8.
301      */
302     MemoryLayout withBitAlignment(long bitAlignment);
303 
304     /**
305      * Computes the offset, in bits, of the layout selected by a given layout path, where the path is considered rooted in this
306      * layout.
307      *
308      * @param elements the layout path elements.
309      * @return The offset, in bits, of the layout selected by the layout path in {@code elements}.
310      * @throws IllegalArgumentException if the layout path does not select any layout nested in this layout, or if the
311      * layout path contains one or more path elements that select multiple sequence element indices
312      * (see {@link PathElement#sequenceElement()} and {@link PathElement#sequenceElement(long, long)}).
313      * @throws UnsupportedOperationException if one of the layouts traversed by the layout path has unspecified size.
314      * @throws NullPointerException if either {@code elements == null}, or if any of the elements
315      * in {@code elements} is {@code null}.
316      */
317     default long bitOffset(PathElement... elements) {
318         return computePathOp(LayoutPath.rootPath(this, MemoryLayout::bitSize), LayoutPath::offset,
319                 EnumSet.of(PathKind.SEQUENCE_ELEMENT, PathKind.SEQUENCE_RANGE), elements);
320     }
321 
322     /**
323      * Creates a method handle that can be used to compute the offset, in bits, of the layout selected
324      * by a given layout path, where the path is considered rooted in this layout.
325      *
326      * <p>The returned method handle has a return type of {@code long}, and features as many {@code long}
327      * parameter types as there are free dimensions in the provided layout path (see {@link PathElement#sequenceElement()}),
328      * where the order of the parameters corresponds to the order of the path elements.
329      * The returned method handle can be used to compute a layout offset similar to {@link #bitOffset(PathElement...)},
330      * but where some sequence indices are specified only when invoking the method handle.
331      *
332      * <p>The final offset returned by the method handle is computed as follows:
333      *
334      * <blockquote><pre>{@code
335     offset = c_1 + c_2 + ... + c_m + (x_1 * s_1) + (x_2 * s_2) + ... + (x_n * s_n)
336      * }</pre></blockquote>
337      *
338      * where {@code x_1}, {@code x_2}, ... {@code x_n} are <em>dynamic</em> values provided as {@code long}
339      * arguments, whereas {@code c_1}, {@code c_2}, ... {@code c_m} are <em>static</em> offset constants
340      * and {@code s_0}, {@code s_1}, ... {@code s_n} are <em>static</em> stride constants which are derived from
341      * the layout path.
342      *
343      * @param elements the layout path elements.
344      * @return a method handle that can be used to compute the bit offset of the layout element
345      * specified by the given layout path elements, when supplied with the missing sequence element indices.
346      * @throws IllegalArgumentException if the layout path contains one or more path elements that select
347      * multiple sequence element indices (see {@link PathElement#sequenceElement(long, long)}).
348      * @throws UnsupportedOperationException if one of the layouts traversed by the layout path has unspecified size.
349      */
350     default MethodHandle bitOffsetHandle(PathElement... elements) {
351         return computePathOp(LayoutPath.rootPath(this, MemoryLayout::bitSize), LayoutPath::offsetHandle,
352                 EnumSet.of(PathKind.SEQUENCE_RANGE), elements);
353     }
354 
355     /**
356      * Computes the offset, in bytes, of the layout selected by a given layout path, where the path is considered rooted in this
357      * layout.
358      *
359      * @param elements the layout path elements.
360      * @return The offset, in bytes, of the layout selected by the layout path in {@code elements}.
361      * @throws IllegalArgumentException if the layout path does not select any layout nested in this layout, or if the
362      * layout path contains one or more path elements that select multiple sequence element indices
363      * (see {@link PathElement#sequenceElement()} and {@link PathElement#sequenceElement(long, long)}).
364      * @throws UnsupportedOperationException if one of the layouts traversed by the layout path has unspecified size,
365      * or if {@code bitOffset(elements)} is not a multiple of 8.
366      * @throws NullPointerException if either {@code elements == null}, or if any of the elements
367      * in {@code elements} is {@code null}.
368      */
369     default long byteOffset(PathElement... elements) {
370         return Utils.bitsToBytesOrThrow(bitOffset(elements), Utils.bitsToBytesThrowOffset);
371     }
372 
373     /**
374      * Creates a method handle that can be used to compute the offset, in bytes, of the layout selected
375      * by a given layout path, where the path is considered rooted in this layout.
376      *
377      * <p>The returned method handle has a return type of {@code long}, and features as many {@code long}
378      * parameter types as there are free dimensions in the provided layout path (see {@link PathElement#sequenceElement()}),
379      * where the order of the parameters corresponds to the order of the path elements.
380      * The returned method handle can be used to compute a layout offset similar to {@link #byteOffset(PathElement...)},
381      * but where some sequence indices are specified only when invoking the method handle.
382      *
383      * <p>The final offset returned by the method handle is computed as follows:
384      *
385      * <blockquote><pre>{@code
386     bitOffset = c_1 + c_2 + ... + c_m + (x_1 * s_1) + (x_2 * s_2) + ... + (x_n * s_n)
387     offset = bitOffset / 8
388      * }</pre></blockquote>
389      *
390      * where {@code x_1}, {@code x_2}, ... {@code x_n} are <em>dynamic</em> values provided as {@code long}
391      * arguments, whereas {@code c_1}, {@code c_2}, ... {@code c_m} are <em>static</em> offset constants
392      * and {@code s_0}, {@code s_1}, ... {@code s_n} are <em>static</em> stride constants which are derived from
393      * the layout path.
394      *
395      * <p>The method handle will throw an {@link UnsupportedOperationException} if the computed
396      * offset in bits is not a multiple of 8.
397      *
398      * @param elements the layout path elements.
399      * @return a method handle that can be used to compute the byte offset of the layout element
400      * specified by the given layout path elements, when supplied with the missing sequence element indices.
401      * @throws IllegalArgumentException if the layout path contains one or more path elements that select
402      * multiple sequence element indices (see {@link PathElement#sequenceElement(long, long)}).
403      * @throws UnsupportedOperationException if one of the layouts traversed by the layout path has unspecified size.
404      */
405     default MethodHandle byteOffsetHandle(PathElement... elements) {
406         MethodHandle mh = bitOffsetHandle(elements);
407         mh = MethodHandles.filterReturnValue(mh, Utils.MH_bitsToBytesOrThrowForOffset);
408         return mh;
409     }
410 
411     /**
412      * Creates a memory access var handle that can be used to dereference memory at the layout selected by a given layout path,
413      * where the path is considered rooted in this layout.
414      * <p>
415      * The final memory location accessed by the returned memory access var handle can be computed as follows:
416      *
417      * <blockquote><pre>{@code
418     address = base + offset
419      * }</pre></blockquote>
420      *
421      * where {@code base} denotes the base address expressed by the {@link MemorySegment} access coordinate
422      * (see {@link MemorySegment#address()} and {@link MemoryAddress#toRawLongValue()}) and {@code offset}
423      * can be expressed in the following form:
424      *
425      * <blockquote><pre>{@code
426     offset = c_1 + c_2 + ... + c_m + (x_1 * s_1) + (x_2 * s_2) + ... + (x_n * s_n)
427      * }</pre></blockquote>
428      *
429      * where {@code x_1}, {@code x_2}, ... {@code x_n} are <em>dynamic</em> values provided as {@code long}
430      * arguments, whereas {@code c_1}, {@code c_2}, ... {@code c_m} are <em>static</em> offset constants
431      * and {@code s_0}, {@code s_1}, ... {@code s_n} are <em>static</em> stride constants which are derived from
432      * the layout path.
433      *
434      * @apiNote the resulting var handle will feature an additional {@code long} access coordinate for every
435      * unspecified sequence access component contained in this layout path. Moreover, the resulting var handle
436      * features certain <a href="MemoryHandles.html#memaccess-mode">access mode restrictions</a>, which are common to all memory access var handles.
437      *
438      * @param elements the layout path elements.
439      * @return a var handle which can be used to dereference memory at the (possibly nested) layout selected by the layout path in {@code elements}.
440      * @throws UnsupportedOperationException if the layout path has one or more elements with incompatible alignment constraints,
441      * or if one of the layouts traversed by the layout path has unspecified size.
442      * @throws IllegalArgumentException if the layout path in {@code elements} does not select a value layout (see {@link ValueLayout}).
443      */
444     default VarHandle varHandle(PathElement... elements) {
445         return computePathOp(LayoutPath.rootPath(this, MemoryLayout::bitSize), LayoutPath::dereferenceHandle,
446                 Set.of(), elements);
447     }
448 
449     /**
450      * Creates a method handle which, given a memory segment, returns a {@linkplain MemorySegment#asSlice(long,long) slice}
451      * corresponding to the layout selected by a given layout path, where the path is considered rooted in this layout.
452      *
453      * <p>The returned method handle has a return type of {@code MemorySegment}, features a {@code MemorySegment}
454      * parameter as leading parameter representing the segment to be sliced, and features as many trailing {@code long}
455      * parameter types as there are free dimensions in the provided layout path (see {@link PathElement#sequenceElement()}),
456      * where the order of the parameters corresponds to the order of the path elements.
457      * The returned method handle can be used to create a slice similar to using {@link MemorySegment#asSlice(long, long)},
458      * but where the offset argument is dynamically compute based on indices specified when invoking the method handle.
459      *
460      * <p>The offset of the returned segment is computed as follows:
461      *
462      * <blockquote><pre>{@code
463     bitOffset = c_1 + c_2 + ... + c_m + (x_1 * s_1) + (x_2 * s_2) + ... + (x_n * s_n)
464     offset = bitOffset / 8
465      * }</pre></blockquote>
466      *
467      * where {@code x_1}, {@code x_2}, ... {@code x_n} are <em>dynamic</em> values provided as {@code long}
468      * arguments, whereas {@code c_1}, {@code c_2}, ... {@code c_m} are <em>static</em> offset constants
469      * and {@code s_0}, {@code s_1}, ... {@code s_n} are <em>static</em> stride constants which are derived from
470      * the layout path.
471      *
472      * <p>After the offset is computed, the returned segment is created as if by calling:
473      * <blockquote><pre>{@code
474     segment.asSlice(offset, layout.byteSize());
475      * }</pre></blockquote>
476      *
477      * where {@code segment} is the segment to be sliced, and where {@code layout} is the layout selected by the given
478      * layout path, as per {@link MemoryLayout#select(PathElement...)}.
479      *
480      * <p>The method handle will throw an {@link UnsupportedOperationException} if the computed
481      * offset in bits is not a multiple of 8.
482      *
483      * @param elements the layout path elements.
484      * @return a method handle which can be used to create a slice of the selected layout element, given a segment.
485      * @throws UnsupportedOperationException if the size of the selected layout in bits is not a multiple of 8.
486      */
487     default MethodHandle sliceHandle(PathElement... elements) {
488         return computePathOp(LayoutPath.rootPath(this, MemoryLayout::bitSize), LayoutPath::sliceHandle,
489                 Set.of(), elements);
490     }
491 
492 
493     /**
494      * Selects the layout from a path rooted in this layout.
495      *
496      * @param elements the layout path elements.
497      * @return the layout selected by the layout path in {@code elements}.
498      * @throws IllegalArgumentException if the layout path does not select any layout nested in this layout,
499      * or if the layout path contains one or more path elements that select one or more sequence element indices
500      * (see {@link PathElement#sequenceElement(long)} and {@link PathElement#sequenceElement(long, long)}).
501      */
502     default MemoryLayout select(PathElement... elements) {
503         return computePathOp(LayoutPath.rootPath(this, l -> 0L), LayoutPath::layout,
504                 EnumSet.of(PathKind.SEQUENCE_ELEMENT_INDEX, PathKind.SEQUENCE_RANGE), elements);
505     }
506 
507     /**
508      * Creates a transformed copy of this layout where a selected layout, from a path rooted in this layout,
509      * is replaced with the result of applying the given operation.
510      *
511      * @param op the unary operation to be applied to the selected layout.
512      * @param elements the layout path elements.
513      * @return a new layout where the layout selected by the layout path in {@code elements},
514      * has been replaced by the result of applying {@code op} to the selected layout.
515      * @throws IllegalArgumentException if the layout path does not select any layout nested in this layout,
516      * or if the layout path contains one or more path elements that select one or more sequence element indices
517      * (see {@link PathElement#sequenceElement(long)} and {@link PathElement#sequenceElement(long, long)}).
518      */
519     default MemoryLayout map(UnaryOperator<MemoryLayout> op, PathElement... elements) {
520         Objects.requireNonNull(op);
521         return computePathOp(LayoutPath.rootPath(this, l -> 0L), path -> path.map(op),
522                 EnumSet.of(PathKind.SEQUENCE_ELEMENT_INDEX, PathKind.SEQUENCE_RANGE), elements);
523     }
524 
525     private static <Z> Z computePathOp(LayoutPath path, Function<LayoutPath, Z> finalizer,
526                                        Set<LayoutPath.PathElementImpl.PathKind> badKinds, PathElement... elements) {
527         Objects.requireNonNull(elements);
528         for (PathElement e : elements) {
529             LayoutPath.PathElementImpl pathElem = (LayoutPath.PathElementImpl)Objects.requireNonNull(e);
530             if (badKinds.contains(pathElem.kind())) {
531                 throw new IllegalArgumentException(String.format("Invalid %s selection in layout path", pathElem.kind().description()));
532             }
533             path = pathElem.apply(path);
534         }
535         return finalizer.apply(path);
536     }
537 
538     /**
539      * Is this a {@linkplain #paddingLayout(long) padding layout} ?
540      * @return true, if this layout is a padding layout.
541      */
542     boolean isPadding();
543 
544     /**
545      * Instances of this class are used to form <a href="MemoryLayout.html#layout-paths"><em>layout paths</em></a>. There
546      * are two kinds of path elements: <em>group path elements</em> and <em>sequence path elements</em>. Group
547      * path elements are used to select a given named member layout within a {@link GroupLayout}. Sequence
548      * path elements are used to select a sequence element layout within a {@link SequenceLayout}; selection
549      * of sequence element layout can be <em>explicit</em> (see {@link PathElement#sequenceElement(long)}) or
550      * <em>implicit</em> (see {@link PathElement#sequenceElement()}). When a path uses one or more implicit
551      * sequence path elements, it acquires additional <em>free dimensions</em>.
552      * <p>
553      * Non-platform classes should not implement {@linkplain PathElement} directly.
554      *
555      * <p> Unless otherwise specified, passing a {@code null} argument, or an array argument containing one or more {@code null}
556      * elements to a method in this class causes a {@link NullPointerException NullPointerException} to be thrown. </p>
557      *
558      * @implSpec
559      * Implementations of this interface are immutable and thread-safe.
560      */
561     sealed interface PathElement permits LayoutPath.PathElementImpl {
562 
563         /**
564          * Returns a path element which selects a member layout with given name from a given group layout.
565          * The path element returned by this method does not alter the number of free dimensions of any path
566          * that is combined with such element.
567          *
568          * @implSpec in case multiple group elements with a matching name exist, the path element returned by this
569          * method will select the first one; that is, the group element with the lowest offset from current path is selected.
570          *
571          * @param name the name of the group element to be selected.
572          * @return a path element which selects the group element with given name.
573          */
574         static PathElement groupElement(String name) {
575             Objects.requireNonNull(name);
576             return new LayoutPath.PathElementImpl(LayoutPath.PathElementImpl.PathKind.GROUP_ELEMENT,
577                                                   path -> path.groupElement(name));
578         }
579 
580         /**
581          * Returns a path element which selects the element layout at the specified position in a given the sequence layout.
582          * The path element returned by this method does not alter the number of free dimensions of any path
583          * that is combined with such element.
584          *
585          * @param index the index of the sequence element to be selected.
586          * @return a path element which selects the sequence element layout with given index.
587          * @throws IllegalArgumentException if {@code index < 0}.
588          */
589         static PathElement sequenceElement(long index) {
590             if (index < 0) {
591                 throw new IllegalArgumentException("Index must be positive: " + index);
592             }
593             return new LayoutPath.PathElementImpl(LayoutPath.PathElementImpl.PathKind.SEQUENCE_ELEMENT_INDEX,
594                                                   path -> path.sequenceElement(index));
595         }
596 
597         /**
598          * Returns a path element which selects the element layout in a <em>range</em> of positions in a given the sequence layout,
599          * where the range is expressed as a pair of starting index (inclusive) {@code S} and step factor (which can also be negative)
600          * {@code F}.
601          * If a path with free dimensions {@code n} is combined with the path element returned by this method,
602          * the number of free dimensions of the resulting path will be {@code 1 + n}. If the free dimension associated
603          * with this path is bound by an index {@code I}, the resulting accessed offset can be obtained with the following
604          * formula:
605          * <blockquote><pre>{@code
606 E * (S + I * F)
607          * }</pre></blockquote>
608          * where {@code E} is the size (in bytes) of the sequence element layout.
609          *
610          * @param start the index of the first sequence element to be selected.
611          * @param step the step factor at which subsequence sequence elements are to be selected.
612          * @return a path element which selects the sequence element layout with given index.
613          * @throws IllegalArgumentException if {@code start < 0}, or {@code step == 0}.
614          */
615         static PathElement sequenceElement(long start, long step) {
616             if (start < 0) {
617                 throw new IllegalArgumentException("Start index must be positive: " + start);
618             }
619             if (step == 0) {
620                 throw new IllegalArgumentException("Step must be != 0: " + step);
621             }
622             return new LayoutPath.PathElementImpl(LayoutPath.PathElementImpl.PathKind.SEQUENCE_RANGE,
623                                                   path -> path.sequenceElement(start, step));
624         }
625 
626         /**
627          * Returns a path element which selects an unspecified element layout from a given sequence layout.
628          * If a path with free dimensions {@code n} is combined with the path element returned by this method,
629          * the number of free dimensions of the resulting path will be {@code 1 + n}.
630          *
631          * @return a path element which selects an unspecified sequence element layout.
632          */
633         static PathElement sequenceElement() {
634             return new LayoutPath.PathElementImpl(LayoutPath.PathElementImpl.PathKind.SEQUENCE_ELEMENT,
635                                                   LayoutPath::sequenceElement);
636         }
637     }
638 
639     /**
640      * Compares the specified object with this layout for equality. Returns {@code true} if and only if the specified
641      * object is also a layout, and it is equal to this layout. Two layouts are considered equal if they are of
642      * the same kind, have the same size, name and alignment constraints. Furthermore, depending on the layout kind, additional
643      * conditions must be satisfied:
644      * <ul>
645      *     <li>two value layouts are considered equal if they have the same byte order (see {@link ValueLayout#order()})</li>
646      *     <li>two sequence layouts are considered equal if they have the same element count (see {@link SequenceLayout#elementCount()}), and
647      *     if their element layouts (see {@link SequenceLayout#elementLayout()}) are also equal</li>
648      *     <li>two group layouts are considered equal if they are of the same kind (see {@link GroupLayout#isStruct()},
649      *     {@link GroupLayout#isUnion()}) and if their member layouts (see {@link GroupLayout#memberLayouts()}) are also equal</li>
650      * </ul>
651      *
652      * @param that the object to be compared for equality with this layout.
653      * @return {@code true} if the specified object is equal to this layout.
654      */
655     boolean equals(Object that);
656 
657     /**
658      * Returns the hash code value for this layout.
659      *
660      * @return the hash code value for this layout.
661      */
662     int hashCode();
663 
664     /**
665      * Returns a string representation of this layout.
666      *
667      * @return a string representation of this layout.
668      */
669     @Override
670     String toString();
671 
672     /**
673      * Create a new padding layout with given size.
674      *
675      * @param size the padding size in bits.
676      * @return the new selector layout.
677      * @throws IllegalArgumentException if {@code size <= 0}.
678      */
679     static MemoryLayout paddingLayout(long size) {
680         AbstractLayout.checkSize(size);
681         return new PaddingLayout(size);
682     }
683 
684     /**
685      * Creates a value layout of given Java carrier and byte order. The type of resulting value layout is determined
686      * by the carrier provided:
687      * <ul>
688      *     <li>{@link ValueLayout.OfBoolean}, for {@code boolean.class}</li>
689      *     <li>{@link ValueLayout.OfByte}, for {@code byte.class}</li>
690      *     <li>{@link ValueLayout.OfShort}, for {@code short.class}</li>
691      *     <li>{@link ValueLayout.OfChar}, for {@code char.class}</li>
692      *     <li>{@link ValueLayout.OfInt}, for {@code int.class}</li>
693      *     <li>{@link ValueLayout.OfFloat}, for {@code float.class}</li>
694      *     <li>{@link ValueLayout.OfLong}, for {@code long.class}</li>
695      *     <li>{@link ValueLayout.OfDouble}, for {@code double.class}</li>
696      *     <li>{@link ValueLayout.OfAddress}, for {@code MemoryAddress.class}</li>
697      * </ul>
698      * @param carrier the value layout carrier.
699      * @param order the value layout's byte order.
700      * @return a new value layout.
701      * @throws IllegalArgumentException if the carrier type is not supported.
702      */
703     static ValueLayout valueLayout(Class<?> carrier, ByteOrder order) {
704         Objects.requireNonNull(carrier);
705         Objects.requireNonNull(order);
706         if (carrier == boolean.class) {
707             return new ValueLayout.OfBoolean(order);
708         } else if (carrier == char.class) {
709             return new ValueLayout.OfChar(order);
710         } else if (carrier == byte.class) {
711             return new ValueLayout.OfByte(order);
712         } else if (carrier == short.class) {
713             return new ValueLayout.OfShort(order);
714         } else if (carrier == int.class) {
715             return new ValueLayout.OfInt(order);
716         } else if (carrier == float.class) {
717             return new ValueLayout.OfFloat(order);
718         } else if (carrier == long.class) {
719             return new ValueLayout.OfLong(order);
720         } else if (carrier == double.class) {
721             return new ValueLayout.OfDouble(order);
722         } else if (carrier == MemoryAddress.class) {
723             return new ValueLayout.OfAddress(order);
724         } else {
725             throw new IllegalArgumentException("Unsupported carrier: " + carrier.getName());
726         }
727     }
728 
729     /**
730      * Create a new sequence layout with given element layout and element count.
731      *
732      * @param elementCount the sequence element count.
733      * @param elementLayout the sequence element layout.
734      * @return the new sequence layout with given element layout and size.
735      * @throws IllegalArgumentException if {@code elementCount < 0}.
736      */
737     static SequenceLayout sequenceLayout(long elementCount, MemoryLayout elementLayout) {
738         AbstractLayout.checkSize(elementCount, true);
739         OptionalLong size = OptionalLong.of(elementCount);
740         return new SequenceLayout(size, Objects.requireNonNull(elementLayout));
741     }
742 
743     /**
744      * Create a new sequence layout, with unbounded element count and given element layout.
745      *
746      * @param elementLayout the element layout of the sequence layout.
747      * @return the new sequence layout with given element layout.
748      */
749     static SequenceLayout sequenceLayout(MemoryLayout elementLayout) {
750         return new SequenceLayout(OptionalLong.empty(), Objects.requireNonNull(elementLayout));
751     }
752 
753     /**
754      * Create a new <em>struct</em> group layout with given member layouts.
755      *
756      * @param elements The member layouts of the <em>struct</em> group layout.
757      * @return a new <em>struct</em> group layout with given member layouts.
758      */
759     static GroupLayout structLayout(MemoryLayout... elements) {
760         Objects.requireNonNull(elements);
761         return new GroupLayout(GroupLayout.Kind.STRUCT,
762                 Stream.of(elements)
763                         .map(Objects::requireNonNull)
764                         .collect(Collectors.toList()));
765     }
766 
767     /**
768      * Create a new <em>union</em> group layout with given member layouts.
769      *
770      * @param elements The member layouts of the <em>union</em> layout.
771      * @return a new <em>union</em> group layout with given member layouts.
772      */
773     static GroupLayout unionLayout(MemoryLayout... elements) {
774         Objects.requireNonNull(elements);
775         return new GroupLayout(GroupLayout.Kind.UNION,
776                 Stream.of(elements)
777                         .map(Objects::requireNonNull)
778                         .collect(Collectors.toList()));
779     }
780 }