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