Track schema tree 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 java.util.Objects.requireNonNull;
12
13 import java.util.ArrayList;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.stream.Collectors;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.mdsal.binding.generator.impl.tree.SchemaTreeChild;
22 import org.opendaylight.mdsal.binding.generator.impl.tree.SchemaTreeParent;
23 import org.opendaylight.mdsal.binding.model.api.Enumeration;
24 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
25 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
26 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
27 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
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.ActionEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.AnydataEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.AnyxmlEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.ContainerEffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.IdentityEffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.stmt.InputEffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.stmt.LeafEffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.LeafListEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.ListEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationEffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.OutputEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
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  * <p>
61  * State tracking for resolution of children to their original declaration, i.e. back along the 'uses' and 'augment'
62  * axis. This is quite convoluted because we are traversing the generator tree recursively in the iteration order of
63  * children, but actual dependencies may require resolution in a different order, for example in the case of:
64  * <pre>
65  *   container foo {
66  *     uses bar {             // A
67  *       augment bar {        // B
68  *         container xyzzy;   // C
69  *       }
70  *     }
71  *
72  *     grouping bar {
73  *       container bar {      // D
74  *         uses baz;          // E
75  *       }
76  *     }
77  *
78  *     grouping baz {
79  *       leaf baz {           // F
80  *         type string;
81  *       }
82  *     }
83  *   }
84  *
85  *   augment /foo/bar/xyzzy { // G
86  *     leaf xyzzy {           // H
87  *       type string;
88  *     }
89  *   }
90  * </pre>
91  *
92  * <p>
93  * In this case we have three manifestations of 'leaf baz' -- marked A, E and F in the child iteration order. In order
94  * to perform a resolution, we first have to determine that F is the original definition, then establish that E is using
95  * the definition made by F and finally establish that A is using the definition made by F.
96  *
97  * <p>
98  * Dealing with augmentations is harder still, because we need to attach them to the original definition, hence for the
99  * /foo/bar container at A, we need to understand that its original definition is at D and we need to attach the augment
100  * at B to D. Futhermore we also need to establish that the augmentation at G attaches to container defined in C, so
101  * that the 'leaf xyzzy' existing as /foo/bar/xyzzy/xyzzy under C has its original definition at H.
102  *
103  * <p>
104  * Finally realize that the augment at G can actually exist in a different module and is shown in this example only
105  * the simplified form. That also means we could encounter G well before 'container foo' as well as we can have multiple
106  * such augments sprinkled across multiple modules having the same dependency rules as between C and G -- but they still
107  * have to form a directed acyclic graph and we partially deal with those complexities by having modules sorted by their
108  * dependencies.
109  *
110  * <p>
111  * For further details see {@link #linkOriginalGenerator()} and {@link #linkOriginalGeneratorRecursive()}, which deal
112  * with linking original instances in the tree iteration order. The part dealing with augment attachment lives mostly
113  * in {@link AugmentRequirement}.
114  */
115 public abstract class AbstractCompositeGenerator<T extends EffectiveStatement<?, ?>>
116         extends AbstractExplicitGenerator<T> implements SchemaTreeParent<T> {
117     private static final Logger LOG = LoggerFactory.getLogger(AbstractCompositeGenerator.class);
118
119     // FIXME: we want to allocate this lazily to lower memory footprint
120     private final @NonNull CollisionDomain domain = new CollisionDomain(this);
121     private final @NonNull List<Generator> childGenerators;
122     /**
123      * {@link SchemaTreeChild} children of this generator. Generator linkage is ensured on first access.
124      */
125     private final @NonNull List<SchemaTreeChild<?, ?>> schemaTreeChildren;
126
127     /**
128      * List of {@code augment} statements targeting this generator. This list is maintained only for the primary
129      * incarnation. This list is an evolving entity until after we have finished linkage of original statements. It is
130      * expected to be stable at the start of {@code step 2} in {@link GeneratorReactor#execute(TypeBuilderFactory)}.
131      */
132     private List<AbstractAugmentGenerator> augments = List.of();
133
134     /**
135      * List of {@code grouping} statements this statement references. This field is set once by
136      * {@link #linkUsesDependencies(GeneratorContext)}.
137      */
138     private List<GroupingGenerator> groupings;
139
140     /**
141      * List of composite children which have not been recursively processed. This may become a mutable list when we
142      * have some children which have not completed linking. Once we have completed linking of all children, including
143      * {@link #unlinkedChildren}, this will be set to {@code null}.
144      */
145     private List<AbstractCompositeGenerator<?>> unlinkedComposites = List.of();
146     /**
147      * List of children which have not had their original linked. This list starts of as null. When we first attempt
148      * linkage, it becomes non-null.
149      */
150     private List<Generator> unlinkedChildren;
151
152     AbstractCompositeGenerator(final T statement) {
153         super(statement);
154
155         final var children = createChildren(statement);
156         childGenerators = children.getKey();
157         schemaTreeChildren = children.getValue();
158     }
159
160     AbstractCompositeGenerator(final T statement, final AbstractCompositeGenerator<?> parent) {
161         super(statement, parent);
162
163         final var children = createChildren(statement);
164         childGenerators = children.getKey();
165         schemaTreeChildren = children.getValue();
166     }
167
168     @Override
169     public final Iterator<Generator> iterator() {
170         return childGenerators.iterator();
171     }
172
173     @Override
174     public List<SchemaTreeChild<?, ?>> schemaTreeChildren() {
175         for (var child : schemaTreeChildren) {
176             if (child instanceof SchemaTreePlaceholder) {
177                 ((SchemaTreePlaceholder<?, ?>) child).setGenerator(this);
178             }
179         }
180         return schemaTreeChildren;
181     }
182
183     @Override
184     final boolean isEmpty() {
185         return childGenerators.isEmpty();
186     }
187
188     final @Nullable AbstractExplicitGenerator<?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
189         return findGenerator(MatchStrategy.identity(), stmtPath, 0);
190     }
191
192     final @Nullable AbstractExplicitGenerator<?> findGenerator(final MatchStrategy childStrategy,
193             // TODO: Wouldn't this method be nicer with Deque<EffectiveStatement<?, ?>> ?
194             final List<EffectiveStatement<?, ?>> stmtPath, final int offset) {
195         final EffectiveStatement<?, ?> stmt = stmtPath.get(offset);
196
197         // Try direct children first, which is simple
198         AbstractExplicitGenerator<?> ret = childStrategy.findGenerator(stmt, childGenerators);
199         if (ret != null) {
200             final int next = offset + 1;
201             if (stmtPath.size() == next) {
202                 // Final step, return child
203                 return ret;
204             }
205             if (ret instanceof AbstractCompositeGenerator) {
206                 // We know how to descend down
207                 return ((AbstractCompositeGenerator<?>) ret).findGenerator(childStrategy, stmtPath, next);
208             }
209             // Yeah, don't know how to continue here
210             return null;
211         }
212
213         // At this point we are about to fork for augments or groupings. In either case only schema tree statements can
214         // be found this way. The fun part is that if we find a match and need to continue, we will use the same
215         // strategy for children as well. We now know that this (and subsequent) statements need to have a QName
216         // argument.
217         if (stmt instanceof SchemaTreeEffectiveStatement) {
218             // grouping -> uses instantiation changes the namespace to the local namespace of the uses site. We are
219             // going the opposite direction, hence we are changing namespace from local to the grouping's namespace.
220             for (GroupingGenerator gen : groupings) {
221                 final MatchStrategy strat = MatchStrategy.grouping(gen);
222                 ret = gen.findGenerator(strat, stmtPath, offset);
223                 if (ret != null) {
224                     return ret;
225                 }
226             }
227
228             // All augments are dead simple: they need to match on argument (which we expect to be a QName)
229             final MatchStrategy strat = MatchStrategy.augment();
230             for (AbstractAugmentGenerator gen : augments) {
231                 ret = gen.findGenerator(strat, stmtPath, offset);
232                 if (ret != null) {
233                     return ret;
234                 }
235             }
236         }
237         return null;
238     }
239
240     final @NonNull CollisionDomain domain() {
241         return domain;
242     }
243
244     final void linkUsesDependencies(final GeneratorContext context) {
245         // We are establishing two linkages here:
246         // - we are resolving 'uses' statements to their corresponding 'grouping' definitions
247         // - we propagate those groupings as anchors to any augment statements, which takes out some amount of guesswork
248         //   from augment+uses resolution case, as groupings know about their immediate augments as soon as uses linkage
249         //   is resolved
250         final List<GroupingGenerator> tmp = new ArrayList<>();
251         for (EffectiveStatement<?, ?> stmt : statement().effectiveSubstatements()) {
252             if (stmt instanceof UsesEffectiveStatement) {
253                 final UsesEffectiveStatement uses = (UsesEffectiveStatement) stmt;
254                 final GroupingGenerator grouping = context.resolveTreeScoped(GroupingGenerator.class, uses.argument());
255                 tmp.add(grouping);
256
257                 // Trigger resolution of uses/augment statements. This looks like guesswork, but there may be multiple
258                 // 'augment' statements in a 'uses' statement and keeping a ListMultimap here seems wasteful.
259                 for (Generator gen : this) {
260                     if (gen instanceof UsesAugmentGenerator) {
261                         ((UsesAugmentGenerator) gen).resolveGrouping(uses, grouping);
262                     }
263                 }
264             }
265         }
266         groupings = List.copyOf(tmp);
267     }
268
269     final void startUsesAugmentLinkage(final List<AugmentRequirement> requirements) {
270         for (Generator child : childGenerators) {
271             if (child instanceof UsesAugmentGenerator) {
272                 requirements.add(((UsesAugmentGenerator) child).startLinkage());
273             }
274             if (child instanceof AbstractCompositeGenerator) {
275                 ((AbstractCompositeGenerator<?>) child).startUsesAugmentLinkage(requirements);
276             }
277         }
278     }
279
280     final void addAugment(final AbstractAugmentGenerator augment) {
281         if (augments.isEmpty()) {
282             augments = new ArrayList<>(2);
283         }
284         augments.add(requireNonNull(augment));
285     }
286
287     /**
288      * Attempt to link the generator corresponding to the original definition for this generator's statements as well as
289      * to all child generators.
290      *
291      * @return Progress indication
292      */
293     final @NonNull LinkageProgress linkOriginalGeneratorRecursive() {
294         if (unlinkedComposites == null) {
295             // We have unset this list (see below), and there is nothing left to do
296             return LinkageProgress.DONE;
297         }
298
299         if (unlinkedChildren == null) {
300             unlinkedChildren = childGenerators.stream()
301                 .filter(AbstractExplicitGenerator.class::isInstance)
302                 .map(child -> (AbstractExplicitGenerator<?>) child)
303                 .collect(Collectors.toList());
304         }
305
306         var progress = LinkageProgress.NONE;
307         if (!unlinkedChildren.isEmpty()) {
308             // Attempt to make progress on child linkage
309             final var it = unlinkedChildren.iterator();
310             while (it.hasNext()) {
311                 final var child = it.next();
312                 if (child instanceof AbstractExplicitGenerator) {
313                     if (((AbstractExplicitGenerator<?>) child).linkOriginalGenerator()) {
314                         progress = LinkageProgress.SOME;
315                         it.remove();
316
317                         // If this is a composite generator we need to process is further
318                         if (child instanceof AbstractCompositeGenerator) {
319                             if (unlinkedComposites.isEmpty()) {
320                                 unlinkedComposites = new ArrayList<>();
321                             }
322                             unlinkedComposites.add((AbstractCompositeGenerator<?>) child);
323                         }
324                     }
325                 }
326             }
327
328             if (unlinkedChildren.isEmpty()) {
329                 // Nothing left to do, make sure any previously-allocated list can be scavenged
330                 unlinkedChildren = List.of();
331             }
332         }
333
334         // Process children of any composite children we have.
335         final var it = unlinkedComposites.iterator();
336         while (it.hasNext()) {
337             final var tmp = it.next().linkOriginalGeneratorRecursive();
338             if (tmp != LinkageProgress.NONE) {
339                 progress = LinkageProgress.SOME;
340             }
341             if (tmp == LinkageProgress.DONE) {
342                 it.remove();
343             }
344         }
345
346         if (unlinkedChildren.isEmpty() && unlinkedComposites.isEmpty()) {
347             // All done, set the list to null to indicate there is nothing left to do in this generator or any of our
348             // children.
349             unlinkedComposites = null;
350             return LinkageProgress.DONE;
351         }
352
353         return progress;
354     }
355
356     @Override
357     final AbstractCompositeGenerator<T> getOriginal() {
358         return (AbstractCompositeGenerator<T>) super.getOriginal();
359     }
360
361     @Override
362     final AbstractCompositeGenerator<T> tryOriginal() {
363         return (AbstractCompositeGenerator<T>) super.tryOriginal();
364     }
365
366     final <S extends EffectiveStatement<?, ?>> @Nullable OriginalLink<S> originalChild(final QName childQName) {
367         // First try groupings/augments ...
368         var found = findInferredGenerator(childQName);
369         if (found != null) {
370             return (OriginalLink<S>) OriginalLink.partial(found);
371         }
372
373         // ... no luck, we really need to start looking at our origin
374         final var prev = previous();
375         if (prev != null) {
376             final QName prevQName = childQName.bindTo(prev.getQName().getModule());
377             found = prev.findSchemaTreeGenerator(prevQName);
378             if (found != null) {
379                 return (OriginalLink<S>) found.originalLink();
380             }
381         }
382
383         return null;
384     }
385
386     @Override
387     final AbstractExplicitGenerator<?> findSchemaTreeGenerator(final QName qname) {
388         final AbstractExplicitGenerator<?> found = super.findSchemaTreeGenerator(qname);
389         return found != null ? found : findInferredGenerator(qname);
390     }
391
392     final @Nullable AbstractAugmentGenerator findAugmentForGenerator(final QName qname) {
393         for (var augment : augments) {
394             final var gen = augment.findSchemaTreeGenerator(qname);
395             if (gen != null) {
396                 return augment;
397             }
398         }
399         return null;
400     }
401
402     final @Nullable GroupingGenerator findGroupingForGenerator(final QName qname) {
403         for (GroupingGenerator grouping : groupings) {
404             final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
405             if (gen != null) {
406                 return grouping;
407             }
408         }
409         return null;
410     }
411
412     private @Nullable AbstractExplicitGenerator<?> findInferredGenerator(final QName qname) {
413         // First search our local groupings ...
414         for (var grouping : groupings) {
415             final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
416             if (gen != null) {
417                 return gen;
418             }
419         }
420         // ... next try local augments, which may have groupings themselves
421         for (var augment : augments) {
422             final var gen = augment.findSchemaTreeGenerator(qname);
423             if (gen != null) {
424                 return gen;
425             }
426         }
427         return null;
428     }
429
430     /**
431      * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
432      * is using.
433      *
434      * @param builder Target builder
435      * @param builderFactory factory for creating {@link TypeBuilder}s
436      * @return The number of groupings this type uses.
437      */
438     final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
439         for (GroupingGenerator grp : groupings) {
440             builder.addImplementsType(grp.getGeneratedType(builderFactory));
441         }
442         return groupings.size();
443     }
444
445     static final void addAugmentable(final GeneratedTypeBuilder builder) {
446         builder.addImplementsType(BindingTypes.augmentable(builder));
447     }
448
449     final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
450         for (Generator child : this) {
451             // Only process explicit generators here
452             if (child instanceof AbstractExplicitGenerator) {
453                 ((AbstractExplicitGenerator<?>) child).addAsGetterMethod(builder, builderFactory);
454             }
455
456             final GeneratedType enclosedType = child.enclosedType(builderFactory);
457             if (enclosedType instanceof GeneratedTransferObject) {
458                 builder.addEnclosingTransferObject((GeneratedTransferObject) enclosedType);
459             } else if (enclosedType instanceof Enumeration) {
460                 builder.addEnumeration((Enumeration) enclosedType);
461             } else {
462                 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
463             }
464         }
465     }
466
467     private Entry<List<Generator>, List<SchemaTreeChild<?, ?>>> createChildren(
468             final EffectiveStatement<?, ?> statement) {
469         final var tmp = new ArrayList<Generator>();
470         final var tmpAug = new ArrayList<AbstractAugmentGenerator>();
471         final var tmpSchema = new ArrayList<SchemaTreeChild<?, ?>>();
472
473         for (var stmt : statement.effectiveSubstatements()) {
474             if (stmt instanceof ActionEffectiveStatement) {
475                 final var cast = (ActionEffectiveStatement) stmt;
476                 if (isAugmenting(cast)) {
477                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, ActionGenerator.class));
478                 } else {
479                     tmp.add(new ActionGenerator(cast, this));
480                 }
481             } else if (stmt instanceof AnydataEffectiveStatement) {
482                 final var cast = (AnydataEffectiveStatement) stmt;
483                 if (isAugmenting(stmt)) {
484                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, OpaqueObjectGenerator.class));
485                 } else {
486                     tmp.add(new OpaqueObjectGenerator<>(cast, this));
487                 }
488             } else if (stmt instanceof AnyxmlEffectiveStatement) {
489                 final var cast = (AnyxmlEffectiveStatement) stmt;
490                 if (isAugmenting(stmt)) {
491                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, OpaqueObjectGenerator.class));
492                 } else {
493                     tmp.add(new OpaqueObjectGenerator<>(cast, this));
494                 }
495             } else if (stmt instanceof CaseEffectiveStatement) {
496                 tmp.add(new CaseGenerator((CaseEffectiveStatement) stmt, this));
497             } else if (stmt instanceof ChoiceEffectiveStatement) {
498                 final var cast = (ChoiceEffectiveStatement) stmt;
499                 // FIXME: use isOriginalDeclaration() ?
500                 if (isAddedByUses(stmt)) {
501                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, ChoiceGenerator.class));
502                 } else {
503                     tmp.add(new ChoiceGenerator(cast, this));
504                 }
505             } else if (stmt instanceof ContainerEffectiveStatement) {
506                 final var cast = (ContainerEffectiveStatement) stmt;
507                 if (isOriginalDeclaration(stmt)) {
508                     tmp.add(new ContainerGenerator((ContainerEffectiveStatement) stmt, this));
509                 } else {
510                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, ContainerGenerator.class));
511                 }
512             } else if (stmt instanceof GroupingEffectiveStatement) {
513                 tmp.add(new GroupingGenerator((GroupingEffectiveStatement) stmt, this));
514             } else if (stmt instanceof IdentityEffectiveStatement) {
515                 tmp.add(new IdentityGenerator((IdentityEffectiveStatement) stmt, this));
516             } else if (stmt instanceof InputEffectiveStatement) {
517                 // FIXME: do not generate legacy RPC layout
518                 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((InputEffectiveStatement) stmt, this)
519                     : new OperationContainerGenerator((InputEffectiveStatement) stmt, this));
520             } else if (stmt instanceof LeafEffectiveStatement) {
521                 final var cast = (LeafEffectiveStatement) stmt;
522                 if (isAugmenting(stmt)) {
523                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, LeafGenerator.class));
524                 } else {
525                     tmp.add(new LeafGenerator(cast, this));
526                 }
527             } else if (stmt instanceof LeafListEffectiveStatement) {
528                 final var cast = (LeafListEffectiveStatement) stmt;
529                 if (isAugmenting(stmt)) {
530                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, LeafListGenerator.class));
531                 } else {
532                     tmp.add(new LeafListGenerator((LeafListEffectiveStatement) stmt, this));
533                 }
534             } else if (stmt instanceof ListEffectiveStatement) {
535                 final var cast = (ListEffectiveStatement) stmt;
536                 if (isOriginalDeclaration(stmt)) {
537                     final ListGenerator listGen = new ListGenerator(cast, this);
538                     tmp.add(listGen);
539
540                     final KeyGenerator keyGen = listGen.keyGenerator();
541                     if (keyGen != null) {
542                         tmp.add(keyGen);
543                     }
544                 } else {
545                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, ListGenerator.class));
546                 }
547             } else if (stmt instanceof NotificationEffectiveStatement) {
548                 final var cast = (NotificationEffectiveStatement) stmt;
549                 if (isAugmenting(stmt)) {
550                     tmpSchema.add(new SchemaTreePlaceholder<>(cast, NotificationGenerator.class));
551                 } else {
552                     tmp.add(new NotificationGenerator(cast, this));
553                 }
554             } else if (stmt instanceof OutputEffectiveStatement) {
555                 // FIXME: do not generate legacy RPC layout
556                 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((OutputEffectiveStatement) stmt, this)
557                     : new OperationContainerGenerator((OutputEffectiveStatement) stmt, this));
558             } else if (stmt instanceof RpcEffectiveStatement) {
559                 tmp.add(new RpcGenerator((RpcEffectiveStatement) stmt, this));
560             } else if (stmt instanceof TypedefEffectiveStatement) {
561                 tmp.add(new TypedefGenerator((TypedefEffectiveStatement) stmt, this));
562             } else if (stmt instanceof AugmentEffectiveStatement) {
563                 // FIXME: MDSAL-695: So here we are ignoring any augment which is not in a module, while the 'uses'
564                 //                   processing takes care of the rest. There are two problems here:
565                 //
566                 //                   1) this could be an augment introduced through uses -- in this case we are picking
567                 //                      confusing it with this being its declaration site, we should probably be
568                 //                      ignoring it, but then
569                 //
570                 //                   2) we are losing track of AugmentEffectiveStatement for which we do not generate
571                 //                      interfaces -- and recover it at runtime through explicit walk along the
572                 //                      corresponding AugmentationSchemaNode.getOriginalDefinition() pointer
573                 //
574                 //                   So here is where we should decide how to handle this augment, and make sure we
575                 //                   retain information about this being an alias. That will serve as the base for keys
576                 //                   in the augment -> original map we provide to BindingRuntimeTypes.
577                 if (this instanceof ModuleGenerator) {
578                     tmpAug.add(new ModuleAugmentGenerator((AugmentEffectiveStatement) stmt, this));
579                 }
580             } else if (stmt instanceof UsesEffectiveStatement) {
581                 final UsesEffectiveStatement uses = (UsesEffectiveStatement) stmt;
582                 for (EffectiveStatement<?, ?> usesSub : uses.effectiveSubstatements()) {
583                     if (usesSub instanceof AugmentEffectiveStatement) {
584                         tmpAug.add(new UsesAugmentGenerator((AugmentEffectiveStatement) usesSub, uses, this));
585                     }
586                 }
587             } else {
588                 LOG.trace("Ignoring statement {}", stmt);
589             }
590         }
591
592         // Add any SchemaTreeChild generators to the list
593         for (var child : tmp) {
594             if (child instanceof SchemaTreeChild) {
595                 tmpSchema.add((SchemaTreeChild<?, ?>) child);
596             }
597         }
598
599         // Sort augments and add them last. This ensures child iteration order always reflects potential
600         // interdependencies, hence we do not need to worry about them. This is extremely important, as there are a
601         // number of places where we would have to either move the logic to parent statement and explicitly filter/sort
602         // substatements to establish this order.
603         tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
604         tmp.addAll(tmpAug);
605
606         // Compatibility FooService and FooListener interfaces, only generated for modules.
607         if (this instanceof ModuleGenerator) {
608             final ModuleGenerator moduleGen = (ModuleGenerator) this;
609
610             final List<NotificationGenerator> notifs = tmp.stream()
611                 .filter(NotificationGenerator.class::isInstance)
612                 .map(NotificationGenerator.class::cast)
613                 .collect(Collectors.toUnmodifiableList());
614             if (!notifs.isEmpty()) {
615                 tmp.add(new NotificationServiceGenerator(moduleGen, notifs));
616             }
617
618             final List<RpcGenerator> rpcs = tmp.stream()
619                 .filter(RpcGenerator.class::isInstance)
620                 .map(RpcGenerator.class::cast)
621                 .collect(Collectors.toUnmodifiableList());
622             if (!rpcs.isEmpty()) {
623                 tmp.add(new RpcServiceGenerator(moduleGen, rpcs));
624             }
625         }
626
627         return Map.entry(List.copyOf(tmp), List.copyOf(tmpSchema));
628     }
629
630     // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
631     // CopyableNode and AddedByUsesAware
632     private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
633         if (stmt instanceof AddedByUsesAware) {
634             if (((AddedByUsesAware) stmt).isAddedByUses()
635                 || stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting()) {
636                 return false;
637             }
638         }
639         return true;
640     }
641
642     private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
643         return stmt instanceof AddedByUsesAware && ((AddedByUsesAware) stmt).isAddedByUses();
644     }
645
646     private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
647         return stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting();
648     }
649 }