Use an instanceof pattern
[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;
24 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
25 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
26 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
27 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
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<S extends EffectiveStatement<?, ?>, R extends CompositeRuntimeType>
116         extends AbstractExplicitGenerator<S, R> {
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     /**
124      * List of {@code augment} statements targeting this generator. This list is maintained only for the primary
125      * incarnation. This list is an evolving entity until after we have finished linkage of original statements. It is
126      * expected to be stable at the start of {@code step 2} in {@link GeneratorReactor#execute(TypeBuilderFactory)}.
127      */
128     private @NonNull List<AbstractAugmentGenerator> augments = List.of();
129
130     /**
131      * List of {@code grouping} statements this statement references. This field is set once by
132      * {@link #linkUsesDependencies(GeneratorContext)}.
133      */
134     private List<GroupingGenerator> groupings;
135
136     /**
137      * List of composite children which have not been recursively processed. This may become a mutable list when we
138      * have some children which have not completed linking. Once we have completed linking of all children, including
139      * {@link #unlinkedChildren}, this will be set to {@code null}.
140      */
141     private List<AbstractCompositeGenerator<?, ?>> unlinkedComposites = List.of();
142     /**
143      * List of children which have not had their original linked. This list starts of as null. When we first attempt
144      * linkage, it becomes non-null.
145      */
146     private List<Generator> unlinkedChildren;
147
148     AbstractCompositeGenerator(final S statement) {
149         super(statement);
150         childGenerators = createChildren(statement);
151     }
152
153     AbstractCompositeGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
154         super(statement, parent);
155         childGenerators = createChildren(statement);
156     }
157
158     @Override
159     public final Iterator<Generator> iterator() {
160         return childGenerators.iterator();
161     }
162
163     final @NonNull List<AbstractAugmentGenerator> augments() {
164         return augments;
165     }
166
167     final @NonNull List<GroupingGenerator> groupings() {
168         return verifyNotNull(groupings, "Groupings not initialized in %s", this);
169     }
170
171     @Override
172     final R createExternalRuntimeType(final Type type) {
173         verify(type instanceof GeneratedType, "Unexpected type %s", type);
174         return createBuilder(statement()).populate(new AugmentResolver(), this).build((GeneratedType) type);
175     }
176
177     abstract @NonNull CompositeRuntimeTypeBuilder<S, R> createBuilder(S statement);
178
179     @Override
180     final R createInternalRuntimeType(final AugmentResolver resolver, final S statement, final Type type) {
181         verify(type instanceof GeneratedType, "Unexpected type %s", type);
182         return createBuilder(statement).populate(resolver, this).build((GeneratedType) type);
183     }
184
185     @Override
186     final boolean isEmpty() {
187         return childGenerators.isEmpty();
188     }
189
190     final @Nullable AbstractExplicitGenerator<?, ?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
191         return findGenerator(MatchStrategy.identity(), stmtPath, 0);
192     }
193
194     final @Nullable AbstractExplicitGenerator<?, ?> findGenerator(final MatchStrategy childStrategy,
195             // TODO: Wouldn't this method be nicer with Deque<EffectiveStatement<?, ?>> ?
196             final List<EffectiveStatement<?, ?>> stmtPath, final int offset) {
197         final var stmt = stmtPath.get(offset);
198
199         // Try direct children first, which is simple
200         var ret = childStrategy.findGenerator(stmt, childGenerators);
201         if (ret != null) {
202             final int next = offset + 1;
203             if (stmtPath.size() == next) {
204                 // Final step, return child
205                 return ret;
206             }
207             if (ret instanceof AbstractCompositeGenerator<?, ?> composite) {
208                 // We know how to descend down
209                 return composite.findGenerator(childStrategy, stmtPath, next);
210             }
211             // Yeah, don't know how to continue here
212             return null;
213         }
214
215         // At this point we are about to fork for augments or groupings. In either case only schema tree statements can
216         // be found this way. The fun part is that if we find a match and need to continue, we will use the same
217         // strategy for children as well. We now know that this (and subsequent) statements need to have a QName
218         // argument.
219         if (stmt instanceof SchemaTreeEffectiveStatement) {
220             // grouping -> uses instantiation changes the namespace to the local namespace of the uses site. We are
221             // going the opposite direction, hence we are changing namespace from local to the grouping's namespace.
222             for (GroupingGenerator gen : groupings) {
223                 final MatchStrategy strat = MatchStrategy.grouping(gen);
224                 ret = gen.findGenerator(strat, stmtPath, offset);
225                 if (ret != null) {
226                     return ret;
227                 }
228             }
229
230             // All augments are dead simple: they need to match on argument (which we expect to be a QName)
231             final MatchStrategy strat = MatchStrategy.augment();
232             for (AbstractAugmentGenerator gen : augments) {
233                 ret = gen.findGenerator(strat, stmtPath, offset);
234                 if (ret != null) {
235                     return ret;
236                 }
237             }
238         }
239         return null;
240     }
241
242     final @NonNull CollisionDomain domain() {
243         return domain;
244     }
245
246     final void linkUsesDependencies(final GeneratorContext context) {
247         // We are establishing two linkages here:
248         // - we are resolving 'uses' statements to their corresponding 'grouping' definitions
249         // - we propagate those groupings as anchors to any augment statements, which takes out some amount of guesswork
250         //   from augment+uses resolution case, as groupings know about their immediate augments as soon as uses linkage
251         //   is resolved
252         final var tmp = new ArrayList<GroupingGenerator>();
253         for (var stmt : statement().effectiveSubstatements()) {
254             if (stmt instanceof UsesEffectiveStatement uses) {
255                 final var grouping = context.resolveTreeScoped(GroupingGenerator.class, uses.argument());
256                 tmp.add(grouping);
257
258                 // Trigger resolution of uses/augment statements. This looks like guesswork, but there may be multiple
259                 // 'augment' statements in a 'uses' statement and keeping a ListMultimap here seems wasteful.
260                 for (Generator gen : this) {
261                     if (gen instanceof UsesAugmentGenerator usesGen) {
262                         usesGen.resolveGrouping(uses, grouping);
263                     }
264                 }
265             }
266         }
267         groupings = List.copyOf(tmp);
268     }
269
270     final void startUsesAugmentLinkage(final List<AugmentRequirement> requirements) {
271         for (var child : childGenerators) {
272             if (child instanceof UsesAugmentGenerator uses) {
273                 requirements.add(uses.startLinkage());
274             }
275             if (child instanceof AbstractCompositeGenerator<?, ?> composite) {
276                 composite.startUsesAugmentLinkage(requirements);
277             }
278         }
279     }
280
281     final void addAugment(final AbstractAugmentGenerator augment) {
282         if (augments.isEmpty()) {
283             augments = new ArrayList<>(2);
284         }
285         augments.add(requireNonNull(augment));
286     }
287
288     /**
289      * Attempt to link the generator corresponding to the original definition for this generator's statements as well as
290      * to all child generators.
291      *
292      * @return Progress indication
293      */
294     final @NonNull LinkageProgress linkOriginalGeneratorRecursive() {
295         if (unlinkedComposites == null) {
296             // We have unset this list (see below), and there is nothing left to do
297             return LinkageProgress.DONE;
298         }
299
300         if (unlinkedChildren == null) {
301             unlinkedChildren = childGenerators.stream()
302                 .filter(AbstractExplicitGenerator.class::isInstance)
303                 .map(child -> (AbstractExplicitGenerator<?, ?>) child)
304                 .collect(Collectors.toList());
305         }
306
307         var progress = LinkageProgress.NONE;
308         if (!unlinkedChildren.isEmpty()) {
309             // Attempt to make progress on child linkage
310             final var it = unlinkedChildren.iterator();
311             while (it.hasNext()) {
312                 final var child = it.next();
313                 if (child instanceof AbstractExplicitGenerator) {
314                     if (((AbstractExplicitGenerator<?, ?>) child).linkOriginalGenerator()) {
315                         progress = LinkageProgress.SOME;
316                         it.remove();
317
318                         // If this is a composite generator we need to process is further
319                         if (child instanceof AbstractCompositeGenerator<?, ?> composite) {
320                             if (unlinkedComposites.isEmpty()) {
321                                 unlinkedComposites = new ArrayList<>();
322                             }
323                             unlinkedComposites.add(composite);
324                         }
325                     }
326                 }
327             }
328
329             if (unlinkedChildren.isEmpty()) {
330                 // Nothing left to do, make sure any previously-allocated list can be scavenged
331                 unlinkedChildren = List.of();
332             }
333         }
334
335         // Process children of any composite children we have.
336         final var it = unlinkedComposites.iterator();
337         while (it.hasNext()) {
338             final var tmp = it.next().linkOriginalGeneratorRecursive();
339             if (tmp != LinkageProgress.NONE) {
340                 progress = LinkageProgress.SOME;
341             }
342             if (tmp == LinkageProgress.DONE) {
343                 it.remove();
344             }
345         }
346
347         if (unlinkedChildren.isEmpty() && unlinkedComposites.isEmpty()) {
348             // All done, set the list to null to indicate there is nothing left to do in this generator or any of our
349             // children.
350             unlinkedComposites = null;
351             return LinkageProgress.DONE;
352         }
353
354         return progress;
355     }
356
357     @Override
358     final AbstractCompositeGenerator<S, R> getOriginal() {
359         return (AbstractCompositeGenerator<S, R>) super.getOriginal();
360     }
361
362     @Override
363     final AbstractCompositeGenerator<S, R> tryOriginal() {
364         return (AbstractCompositeGenerator<S, R>) super.tryOriginal();
365     }
366
367     final <X extends EffectiveStatement<?, ?>, Y extends RuntimeType> @Nullable OriginalLink<X, Y> originalChild(
368             final QName childQName) {
369         // First try groupings/augments ...
370         var found = findInferredGenerator(childQName);
371         if (found != null) {
372             return (OriginalLink<X, Y>) OriginalLink.partial(found);
373         }
374
375         // ... no luck, we really need to start looking at our origin
376         final var prev = previous();
377         if (prev != null) {
378             final QName prevQName = childQName.bindTo(prev.getQName().getModule());
379             found = prev.findSchemaTreeGenerator(prevQName);
380             if (found != null) {
381                 return (OriginalLink<X, Y>) found.originalLink();
382             }
383         }
384
385         return null;
386     }
387
388     @Override
389     final AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
390         final var found = super.findSchemaTreeGenerator(qname);
391         return found != null ? found : findInferredGenerator(qname);
392     }
393
394     final @Nullable AbstractAugmentGenerator findAugmentForGenerator(final QName qname) {
395         for (var augment : augments) {
396             final var gen = augment.findSchemaTreeGenerator(qname);
397             if (gen != null) {
398                 return augment;
399             }
400         }
401         return null;
402     }
403
404     final @Nullable GroupingGenerator findGroupingForGenerator(final QName qname) {
405         for (var grouping : groupings) {
406             final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
407             if (gen != null) {
408                 return grouping;
409             }
410         }
411         return null;
412     }
413
414     private @Nullable AbstractExplicitGenerator<?, ?> findInferredGenerator(final QName qname) {
415         // First search our local groupings ...
416         for (var grouping : groupings) {
417             final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
418             if (gen != null) {
419                 return gen;
420             }
421         }
422         // ... next try local augments, which may have groupings themselves
423         for (var augment : augments) {
424             final var gen = augment.findSchemaTreeGenerator(qname);
425             if (gen != null) {
426                 return gen;
427             }
428         }
429         return null;
430     }
431
432     /**
433      * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
434      * is using.
435      *
436      * @param builder Target builder
437      * @param builderFactory factory for creating {@link TypeBuilder}s
438      * @return The number of groupings this type uses.
439      */
440     final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
441         for (var grp : groupings) {
442             builder.addImplementsType(grp.getGeneratedType(builderFactory));
443         }
444         return groupings.size();
445     }
446
447     static final void addAugmentable(final GeneratedTypeBuilder builder) {
448         builder.addImplementsType(BindingTypes.augmentable(builder));
449     }
450
451     final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
452         for (var child : this) {
453             // Only process explicit generators here
454             if (child instanceof AbstractExplicitGenerator<?, ?> explicit) {
455                 explicit.addAsGetterMethod(builder, builderFactory);
456             }
457
458             final var enclosedType = child.enclosedType(builderFactory);
459             if (enclosedType instanceof GeneratedTransferObject gto) {
460                 builder.addEnclosingTransferObject(gto);
461             } else if (enclosedType instanceof Enumeration enumeration) {
462                 builder.addEnumeration(enumeration);
463             } else {
464                 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
465             }
466         }
467     }
468
469     private @NonNull List<Generator> createChildren(final EffectiveStatement<?, ?> statement) {
470         final var tmp = new ArrayList<Generator>();
471         final var tmpAug = new ArrayList<AbstractAugmentGenerator>();
472
473         for (var stmt : statement.effectiveSubstatements()) {
474             if (stmt instanceof ActionEffectiveStatement action) {
475                 if (!isAugmenting(action)) {
476                     tmp.add(new ActionGenerator(action, this));
477                 }
478             } else if (stmt instanceof AnydataEffectiveStatement anydata) {
479                 if (!isAugmenting(anydata)) {
480                     tmp.add(new OpaqueObjectGenerator.Anydata(anydata, this));
481                 }
482             } else if (stmt instanceof AnyxmlEffectiveStatement anyxml) {
483                 if (!isAugmenting(anyxml)) {
484                     tmp.add(new OpaqueObjectGenerator.Anyxml(anyxml, this));
485                 }
486             } else if (stmt instanceof CaseEffectiveStatement cast) {
487                 tmp.add(new CaseGenerator(cast, this));
488             } else if (stmt instanceof ChoiceEffectiveStatement choice) {
489                 // FIXME: use isOriginalDeclaration() ?
490                 if (!isAddedByUses(choice)) {
491                     tmp.add(new ChoiceGenerator(choice, this));
492                 }
493             } else if (stmt instanceof ContainerEffectiveStatement container) {
494                 if (isOriginalDeclaration(container)) {
495                     tmp.add(new ContainerGenerator(container, this));
496                 }
497             } else if (stmt instanceof GroupingEffectiveStatement grouping) {
498                 tmp.add(new GroupingGenerator(grouping, this));
499             } else if (stmt instanceof IdentityEffectiveStatement identity) {
500                 tmp.add(new IdentityGenerator(identity, this));
501             } else if (stmt instanceof InputEffectiveStatement input) {
502                 tmp.add(this instanceof RpcGenerator ? new RpcInputGenerator(input, this)
503                     : new InputGenerator(input, this));
504             } else if (stmt instanceof LeafEffectiveStatement leaf) {
505                 if (!isAugmenting(leaf)) {
506                     tmp.add(new LeafGenerator(leaf, this));
507                 }
508             } else if (stmt instanceof LeafListEffectiveStatement leafList) {
509                 if (!isAugmenting(leafList)) {
510                     tmp.add(new LeafListGenerator(leafList, this));
511                 }
512             } else if (stmt instanceof ListEffectiveStatement list) {
513                 if (isOriginalDeclaration(list)) {
514                     final var listGen = new ListGenerator(list, this);
515                     tmp.add(listGen);
516
517                     final var keyGen = listGen.keyGenerator();
518                     if (keyGen != null) {
519                         tmp.add(keyGen);
520                     }
521                 }
522             } else if (stmt instanceof NotificationEffectiveStatement notification) {
523                 if (!isAugmenting(notification)) {
524                     tmp.add(new NotificationGenerator(notification, this));
525                 }
526             } else if (stmt instanceof OutputEffectiveStatement output) {
527                 tmp.add(this instanceof RpcGenerator ? new RpcOutputGenerator(output, this)
528                     : new OutputGenerator(output, this));
529             } else if (stmt instanceof RpcEffectiveStatement rpc) {
530                 tmp.add(new RpcGenerator(rpc, this));
531             } else if (stmt instanceof TypedefEffectiveStatement typedef) {
532                 tmp.add(new TypedefGenerator(typedef, this));
533             } else if (stmt instanceof AugmentEffectiveStatement augment) {
534                 // FIXME: MDSAL-695: So here we are ignoring any augment which is not in a module, while the 'uses'
535                 //                   processing takes care of the rest. There are two problems here:
536                 //
537                 //                   1) this could be an augment introduced through uses -- in this case we are picking
538                 //                      confusing it with this being its declaration site, we should probably be
539                 //                      ignoring it, but then
540                 //
541                 //                   2) we are losing track of AugmentEffectiveStatement for which we do not generate
542                 //                      interfaces -- and recover it at runtime through explicit walk along the
543                 //                      corresponding AugmentationSchemaNode.getOriginalDefinition() pointer
544                 //
545                 //                   So here is where we should decide how to handle this augment, and make sure we
546                 //                   retain information about this being an alias. That will serve as the base for keys
547                 //                   in the augment -> original map we provide to BindingRuntimeTypes.
548                 if (this instanceof ModuleGenerator) {
549                     tmpAug.add(new ModuleAugmentGenerator(augment, this));
550                 }
551             } else if (stmt instanceof UsesEffectiveStatement uses) {
552                 for (var usesSub : uses.effectiveSubstatements()) {
553                     if (usesSub instanceof AugmentEffectiveStatement usesAug) {
554                         tmpAug.add(new UsesAugmentGenerator(usesAug, uses, this));
555                     }
556                 }
557             } else {
558                 LOG.trace("Ignoring statement {}", stmt);
559             }
560         }
561
562         // Sort augments and add them last. This ensures child iteration order always reflects potential
563         // interdependencies, hence we do not need to worry about them. This is extremely important, as there are a
564         // number of places where we would have to either move the logic to parent statement and explicitly filter/sort
565         // substatements to establish this order.
566         tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
567         tmp.addAll(tmpAug);
568
569         // Compatibility FooService and FooListener interfaces, only generated for modules.
570         if (this instanceof ModuleGenerator moduleGen) {
571             final List<NotificationGenerator> notifs = tmp.stream()
572                 .filter(NotificationGenerator.class::isInstance)
573                 .map(NotificationGenerator.class::cast)
574                 .collect(Collectors.toUnmodifiableList());
575             if (!notifs.isEmpty()) {
576                 tmp.add(new NotificationServiceGenerator(moduleGen, notifs));
577             }
578
579             final List<RpcGenerator> rpcs = tmp.stream()
580                 .filter(RpcGenerator.class::isInstance)
581                 .map(RpcGenerator.class::cast)
582                 .collect(Collectors.toUnmodifiableList());
583             if (!rpcs.isEmpty()) {
584                 tmp.add(new RpcServiceGenerator(moduleGen, rpcs));
585             }
586         }
587
588         return List.copyOf(tmp);
589     }
590
591     // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
592     // CopyableNode and AddedByUsesAware
593     private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
594         if (stmt instanceof AddedByUsesAware aware) {
595             if (aware.isAddedByUses()
596                 || stmt instanceof CopyableNode copyable && copyable.isAugmenting()) {
597                 return false;
598             }
599         }
600         return true;
601     }
602
603     private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
604         return stmt instanceof AddedByUsesAware aware && aware.isAddedByUses();
605     }
606
607     private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
608         return stmt instanceof CopyableNode copyable && copyable.isAugmenting();
609     }
610 }