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