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