Do not use BindingReflections to acquire augmentations
[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 org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.mdsal.binding.generator.impl.reactor.CollisionDomain.Member;
18 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
19 import org.opendaylight.mdsal.binding.model.api.Type;
20 import org.opendaylight.mdsal.binding.model.api.TypeMemberComment;
21 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
22 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
23 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
24 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
25 import org.opendaylight.yangtools.yang.common.AbstractQName;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
28 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
29 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * An explicit {@link Generator}, associated with a particular {@link EffectiveStatement}.
37  */
38 public abstract class AbstractExplicitGenerator<T extends EffectiveStatement<?, ?>> extends Generator
39         implements CopyableNode {
40     private static final Logger LOG = LoggerFactory.getLogger(AbstractExplicitGenerator.class);
41
42     private final @NonNull T statement;
43
44     /**
45      * Field tracking previous incarnation (along reverse of 'uses' and 'augment' axis) of this statement. This field
46      * can either be one of:
47      * <ul>
48      *   <li>{@code null} when not resolved, i.e. access is not legal, or</li>
49      *   <li>{@code this} object if this is the original definition, or</li>
50      *   <li>a generator which is one step closer to the original definition</li>
51      * </ul>
52      */
53     private AbstractExplicitGenerator<T> prev;
54     /**
55      * Field holding the original incarnation, i.e. the terminal node along {@link #prev} links.
56      */
57     private AbstractExplicitGenerator<T> orig;
58
59     AbstractExplicitGenerator(final T statement) {
60         this.statement = requireNonNull(statement);
61     }
62
63     AbstractExplicitGenerator(final T statement, final AbstractCompositeGenerator<?> parent) {
64         super(parent);
65         this.statement = requireNonNull(statement);
66     }
67
68     /**
69      * Return the {@link EffectiveStatement} associated with this generator.
70      *
71      * @return An EffectiveStatement
72      */
73     public final @NonNull T statement() {
74         return statement;
75     }
76
77     @Override
78     public final boolean isAddedByUses() {
79         return statement instanceof AddedByUsesAware && ((AddedByUsesAware) statement).isAddedByUses();
80     }
81
82     @Override
83     public final boolean isAugmenting() {
84         return statement instanceof CopyableNode && ((CopyableNode) statement).isAugmenting();
85     }
86
87     /**
88      * Attempt to link the generator corresponding to the original definition for this generator.
89      *
90      * @return {@code true} if this generator is linked
91      */
92     final boolean linkOriginalGenerator() {
93         if (orig != null) {
94             // Original already linked
95             return true;
96         }
97
98         if (prev == null) {
99             LOG.trace("Linking {}", this);
100
101             if (!isAddedByUses() && !isAugmenting()) {
102                 orig = prev = this;
103                 LOG.trace("Linked {} to self", this);
104                 return true;
105             }
106
107             final var link = getParent().<T>originalChild(getQName());
108             if (link == null) {
109                 LOG.trace("Cannot link {} yet", this);
110                 return false;
111             }
112
113             prev = link.previous();
114             orig = link.original();
115             if (orig != null) {
116                 LOG.trace("Linked {} to {} original {}", this, prev, orig);
117                 return true;
118             }
119
120             LOG.trace("Linked {} to intermediate {}", this, prev);
121             return false;
122         }
123
124         orig = prev.originalLink().original();
125         if (orig != null) {
126             LOG.trace("Linked {} to original {}", this, orig);
127             return true;
128         }
129         return false;
130     }
131
132     /**
133      * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
134      *
135      * @return Previous incarnation or {@code null}
136      */
137     final @Nullable AbstractExplicitGenerator<T> previous() {
138         final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
139         return local == this ? null : local;
140     }
141
142     /**
143      * Return the original incarnation of this generator, or self if this is the original generator.
144      *
145      * @return Original incarnation of this generator
146      */
147     @NonNull AbstractExplicitGenerator<T> getOriginal() {
148         return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
149     }
150
151     @Nullable AbstractExplicitGenerator<T> tryOriginal() {
152         return orig;
153     }
154
155     /**
156      * Return the link towards the original generator.
157      *
158      * @return Link towards the original generator.
159      */
160     final @NonNull OriginalLink<T> originalLink() {
161         final var local = prev;
162         if (local == null) {
163             return OriginalLink.partial(this);
164         } else if (local == this) {
165             return OriginalLink.complete(this);
166         } else {
167             return OriginalLink.partial(local);
168         }
169     }
170
171     @Nullable AbstractExplicitGenerator<?> findSchemaTreeGenerator(final QName qname) {
172         return findLocalSchemaTreeGenerator(qname);
173     }
174
175     final @Nullable AbstractExplicitGenerator<?> findLocalSchemaTreeGenerator(final QName qname) {
176         for (Generator child : this) {
177             if (child instanceof AbstractExplicitGenerator) {
178                 final AbstractExplicitGenerator<?> gen = (AbstractExplicitGenerator<?>) child;
179                 final EffectiveStatement<?, ?> stmt = gen.statement();
180                 if (stmt instanceof SchemaTreeEffectiveStatement && qname.equals(stmt.argument())) {
181                     return gen;
182                 }
183             }
184         }
185         return null;
186     }
187
188     final @NonNull QName getQName() {
189         final Object arg = statement.argument();
190         verify(arg instanceof QName, "Unexpected argument %s", arg);
191         return (QName) arg;
192     }
193
194     @NonNull AbstractQName localName() {
195         // FIXME: this should be done in a nicer way
196         final Object argument = statement.argument();
197         verify(argument instanceof AbstractQName, "Illegal argument %s", argument);
198         return (AbstractQName) argument;
199     }
200
201     @Override
202     ClassPlacement classPlacement() {
203         // We process nodes introduced through augment or uses separately
204         // FIXME: this is not quite right!
205         return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
206     }
207
208     @Override
209     Member createMember(final CollisionDomain domain) {
210         return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
211     }
212
213     void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
214             final @NonNull TypeBuilderFactory builderFactory) {
215         if (isAugmenting()) {
216             // Do not process augmented nodes: they will be taken care of in their home augmentation
217             return;
218         }
219         if (isAddedByUses()) {
220             // If this generator has been added by a uses node, it is already taken care of by the corresponding
221             // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
222             // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
223             // resolving the reference.
224             addAsGetterMethodOverride(builder, builderFactory);
225             return;
226         }
227
228         final Type returnType = methodReturnType(builderFactory);
229         constructGetter(builder, returnType);
230         constructRequire(builder, returnType);
231     }
232
233     MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
234         return constructGetter(builder, returnType, BindingMapping.getGetterMethodName(localName().getLocalName()));
235     }
236
237     final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
238             final Type returnType, final String methodName) {
239         final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
240
241         annotateDeprecatedIfNecessary(getMethod);
242
243         statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
244             .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
245
246         return getMethod;
247     }
248
249     void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
250         // No-op in most cases
251     }
252
253     final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
254         constructGetter(builder, returnType, BindingMapping.getRequireMethodName(localName().getLocalName()))
255             .setDefault(true)
256             .setMechanics(ValueMechanics.NONNULL);
257     }
258
259     void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
260             final @NonNull TypeBuilderFactory builderFactory) {
261         // No-op for most cases
262     }
263
264     @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
265         return getGeneratedType(builderFactory);
266     }
267
268     final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
269         annotateDeprecatedIfNecessary(statement, builder);
270     }
271
272     @Override
273     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
274         helper.add("argument", statement.argument());
275
276         if (isAddedByUses()) {
277             helper.addValue("addedByUses");
278         }
279         if (isAugmenting()) {
280             helper.addValue("augmenting");
281         }
282         return helper;
283     }
284 }