f11042e2c35b7c5c28d4f064e09a0a75e453cff8
[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.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 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         if (arg instanceof QName qname) {
271             return qname;
272         }
273         throw new VerifyException("Unexpected argument " + arg);
274     }
275
276     @NonNull AbstractQName localName() {
277         // FIXME: this should be done in a nicer way
278         final Object arg = statement.argument();
279         if (arg instanceof AbstractQName aqn) {
280             return aqn;
281         }
282         throw new VerifyException("Illegal argument " + arg);
283     }
284
285     @Override
286     ClassPlacement classPlacement() {
287         // We process nodes introduced through augment or uses separately
288         // FIXME: this is not quite right!
289         return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
290     }
291
292     @Override
293     Member createMember(final CollisionDomain domain) {
294         return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
295     }
296
297     void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
298             final @NonNull TypeBuilderFactory builderFactory) {
299         if (isAugmenting()) {
300             // Do not process augmented nodes: they will be taken care of in their home augmentation
301             return;
302         }
303         if (isAddedByUses()) {
304             // If this generator has been added by a uses node, it is already taken care of by the corresponding
305             // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
306             // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
307             // resolving the reference.
308             addAsGetterMethodOverride(builder, builderFactory);
309             return;
310         }
311
312         final Type returnType = methodReturnType(builderFactory);
313         constructGetter(builder, returnType);
314         constructRequire(builder, returnType);
315     }
316
317     MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
318         return constructGetter(builder, returnType, Naming.getGetterMethodName(localName().getLocalName()));
319     }
320
321     final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
322             final Type returnType, final String methodName) {
323         final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
324
325         annotateDeprecatedIfNecessary(getMethod);
326
327         statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
328             .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
329
330         return getMethod;
331     }
332
333     void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
334         // No-op in most cases
335     }
336
337     final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
338         constructGetter(builder, returnType, Naming.getRequireMethodName(localName().getLocalName()))
339             .setDefault(true)
340             .setMechanics(ValueMechanics.NONNULL);
341     }
342
343     void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
344             final @NonNull TypeBuilderFactory builderFactory) {
345         // No-op for most cases
346     }
347
348     @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
349         return getGeneratedType(builderFactory);
350     }
351
352     final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
353         annotateDeprecatedIfNecessary(statement, builder);
354     }
355
356     @Override
357     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
358         helper.add("argument", statement.argument());
359
360         if (isAddedByUses()) {
361             helper.addValue("addedByUses");
362         }
363         if (isAugmenting()) {
364             helper.addValue("augmenting");
365         }
366         return helper;
367     }
368 }