Enforce explicit generator linkage
[mdsal.git] / binding / mdsal-binding-generator / src / main / java / org / opendaylight / mdsal / binding / generator / impl / reactor / AbstractCompositeGenerator.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 java.util.ArrayList;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.stream.Collectors;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.mdsal.binding.generator.impl.reactor.OriginalLink.Partial;
21 import org.opendaylight.mdsal.binding.model.api.Enumeration;
22 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
23 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
24 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
25 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
29 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.AnydataEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.AnyxmlEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.ContainerEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.IdentityEffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.InputEffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.stmt.LeafEffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.stmt.LeafListEffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ListEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.OutputEffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.ri.type.TypeBuilder;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * A composite generator. Composite generators may contain additional children, which end up being mapped into
57  * the naming hierarchy 'under' the composite generator. To support this use case, each composite has a Java package
58  * name assigned.
59  */
60 abstract class AbstractCompositeGenerator<T extends EffectiveStatement<?, ?>> extends AbstractExplicitGenerator<T> {
61     private static final Logger LOG = LoggerFactory.getLogger(AbstractCompositeGenerator.class);
62
63     private final @NonNull CollisionDomain domain = new CollisionDomain(this);
64     private final List<Generator> children;
65
66     private List<AbstractAugmentGenerator> augments = List.of();
67     private List<GroupingGenerator> groupings;
68
69     // Performance optimization: if this is true, we have ascertained our original definition as well that of all our
70     // children
71     private boolean originalsResolved;
72
73     AbstractCompositeGenerator(final T statement) {
74         super(statement);
75         children = createChildren(statement);
76     }
77
78     AbstractCompositeGenerator(final T statement, final AbstractCompositeGenerator<?> parent) {
79         super(statement, parent);
80         children = createChildren(statement);
81     }
82
83     @Override
84     public final Iterator<Generator> iterator() {
85         return children.iterator();
86     }
87
88     @Override
89     final boolean isEmpty() {
90         return children.isEmpty();
91     }
92
93     final @Nullable AbstractExplicitGenerator<?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
94         return findGenerator(MatchStrategy.identity(), stmtPath, 0);
95     }
96
97     final @Nullable AbstractExplicitGenerator<?> findGenerator(final MatchStrategy childStrategy,
98             // TODO: Wouldn't this method be nicer with Deque<EffectiveStatement<?, ?>> ?
99             final List<EffectiveStatement<?, ?>> stmtPath, final int offset) {
100         final EffectiveStatement<?, ?> stmt = stmtPath.get(offset);
101
102         // Try direct children first, which is simple
103         AbstractExplicitGenerator<?> ret = childStrategy.findGenerator(stmt, children);
104         if (ret != null) {
105             final int next = offset + 1;
106             if (stmtPath.size() == next) {
107                 // Final step, return child
108                 return ret;
109             }
110             if (ret instanceof AbstractCompositeGenerator) {
111                 // We know how to descend down
112                 return ((AbstractCompositeGenerator<?>) ret).findGenerator(childStrategy, stmtPath, next);
113             }
114             // Yeah, don't know how to continue here
115             return null;
116         }
117
118         // At this point we are about to fork for augments or groupings. In either case only schema tree statements can
119         // be found this way. The fun part is that if we find a match and need to continue, we will use the same
120         // strategy for children as well. We now know that this (and subsequent) statements need to have a QName
121         // argument.
122         if (stmt instanceof SchemaTreeEffectiveStatement) {
123             // grouping -> uses instantiation changes the namespace to the local namespace of the uses site. We are
124             // going the opposite direction, hence we are changing namespace from local to the grouping's namespace.
125             for (GroupingGenerator gen : groupings) {
126                 final MatchStrategy strat = MatchStrategy.grouping(gen);
127                 ret = gen.findGenerator(strat, stmtPath, offset);
128                 if (ret != null) {
129                     return ret;
130                 }
131             }
132
133             // All augments are dead simple: they need to match on argument (which we expect to be a QName)
134             final MatchStrategy strat = MatchStrategy.augment();
135             for (AbstractAugmentGenerator gen : augments) {
136                 ret = gen.findGenerator(strat, stmtPath, offset);
137                 if (ret != null) {
138                     return ret;
139                 }
140             }
141         }
142         return null;
143     }
144
145     final @NonNull CollisionDomain domain() {
146         return domain;
147     }
148
149     final void linkUsesDependencies(final GeneratorContext context) {
150         // We are resolving 'uses' statements to their corresponding 'grouping' definitions
151         final List<GroupingGenerator> tmp = new ArrayList<>();
152         for (EffectiveStatement<?, ?> stmt : statement().effectiveSubstatements()) {
153             if (stmt instanceof UsesEffectiveStatement) {
154                 tmp.add(context.resolveTreeScoped(GroupingGenerator.class, ((UsesEffectiveStatement) stmt).argument()));
155             }
156         }
157         groupings = List.copyOf(tmp);
158     }
159
160     final void addAugment(final AbstractAugmentGenerator augment) {
161         if (augments.isEmpty()) {
162             augments = new ArrayList<>(2);
163         }
164         augments.add(requireNonNull(augment));
165     }
166
167     @Override
168     long linkOriginalGenerator() {
169         if (originalsResolved) {
170             return 0;
171         }
172
173         long remaining = super.linkOriginalGenerator();
174         if (remaining == 0) {
175             for (Generator child : children) {
176                 if (child instanceof AbstractExplicitGenerator) {
177                     remaining += ((AbstractExplicitGenerator<?>) child).linkOriginalGenerator();
178                 }
179             }
180             if (remaining == 0) {
181                 originalsResolved = true;
182             }
183         }
184         return remaining;
185     }
186
187     @Override
188     final AbstractCompositeGenerator<?> getOriginal() {
189         return (AbstractCompositeGenerator<?>) super.getOriginal();
190     }
191
192     final @NonNull OriginalLink getOriginalChild(final QName childQName) {
193         // First try groupings/augments ...
194         final AbstractExplicitGenerator<?> found = findInferredGenerator(childQName);
195         if (found != null) {
196             return new Partial(found);
197         }
198
199         // ... no luck, we really need to start looking at our origin
200         final AbstractExplicitGenerator<?> prev = verifyNotNull(previous(),
201             "Failed to find %s in scope of %s", childQName, this);
202
203         final QName prevQName = childQName.bindTo(prev.getQName().getModule());
204         return verifyNotNull(prev.findSchemaTreeGenerator(prevQName),
205             "Failed to find child %s (proxy for %s) in %s", prevQName, childQName, prev).originalLink();
206     }
207
208     @Override
209     final AbstractExplicitGenerator<?> findSchemaTreeGenerator(final QName qname) {
210         final AbstractExplicitGenerator<?> found = super.findSchemaTreeGenerator(qname);
211         return found != null ? found : findInferredGenerator(qname);
212     }
213
214     private @Nullable AbstractExplicitGenerator<?> findInferredGenerator(final QName qname) {
215         // First search our local groupings ...
216         for (GroupingGenerator grouping : groupings) {
217             final AbstractExplicitGenerator<?> gen = grouping.findSchemaTreeGenerator(
218                 qname.bindTo(grouping.statement().argument().getModule()));
219             if (gen != null) {
220                 return gen;
221             }
222         }
223         // ... next try local augments, which may have groupings themselves
224         for (AbstractAugmentGenerator augment : augments) {
225             final AbstractExplicitGenerator<?> gen = augment.findSchemaTreeGenerator(qname);
226             if (gen != null) {
227                 return gen;
228             }
229         }
230         return null;
231     }
232
233     final @NonNull AbstractExplicitGenerator<?> resolveSchemaNode(final SchemaNodeIdentifier path) {
234         // This is not quite straightforward. 'path' works on top of schema tree, which is instantiated view. Since we
235         // do not generate duplicate instantiations along 'uses' path, findSchemaTreeGenerator() would satisfy our
236         // request by returning a child of the source 'grouping'.
237         //
238         // When that happens, our subsequent lookups need to adjust the namespace being looked up to the grouping's
239         // namespace... except for the case when the step is actually an augmentation, in which case we must not make
240         // that adjustment.
241         //
242         // Hence we deal with this lookup recursively, dropping namespace hints when we cross into groupings.
243         return resolveSchemaNode(path.getNodeIdentifiers().iterator(), null);
244     }
245
246     private @NonNull AbstractExplicitGenerator<?> resolveSchemaNode(final Iterator<QName> qnames,
247             final @Nullable QNameModule localNamespace) {
248         final QName qname = qnames.next();
249
250         // First try local augments, as those are guaranteed to match namespace exactly
251         for (AbstractAugmentGenerator augment : augments) {
252             final AbstractExplicitGenerator<?> gen = augment.findSchemaTreeGenerator(qname);
253             if (gen != null) {
254                 return resolveNext(gen, qnames, null);
255             }
256         }
257
258         // Second try local groupings, as those perform their own adjustment
259         for (GroupingGenerator grouping : groupings) {
260             final QNameModule ns = grouping.statement().argument().getModule();
261             final AbstractExplicitGenerator<?> gen = grouping.findSchemaTreeGenerator(qname.bindTo(ns));
262             if (gen != null) {
263                 return resolveNext(gen, qnames, ns);
264             }
265         }
266
267         // Lastly try local statements adjusted with namespace, if applicable
268         final QName lookup = localNamespace == null ? qname : qname.bindTo(localNamespace);
269         final AbstractExplicitGenerator<?> gen = verifyNotNull(super.findSchemaTreeGenerator(lookup),
270             "Failed to find %s as %s in %s", qname, lookup, this);
271         return resolveNext(gen, qnames, localNamespace);
272     }
273
274     private static @NonNull AbstractExplicitGenerator<?> resolveNext(final @NonNull AbstractExplicitGenerator<?> gen,
275             final Iterator<QName> qnames, final QNameModule localNamespace) {
276         if (qnames.hasNext()) {
277             verify(gen instanceof AbstractCompositeGenerator, "Unexpected generator %s", gen);
278             return ((AbstractCompositeGenerator<?>) gen).resolveSchemaNode(qnames, localNamespace);
279         }
280         return gen;
281     }
282
283     /**
284      * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
285      * is using.
286      *
287      * @param builder Target builder
288      * @param builderFactory factory for creating {@link TypeBuilder}s
289      * @return The number of groupings this type uses.
290      */
291     final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
292         for (GroupingGenerator grp : groupings) {
293             builder.addImplementsType(grp.getGeneratedType(builderFactory));
294         }
295         return groupings.size();
296     }
297
298     static final void addAugmentable(final GeneratedTypeBuilder builder) {
299         builder.addImplementsType(BindingTypes.augmentable(builder));
300     }
301
302     final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
303         for (Generator child : this) {
304             // Only process explicit generators here
305             if (child instanceof AbstractExplicitGenerator) {
306                 ((AbstractExplicitGenerator<?>) child).addAsGetterMethod(builder, builderFactory);
307             }
308
309             final GeneratedType enclosedType = child.enclosedType(builderFactory);
310             if (enclosedType instanceof GeneratedTransferObject) {
311                 builder.addEnclosingTransferObject((GeneratedTransferObject) enclosedType);
312             } else if (enclosedType instanceof Enumeration) {
313                 builder.addEnumeration((Enumeration) enclosedType);
314             } else {
315                 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
316             }
317         }
318     }
319
320     private List<Generator> createChildren(final EffectiveStatement<?, ?> statement) {
321         final List<Generator> tmp = new ArrayList<>();
322         final List<AbstractAugmentGenerator> tmpAug = new ArrayList<>();
323
324         for (EffectiveStatement<?, ?> stmt : statement.effectiveSubstatements()) {
325             if (stmt instanceof ActionEffectiveStatement) {
326                 if (!isAugmenting(stmt)) {
327                     tmp.add(new ActionGenerator((ActionEffectiveStatement) stmt, this));
328                 }
329             } else if (stmt instanceof AnydataEffectiveStatement) {
330                 if (!isAugmenting(stmt)) {
331                     tmp.add(new OpaqueObjectGenerator<>((AnydataEffectiveStatement) stmt, this));
332                 }
333             } else if (stmt instanceof AnyxmlEffectiveStatement) {
334                 if (!isAugmenting(stmt)) {
335                     tmp.add(new OpaqueObjectGenerator<>((AnyxmlEffectiveStatement) stmt, this));
336                 }
337             } else if (stmt instanceof CaseEffectiveStatement) {
338                 tmp.add(new CaseGenerator((CaseEffectiveStatement) stmt, this));
339             } else if (stmt instanceof ChoiceEffectiveStatement) {
340                 // FIXME: use isOriginalDeclaration() ?
341                 if (!isAddedByUses(stmt)) {
342                     tmp.add(new ChoiceGenerator((ChoiceEffectiveStatement) stmt, this));
343                 }
344             } else if (stmt instanceof ContainerEffectiveStatement) {
345                 if (isOriginalDeclaration(stmt)) {
346                     tmp.add(new ContainerGenerator((ContainerEffectiveStatement) stmt, this));
347                 }
348             } else if (stmt instanceof GroupingEffectiveStatement) {
349                 tmp.add(new GroupingGenerator((GroupingEffectiveStatement) stmt, this));
350             } else if (stmt instanceof IdentityEffectiveStatement) {
351                 tmp.add(new IdentityGenerator((IdentityEffectiveStatement) stmt, this));
352             } else if (stmt instanceof InputEffectiveStatement) {
353                 // FIXME: do not generate legacy RPC layout
354                 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((InputEffectiveStatement) stmt, this)
355                     : new OperationContainerGenerator((InputEffectiveStatement) stmt, this));
356             } else if (stmt instanceof LeafEffectiveStatement) {
357                 if (!isAugmenting(stmt)) {
358                     tmp.add(new LeafGenerator((LeafEffectiveStatement) stmt, this));
359                 }
360             } else if (stmt instanceof LeafListEffectiveStatement) {
361                 if (!isAugmenting(stmt)) {
362                     tmp.add(new LeafListGenerator((LeafListEffectiveStatement) stmt, this));
363                 }
364             } else if (stmt instanceof ListEffectiveStatement) {
365                 if (isOriginalDeclaration(stmt)) {
366                     final ListGenerator listGen = new ListGenerator((ListEffectiveStatement) stmt, this);
367                     tmp.add(listGen);
368
369                     final KeyGenerator keyGen = listGen.keyGenerator();
370                     if (keyGen != null) {
371                         tmp.add(keyGen);
372                     }
373                 }
374             } else if (stmt instanceof NotificationEffectiveStatement) {
375                 if (!isAugmenting(stmt)) {
376                     tmp.add(new NotificationGenerator((NotificationEffectiveStatement) stmt, this));
377                 }
378             } else if (stmt instanceof OutputEffectiveStatement) {
379                 // FIXME: do not generate legacy RPC layout
380                 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((OutputEffectiveStatement) stmt, this)
381                     : new OperationContainerGenerator((OutputEffectiveStatement) stmt, this));
382             } else if (stmt instanceof RpcEffectiveStatement) {
383                 tmp.add(new RpcGenerator((RpcEffectiveStatement) stmt, this));
384             } else if (stmt instanceof TypedefEffectiveStatement) {
385                 tmp.add(new TypedefGenerator((TypedefEffectiveStatement) stmt, this));
386             } else if (stmt instanceof AugmentEffectiveStatement) {
387                 // FIXME: MDSAL-695: So here we are ignoring any augment which is not in a module, while the 'uses'
388                 //                   processing takes care of the rest. There are two problems here:
389                 //
390                 //                   1) this could be an augment introduced through uses -- in this case we are picking
391                 //                      confusing it with this being its declaration site, we should probably be
392                 //                      ignoring it, but then
393                 //
394                 //                   2) we are losing track of AugmentEffectiveStatement for which we do not generate
395                 //                      interfaces -- and recover it at runtime through explicit walk along the
396                 //                      corresponding AugmentationSchemaNode.getOriginalDefinition() pointer
397                 //
398                 //                   So here is where we should decide how to handle this augment, and make sure we
399                 //                   retain information about this being an alias. That will serve as the base for keys
400                 //                   in the augment -> original map we provide to BindingRuntimeTypes.
401                 if (this instanceof ModuleGenerator) {
402                     tmpAug.add(new ModuleAugmentGenerator((AugmentEffectiveStatement) stmt, this));
403                 }
404             } else if (stmt instanceof UsesEffectiveStatement) {
405                 final UsesEffectiveStatement uses = (UsesEffectiveStatement) stmt;
406                 for (EffectiveStatement<?, ?> usesSub : uses.effectiveSubstatements()) {
407                     if (usesSub instanceof AugmentEffectiveStatement) {
408                         tmpAug.add(new UsesAugmentGenerator((AugmentEffectiveStatement) usesSub, this));
409                     }
410                 }
411             } else {
412                 LOG.trace("Ignoring statement {}", stmt);
413                 continue;
414             }
415         }
416
417         // Sort augments and add them last. This ensures child iteration order always reflects potential
418         // interdependencies, hence we do not need to worry about them.
419         tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
420         tmp.addAll(tmpAug);
421
422         // Compatibility FooService and FooListener interfaces, only generated for modules.
423         if (this instanceof ModuleGenerator) {
424             final ModuleGenerator moduleGen = (ModuleGenerator) this;
425
426             final List<NotificationGenerator> notifs = tmp.stream()
427                 .filter(NotificationGenerator.class::isInstance)
428                 .map(NotificationGenerator.class::cast)
429                 .collect(Collectors.toUnmodifiableList());
430             if (!notifs.isEmpty()) {
431                 tmp.add(new NotificationServiceGenerator(moduleGen, notifs));
432             }
433
434             final List<RpcGenerator> rpcs = tmp.stream()
435                 .filter(RpcGenerator.class::isInstance)
436                 .map(RpcGenerator.class::cast)
437                 .collect(Collectors.toUnmodifiableList());
438             if (!rpcs.isEmpty()) {
439                 tmp.add(new RpcServiceGenerator(moduleGen, rpcs));
440             }
441         }
442
443         return List.copyOf(tmp);
444     }
445
446     // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
447     // CopyableNode and AddedByUsesAware
448     private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
449         if (stmt instanceof AddedByUsesAware) {
450             if (((AddedByUsesAware) stmt).isAddedByUses()
451                 || stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting()) {
452                 return false;
453             }
454         }
455         return true;
456     }
457
458     private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
459         return stmt instanceof AddedByUsesAware && ((AddedByUsesAware) stmt).isAddedByUses();
460     }
461
462     private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
463         return stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting();
464     }
465 }