3ca83a023da644a1810f1292f44bb8a3cf01eeec
[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, of applicable.
83      *
84      * @return Associated run-time type, or empty
85      */
86     public final Optional<R> runtimeType() {
87         if (!runtimeTypeInitialized) {
88             runtimeType = createRuntimeType();
89             runtimeTypeInitialized = true;
90         }
91         return Optional.ofNullable(runtimeType);
92     }
93
94     final Optional<R> runtimeTypeOf(final @NonNull S stmt) {
95         return recursiveRuntimeType().map(childType -> rebaseRuntimeType(childType, stmt));
96     }
97
98     public final Optional<R> recursiveRuntimeType() {
99         AbstractExplicitGenerator<S, R> gen = this;
100         do {
101             final var ret = gen.runtimeType();
102             if (ret.isPresent()) {
103                 return ret;
104             }
105
106             gen = gen.previous();
107         } while (gen != null);
108
109         return Optional.empty();
110     }
111
112     abstract @Nullable R createRuntimeType();
113
114     abstract @NonNull R rebaseRuntimeType(@NonNull R type, @NonNull S statement);
115
116     @Override
117     public final boolean isAddedByUses() {
118         return statement instanceof AddedByUsesAware && ((AddedByUsesAware) statement).isAddedByUses();
119     }
120
121     @Override
122     public final boolean isAugmenting() {
123         return statement instanceof CopyableNode && ((CopyableNode) statement).isAugmenting();
124     }
125
126     /**
127      * Attempt to link the generator corresponding to the original definition for this generator.
128      *
129      * @return {@code true} if this generator is linked
130      */
131     final boolean linkOriginalGenerator() {
132         if (orig != null) {
133             // Original already linked
134             return true;
135         }
136
137         if (prev == null) {
138             LOG.trace("Linking {}", this);
139
140             if (!isAddedByUses() && !isAugmenting()) {
141                 orig = prev = this;
142                 LOG.trace("Linked {} to self", this);
143                 return true;
144             }
145
146             final var link = getParent().<S, R>originalChild(getQName());
147             if (link == null) {
148                 LOG.trace("Cannot link {} yet", this);
149                 return false;
150             }
151
152             prev = link.previous();
153             orig = link.original();
154             if (orig != null) {
155                 LOG.trace("Linked {} to {} original {}", this, prev, orig);
156                 return true;
157             }
158
159             LOG.trace("Linked {} to intermediate {}", this, prev);
160             return false;
161         }
162
163         orig = prev.originalLink().original();
164         if (orig != null) {
165             LOG.trace("Linked {} to original {}", this, orig);
166             return true;
167         }
168         return false;
169     }
170
171     /**
172      * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
173      *
174      * @return Previous incarnation or {@code null}
175      */
176     final @Nullable AbstractExplicitGenerator<S, R> previous() {
177         final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
178         return local == this ? null : local;
179     }
180
181     /**
182      * Return the original incarnation of this generator, or self if this is the original generator.
183      *
184      * @return Original incarnation of this generator
185      */
186     @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
187         return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
188     }
189
190     @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
191         return orig;
192     }
193
194     /**
195      * Return the link towards the original generator.
196      *
197      * @return Link towards the original generator.
198      */
199     final @NonNull OriginalLink<S, R> originalLink() {
200         final var local = prev;
201         if (local == null) {
202             return OriginalLink.partial(this);
203         } else if (local == this) {
204             return OriginalLink.complete(this);
205         } else {
206             return OriginalLink.partial(local);
207         }
208     }
209
210     @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
211         return findLocalSchemaTreeGenerator(qname);
212     }
213
214     final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
215         for (Generator child : this) {
216             if (child instanceof AbstractExplicitGenerator) {
217                 final AbstractExplicitGenerator<?, ?> gen = (AbstractExplicitGenerator<?, ?>) child;
218                 final EffectiveStatement<?, ?> stmt = gen.statement();
219                 if (stmt instanceof SchemaTreeEffectiveStatement && qname.equals(stmt.argument())) {
220                     return gen;
221                 }
222             }
223         }
224         return null;
225     }
226
227     final @NonNull QName getQName() {
228         final Object arg = statement.argument();
229         verify(arg instanceof QName, "Unexpected argument %s", arg);
230         return (QName) arg;
231     }
232
233     @NonNull AbstractQName localName() {
234         // FIXME: this should be done in a nicer way
235         final Object argument = statement.argument();
236         verify(argument instanceof AbstractQName, "Illegal argument %s", argument);
237         return (AbstractQName) argument;
238     }
239
240     @Override
241     ClassPlacement classPlacement() {
242         // We process nodes introduced through augment or uses separately
243         // FIXME: this is not quite right!
244         return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
245     }
246
247     @Override
248     Member createMember(final CollisionDomain domain) {
249         return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
250     }
251
252     void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
253             final @NonNull TypeBuilderFactory builderFactory) {
254         if (isAugmenting()) {
255             // Do not process augmented nodes: they will be taken care of in their home augmentation
256             return;
257         }
258         if (isAddedByUses()) {
259             // If this generator has been added by a uses node, it is already taken care of by the corresponding
260             // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
261             // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
262             // resolving the reference.
263             addAsGetterMethodOverride(builder, builderFactory);
264             return;
265         }
266
267         final Type returnType = methodReturnType(builderFactory);
268         constructGetter(builder, returnType);
269         constructRequire(builder, returnType);
270     }
271
272     MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
273         return constructGetter(builder, returnType, BindingMapping.getGetterMethodName(localName().getLocalName()));
274     }
275
276     final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
277             final Type returnType, final String methodName) {
278         final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
279
280         annotateDeprecatedIfNecessary(getMethod);
281
282         statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
283             .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
284
285         return getMethod;
286     }
287
288     void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
289         // No-op in most cases
290     }
291
292     final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
293         constructGetter(builder, returnType, BindingMapping.getRequireMethodName(localName().getLocalName()))
294             .setDefault(true)
295             .setMechanics(ValueMechanics.NONNULL);
296     }
297
298     void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
299             final @NonNull TypeBuilderFactory builderFactory) {
300         // No-op for most cases
301     }
302
303     @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
304         return getGeneratedType(builderFactory);
305     }
306
307     final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
308         annotateDeprecatedIfNecessary(statement, builder);
309     }
310
311     @Override
312     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
313         helper.add("argument", statement.argument());
314
315         if (isAddedByUses()) {
316             helper.addValue("addedByUses");
317         }
318         if (isAugmenting()) {
319             helper.addValue("augmenting");
320         }
321         return helper;
322     }
323 }