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