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 java.lang.constant.Constable;
 29 import java.lang.constant.ConstantDesc;
 30 import java.lang.constant.ConstantDescs;
 31 import java.lang.constant.DynamicConstantDesc;
 32 import java.lang.constant.MethodHandleDesc;
 33 import java.util.Collections;
 34 import java.util.List;
 35 import java.util.Map;
 36 import java.util.Objects;
 37 import java.util.Optional;
 38 import java.util.OptionalLong;
 39 import java.util.function.LongBinaryOperator;
 40 import java.util.stream.Collectors;
 41 
 42 /**
 43  * A group layout is used to combine together multiple <em>member layouts</em>. There are two ways in which member layouts
 44  * can be combined: if member layouts are laid out one after the other, the resulting group layout is said to be a <em>struct</em>
 45  * (see {@link MemoryLayout#structLayout(MemoryLayout...)}); conversely, if all member layouts are laid out at the same starting offset,
 46  * the resulting group layout is said to be a <em>union</em> (see {@link MemoryLayout#unionLayout(MemoryLayout...)}).
 47  * <p>
 48  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 49  * class; programmers should treat instances that are
 50  * {@linkplain #equals(Object) equal} as interchangeable and should not
 51  * use instances for synchronization, or unpredictable behavior may
 52  * occur. For example, in a future release, synchronization may fail.
 53  * The {@code equals} method should be used for comparisons.
 54  *
 55  * <p> Unless otherwise specified, passing a {@code null} argument, or an array argument containing one or more {@code null}
 56  * elements to a method in this class causes a {@link NullPointerException NullPointerException} to be thrown. </p>
 57  *
 58  * @implSpec
 59  * This class is immutable and thread-safe.
 60  */
 61 public final class GroupLayout extends AbstractLayout implements MemoryLayout {
 62 
 63     /**
 64      * The group kind.
 65      */
 66     enum Kind {
 67         /**
 68          * A 'struct' kind.
 69          */
 70         STRUCT("", MH_STRUCT, Long::sum),
 71         /**
 72          * A 'union' kind.
 73          */
 74         UNION("|", MH_UNION, Math::max);
 75 
 76         final String delimTag;
 77         final MethodHandleDesc mhDesc;
 78         final LongBinaryOperator sizeOp;
 79 
 80         Kind(String delimTag, MethodHandleDesc mhDesc, LongBinaryOperator sizeOp) {
 81             this.delimTag = delimTag;
 82             this.mhDesc = mhDesc;
 83             this.sizeOp = sizeOp;
 84         }
 85 
 86         OptionalLong sizeof(List<MemoryLayout> elems) {
 87             long size = 0;
 88             for (MemoryLayout elem : elems) {
 89                 if (AbstractLayout.optSize(elem).isPresent()) {
 90                     size = sizeOp.applyAsLong(size, elem.bitSize());
 91                 } else {
 92                     return OptionalLong.empty();
 93                 }
 94             }
 95             return OptionalLong.of(size);
 96         }
 97 
 98         long alignof(List<MemoryLayout> elems) {
 99             return elems.stream().mapToLong(MemoryLayout::bitAlignment).max() // max alignment in case we have member layouts
100                     .orElse(1); // or minimal alignment if no member layout is given
101         }
102     }
103 
104     private final Kind kind;
105     private final List<MemoryLayout> elements;
106 
107     GroupLayout(Kind kind, List<MemoryLayout> elements) {
108         this(kind, elements, kind.alignof(elements), Map.of());
109     }
110 
111     GroupLayout(Kind kind, List<MemoryLayout> elements, long alignment, Map<String, Constable> attributes) {
112         super(kind.sizeof(elements), alignment, attributes);
113         this.kind = kind;
114         this.elements = elements;
115     }
116 
117     /**
118      * Returns the member layouts associated with this group.
119      *
120      * @apiNote the order in which member layouts are returned is the same order in which member layouts have
121      * been passed to one of the group layout factory methods (see {@link MemoryLayout#structLayout(MemoryLayout...)},
122      * {@link MemoryLayout#unionLayout(MemoryLayout...)}).
123      *
124      * @return the member layouts associated with this group.
125      */
126     public List<MemoryLayout> memberLayouts() {
127         return Collections.unmodifiableList(elements);
128     }
129 
130     @Override
131     public String toString() {
132         return decorateLayoutString(elements.stream()
133                 .map(Object::toString)
134                 .collect(Collectors.joining(kind.delimTag, "[", "]")));
135     }
136 
137     /**
138      * Is this group layout a <em>struct</em>?
139      *
140      * @return true, if this group layout is a <em>struct</em>.
141      */
142     public boolean isStruct() {
143         return kind == Kind.STRUCT;
144     }
145 
146     /**
147      * Is this group layout a <em>union</em>?
148      *
149      * @return true, if this group layout is a <em>union</em>.
150      */
151     public boolean isUnion() {
152         return kind == Kind.UNION;
153     }
154 
155     @Override
156     public boolean equals(Object other) {
157         if (this == other) {
158             return true;
159         }
160         if (!super.equals(other)) {
161             return false;
162         }
163         if (!(other instanceof GroupLayout)) {
164             return false;
165         }
166         GroupLayout g = (GroupLayout)other;
167         return kind.equals(g.kind) && elements.equals(g.elements);
168     }
169 
170     @Override
171     public int hashCode() {
172         return Objects.hash(super.hashCode(), kind, elements);
173     }
174 
175     @Override
176     GroupLayout dup(long alignment, Map<String, Constable> attributes) {
177         return new GroupLayout(kind, elements, alignment, attributes);
178     }
179 
180     @Override
181     boolean hasNaturalAlignment() {
182         return alignment == kind.alignof(elements);
183     }
184 
185     @Override
186     public Optional<DynamicConstantDesc<GroupLayout>> describeConstable() {
187         ConstantDesc[] constants = new ConstantDesc[1 + elements.size()];
188         constants[0] = kind.mhDesc;
189         for (int i = 0 ; i < elements.size() ; i++) {
190             constants[i + 1] = elements.get(i).describeConstable().get();
191         }
192         return Optional.of(decorateLayoutConstant(DynamicConstantDesc.ofNamed(
193                     ConstantDescs.BSM_INVOKE, kind.name().toLowerCase(),
194                 CD_GROUP_LAYOUT, constants)));
195     }
196 
197     //hack: the declarations below are to make javadoc happy; we could have used generics in AbstractLayout
198     //but that causes issues with javadoc, see JDK-8224052
199 
200     /**
201      * {@inheritDoc}
202      */
203     @Override
204     public GroupLayout withName(String name) {
205         return (GroupLayout)super.withName(name);
206     }
207 
208     /**
209      * {@inheritDoc}
210      */
211     @Override
212     public GroupLayout withBitAlignment(long alignmentBits) {
213         return (GroupLayout)super.withBitAlignment(alignmentBits);
214     }
215 
216     /**
217      * {@inheritDoc}
218      */
219     @Override
220     public GroupLayout withAttribute(String name, Constable value) {
221         return (GroupLayout)super.withAttribute(name, value);
222     }
223 }