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