Unify GeneratedType verification
[mdsal.git] / binding / mdsal-binding-generator / src / main / java / org / opendaylight / mdsal / binding / generator / impl / reactor / AbstractExplicitGenerator.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.generator.impl.reactor;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.VerifyException;
15 import java.util.Optional;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.mdsal.binding.generator.impl.reactor.CollisionDomain.Member;
19 import org.opendaylight.mdsal.binding.generator.impl.tree.StatementRepresentation;
20 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
21 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
22 import org.opendaylight.mdsal.binding.model.api.Type;
23 import org.opendaylight.mdsal.binding.model.api.TypeMemberComment;
24 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
25 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
26 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
27 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
28 import org.opendaylight.yangtools.yang.binding.contract.Naming;
29 import org.opendaylight.yangtools.yang.common.AbstractQName;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
32 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
33 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * An explicit {@link Generator}, associated with a particular {@link EffectiveStatement}.
41  */
42 // FIXME: unify this with Generator
43 public abstract class AbstractExplicitGenerator<S extends EffectiveStatement<?, ?>, R extends RuntimeType>
44         extends Generator implements CopyableNode, StatementRepresentation<S> {
45     private static final Logger LOG = LoggerFactory.getLogger(AbstractExplicitGenerator.class);
46
47     private final @NonNull S statement;
48
49     /**
50      * Field tracking previous incarnation (along reverse of 'uses' and 'augment' axis) of this statement. This field
51      * can either be one of:
52      * <ul>
53      *   <li>{@code null} when not resolved, i.e. access is not legal, or</li>
54      *   <li>{@code this} object if this is the original definition, or</li>
55      *   <li>a generator which is one step closer to the original definition</li>
56      * </ul>
57      */
58     private AbstractExplicitGenerator<S, R> prev;
59     /**
60      * Field holding the original incarnation, i.e. the terminal node along {@link #prev} links.
61      */
62     private AbstractExplicitGenerator<S, R> orig;
63     /**
64      * Field containing and indicator holding the runtime type, if applicable.
65      */
66     private @Nullable R runtimeType;
67     private boolean runtimeTypeInitialized;
68
69     AbstractExplicitGenerator(final S statement) {
70         this.statement = requireNonNull(statement);
71     }
72
73     AbstractExplicitGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
74         super(parent);
75         this.statement = requireNonNull(statement);
76     }
77
78     @Override
79     public final @NonNull S statement() {
80         return statement;
81     }
82
83     /**
84      * Return the {@link RuntimeType} associated with this object, if applicable. This represents the
85      * externally-accessible view of this object when considered outside the schema tree or binding tree hierarchy.
86      *
87      * @return Associated run-time type, or empty
88      */
89     public final Optional<R> runtimeType() {
90         if (!runtimeTypeInitialized) {
91             final var type = runtimeJavaType();
92             if (type != null) {
93                 runtimeType = createExternalRuntimeType(type);
94             }
95             runtimeTypeInitialized = true;
96         }
97         return Optional.ofNullable(runtimeType);
98     }
99
100     /**
101      * Return the {@link Type} associated with this object at run-time, if applicable. This method often synonymous
102      * with {@code generatedType().orElseNull()}, but not always. For example
103      * <pre>
104      *   <code>
105      *     leaf foo {
106      *       type string;
107      *     }
108      *   </code>
109      * </pre>
110      * Results in an empty {@link #generatedType()}, but still produces a {@code java.lang.String}-based
111      * {@link RuntimeType}.
112      *
113      * @return Associated {@link Type}
114      */
115     // FIXME: this should be a generic class argument
116     // FIXME: this needs a better name, but 'runtimeType' is already taken.
117     @Nullable Type runtimeJavaType() {
118         return generatedType().orElse(null);
119     }
120
121     /**
122      * Create the externally-accessible {@link RuntimeType} view of this object. The difference between
123      * this method and {@link #createInternalRuntimeType(EffectiveStatement)} is that this method represents the view
124      * attached to {@link #statement()} and contains a separate global view of all available augmentations attached to
125      * the GeneratedType.
126      *
127      * @param type {@link Type} associated with this object, as returned by {@link #runtimeJavaType()}
128      * @return Externally-accessible RuntimeType
129      */
130     abstract @NonNull R createExternalRuntimeType(@NonNull Type type);
131
132     /**
133      * Create the internally-accessible {@link RuntimeType} view of this object, if applicable. The difference between
134      * this method and {@link #createExternalRuntimeType()} is that this represents the view attached to the specified
135      * {@code stmt}, which is supplied by the parent statement. The returned {@link RuntimeType} always reports the
136      * global view of attached augmentations as empty.
137      *
138      * @param lookup context to use when looking up child statements
139      * @param stmt Statement for which to create the view
140      * @return Internally-accessible RuntimeType, or {@code null} if not applicable
141      */
142     final @Nullable R createInternalRuntimeType(final @NonNull AugmentResolver resolver, final @NonNull S stmt) {
143         // FIXME: cache requests: if we visited this statement, we obviously know what it entails. Note that we walk
144         //        towards the original definition. As such, the cache may have to live in the generator we look up,
145         //        but should operate on this statement to reflect lookups. This needs a bit of figuring out.
146         var gen = this;
147         do {
148             final var type = gen.runtimeJavaType();
149             if (type != null) {
150                 return createInternalRuntimeType(resolver, stmt, type);
151             }
152
153             gen = gen.previous();
154         } while (gen != null);
155
156         return null;
157     }
158
159     abstract @NonNull R createInternalRuntimeType(@NonNull AugmentResolver resolver, @NonNull S statement,
160         @NonNull Type type);
161
162     @Override
163     public final boolean isAddedByUses() {
164         return statement instanceof AddedByUsesAware aware && aware.isAddedByUses();
165     }
166
167     @Override
168     public final boolean isAugmenting() {
169         return statement instanceof CopyableNode copyable && copyable.isAugmenting();
170     }
171
172     /**
173      * Attempt to link the generator corresponding to the original definition for this generator.
174      *
175      * @return {@code true} if this generator is linked
176      */
177     final boolean linkOriginalGenerator() {
178         if (orig != null) {
179             // Original already linked
180             return true;
181         }
182
183         if (prev == null) {
184             LOG.trace("Linking {}", this);
185
186             if (!isAddedByUses() && !isAugmenting()) {
187                 orig = prev = this;
188                 LOG.trace("Linked {} to self", this);
189                 return true;
190             }
191
192             final var link = getParent().<S, R>originalChild(getQName());
193             if (link == null) {
194                 LOG.trace("Cannot link {} yet", this);
195                 return false;
196             }
197
198             prev = link.previous();
199             orig = link.original();
200             if (orig != null) {
201                 LOG.trace("Linked {} to {} original {}", this, prev, orig);
202                 return true;
203             }
204
205             LOG.trace("Linked {} to intermediate {}", this, prev);
206             return false;
207         }
208
209         orig = prev.originalLink().original();
210         if (orig != null) {
211             LOG.trace("Linked {} to original {}", this, orig);
212             return true;
213         }
214         return false;
215     }
216
217     /**
218      * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
219      *
220      * @return Previous incarnation or {@code null}
221      */
222     final @Nullable AbstractExplicitGenerator<S, R> previous() {
223         final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
224         return local == this ? null : local;
225     }
226
227     /**
228      * Return the original incarnation of this generator, or self if this is the original generator.
229      *
230      * @return Original incarnation of this generator
231      */
232     @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
233         return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
234     }
235
236     @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
237         return orig;
238     }
239
240     /**
241      * Return the link towards the original generator.
242      *
243      * @return Link towards the original generator.
244      */
245     final @NonNull OriginalLink<S, R> originalLink() {
246         final var local = prev;
247         if (local == null) {
248             return OriginalLink.partial(this);
249         } else if (local == this) {
250             return OriginalLink.complete(this);
251         } else {
252             return OriginalLink.partial(local);
253         }
254     }
255
256     @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
257         return findLocalSchemaTreeGenerator(qname);
258     }
259
260     final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
261         for (Generator child : this) {
262             if (child instanceof AbstractExplicitGenerator<?, ?> gen
263                 && gen.statement() instanceof SchemaTreeEffectiveStatement<?> stmt && qname.equals(stmt.argument())) {
264                 return gen;
265             }
266         }
267         return null;
268     }
269
270     final @NonNull QName getQName() {
271         final Object arg = statement.argument();
272         if (arg instanceof QName qname) {
273             return qname;
274         }
275         throw new VerifyException("Unexpected argument " + arg);
276     }
277
278     @NonNull AbstractQName localName() {
279         // FIXME: this should be done in a nicer way
280         final Object arg = statement.argument();
281         if (arg instanceof AbstractQName aqn) {
282             return aqn;
283         }
284         throw new VerifyException("Illegal argument " + arg);
285     }
286
287     @Override
288     ClassPlacement classPlacement() {
289         // We process nodes introduced through augment or uses separately
290         // FIXME: this is not quite right!
291         return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
292     }
293
294     @Override
295     Member createMember(final CollisionDomain domain) {
296         return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
297     }
298
299     void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
300             final @NonNull TypeBuilderFactory builderFactory) {
301         if (isAugmenting()) {
302             // Do not process augmented nodes: they will be taken care of in their home augmentation
303             return;
304         }
305         if (isAddedByUses()) {
306             // If this generator has been added by a uses node, it is already taken care of by the corresponding
307             // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
308             // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
309             // resolving the reference.
310             addAsGetterMethodOverride(builder, builderFactory);
311             return;
312         }
313
314         final Type returnType = methodReturnType(builderFactory);
315         constructGetter(builder, returnType);
316         constructRequire(builder, returnType);
317     }
318
319     MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
320         return constructGetter(builder, returnType, Naming.getGetterMethodName(localName().getLocalName()));
321     }
322
323     final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
324             final Type returnType, final String methodName) {
325         final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
326
327         annotateDeprecatedIfNecessary(getMethod);
328
329         statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
330             .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
331
332         return getMethod;
333     }
334
335     void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
336         // No-op in most cases
337     }
338
339     final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
340         constructGetter(builder, returnType, Naming.getRequireMethodName(localName().getLocalName()))
341             .setDefault(true)
342             .setMechanics(ValueMechanics.NONNULL);
343     }
344
345     void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
346             final @NonNull TypeBuilderFactory builderFactory) {
347         // No-op for most cases
348     }
349
350     @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
351         return getGeneratedType(builderFactory);
352     }
353
354     final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
355         annotateDeprecatedIfNecessary(statement, builder);
356     }
357
358     @Override
359     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
360         helper.add("argument", statement.argument());
361
362         if (isAddedByUses()) {
363             helper.addValue("addedByUses");
364         }
365         if (isAugmenting()) {
366             helper.addValue("augmenting");
367         }
368         return helper;
369     }
370
371     static final @NonNull GeneratedType verifyGeneratedType(final Type type) {
372         if (type instanceof GeneratedType ret) {
373             return ret;
374         }
375         throw new VerifyException("Unexpected type " + type);
376     }
377 }