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