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