69a2f217e51e242d9408940958e1f232935ec471
[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<?> prev;
54     /**
55      * Field holding the original incarnation, i.e. the terminal node along {@link #prev} links.
56      */
57     private AbstractExplicitGenerator<?> 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's statements as well as
89      * to all child generators.
90      *
91      * @return Number of generators that remain unlinked.
92      */
93     long linkOriginalGenerator() {
94         if (orig != null) {
95             // Original already linked
96             return 0;
97         }
98
99         if (prev == null) {
100             LOG.trace("Linking {}", this);
101
102             if (!isAddedByUses() && !isAugmenting()) {
103                 orig = prev = this;
104                 LOG.trace("Linked {} to self", this);
105                 return 0;
106             }
107
108             final var link = getParent().getOriginalChild(getQName());
109             prev = link.previous();
110             orig = link.original();
111             if (orig != null) {
112                 LOG.trace("Linked {} to {} original {}", this, prev, orig);
113                 return 0;
114             }
115
116             LOG.trace("Linked {} to intermediate {}", this, prev);
117             return 1;
118         }
119
120         orig = prev.originalLink().original();
121         if (orig != null) {
122             LOG.trace("Linked {} to original {}", this, orig);
123             return 0;
124         }
125         return 1;
126     }
127
128     /**
129      * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
130      *
131      * @return Previous incarnation or {@code null}
132      */
133     final @Nullable AbstractExplicitGenerator<?> previous() {
134         final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
135         return local == this ? null : local;
136     }
137
138     /**
139      * Return the original incarnation of this generator, or self if this is the original generator.
140      *
141      * @return Original incarnation of this generator
142      */
143     @NonNull AbstractExplicitGenerator<?> getOriginal() {
144         return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
145     }
146
147     /**
148      * Return the link towards the original generator.
149      *
150      * @return Link towards the original generator.
151      */
152     final @NonNull OriginalLink originalLink() {
153         final var local = prev;
154         if (local == null) {
155             return OriginalLink.partial(this);
156         } else if (local == this) {
157             return OriginalLink.complete(this);
158         } else {
159             return OriginalLink.partial(local);
160         }
161     }
162
163     @Nullable AbstractExplicitGenerator<?> findSchemaTreeGenerator(final QName qname) {
164         for (Generator child : this) {
165             if (child instanceof AbstractExplicitGenerator) {
166                 final AbstractExplicitGenerator<?> gen = (AbstractExplicitGenerator<?>) child;
167                 final EffectiveStatement<?, ?> stmt = gen.statement();
168                 if (stmt instanceof SchemaTreeEffectiveStatement && qname.equals(stmt.argument())) {
169                     return gen;
170                 }
171             }
172         }
173         return null;
174     }
175
176     final @NonNull QName getQName() {
177         final Object arg = statement.argument();
178         verify(arg instanceof QName, "Unexpected argument %s", arg);
179         return (QName) arg;
180     }
181
182     @NonNull AbstractQName localName() {
183         // FIXME: this should be done in a nicer way
184         final Object argument = statement.argument();
185         verify(argument instanceof AbstractQName, "Illegal argument %s", argument);
186         return (AbstractQName) argument;
187     }
188
189     @Override
190     ClassPlacement classPlacement() {
191         // We process nodes introduced through augment or uses separately
192         // FIXME: this is not quite right!
193         return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
194     }
195
196     @Override
197     Member createMember(final CollisionDomain domain) {
198         return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
199     }
200
201     void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
202             final @NonNull TypeBuilderFactory builderFactory) {
203         if (isAugmenting()) {
204             // Do not process augmented nodes: they will be taken care of in their home augmentation
205             return;
206         }
207         if (isAddedByUses()) {
208             // If this generator has been added by a uses node, it is already taken care of by the corresponding
209             // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
210             // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
211             // resolving the reference.
212             addAsGetterMethodOverride(builder, builderFactory);
213             return;
214         }
215
216         final Type returnType = methodReturnType(builderFactory);
217         constructGetter(builder, returnType);
218         constructRequire(builder, returnType);
219     }
220
221     MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
222         return constructGetter(builder, returnType, BindingMapping.getGetterMethodName(localName().getLocalName()));
223     }
224
225     final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
226             final Type returnType, final String methodName) {
227         final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
228
229         annotateDeprecatedIfNecessary(getMethod);
230
231         statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
232             .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
233
234         return getMethod;
235     }
236
237     void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
238         // No-op in most cases
239     }
240
241     final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
242         constructGetter(builder, returnType, BindingMapping.getRequireMethodName(localName().getLocalName()))
243             .setDefault(true)
244             .setMechanics(ValueMechanics.NONNULL);
245     }
246
247     void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
248             final @NonNull TypeBuilderFactory builderFactory) {
249         // No-op for most cases
250     }
251
252     @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
253         return getGeneratedType(builderFactory);
254     }
255
256     final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
257         annotateDeprecatedIfNecessary(statement, builder);
258     }
259
260     @Override
261     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
262         helper.add("argument", statement.argument());
263
264         if (isAddedByUses()) {
265             helper.addValue("addedByUses");
266         }
267         if (isAugmenting()) {
268             helper.addValue("augmenting");
269         }
270         return helper;
271     }
272 }