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