2 * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.generator.impl.reactor;
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;
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.rfc8040.model.api.YangDataEffectiveStatement;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
31 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.AnydataEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.AnyxmlEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.ContainerEffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.FeatureEffectiveStatement;
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;
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
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:
70 * container xyzzy; // C
75 * container bar { // D
87 * augment /foo/bar/xyzzy { // G
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.
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.
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
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}.
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);
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;
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)}.
130 private @NonNull List<AbstractAugmentGenerator> augments = List.of();
133 * List of {@code grouping} statements this statement references. This field is set once by
134 * {@link #linkUsesDependencies(GeneratorContext)}.
136 private List<GroupingGenerator> groupings;
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}.
143 private List<AbstractCompositeGenerator<?, ?>> unlinkedComposites = List.of();
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.
148 private List<Generator> unlinkedChildren;
150 AbstractCompositeGenerator(final S statement) {
152 childGenerators = createChildren(statement);
155 AbstractCompositeGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
156 super(statement, parent);
157 childGenerators = createChildren(statement);
161 public final Iterator<Generator> iterator() {
162 return childGenerators.iterator();
165 final @NonNull List<AbstractAugmentGenerator> augments() {
169 final @NonNull List<GroupingGenerator> groupings() {
170 return verifyNotNull(groupings, "Groupings not initialized in %s", this);
174 final R createExternalRuntimeType(final Type type) {
175 verify(type instanceof GeneratedType, "Unexpected type %s", type);
176 return createBuilder(statement()).populate(new AugmentResolver(), this).build((GeneratedType) type);
179 abstract @NonNull CompositeRuntimeTypeBuilder<S, R> createBuilder(S statement);
182 final R createInternalRuntimeType(final AugmentResolver resolver, final S statement, final Type type) {
183 verify(type instanceof GeneratedType, "Unexpected type %s", type);
184 return createBuilder(statement).populate(resolver, this).build((GeneratedType) type);
188 final boolean isEmpty() {
189 return childGenerators.isEmpty();
192 final @Nullable AbstractExplicitGenerator<?, ?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
193 return findGenerator(MatchStrategy.identity(), stmtPath, 0);
196 final @Nullable AbstractExplicitGenerator<?, ?> findGenerator(final MatchStrategy childStrategy,
197 // TODO: Wouldn't this method be nicer with Deque<EffectiveStatement<?, ?>> ?
198 final List<EffectiveStatement<?, ?>> stmtPath, final int offset) {
199 final var stmt = stmtPath.get(offset);
201 // Try direct children first, which is simple
202 var ret = childStrategy.findGenerator(stmt, childGenerators);
204 final int next = offset + 1;
205 if (stmtPath.size() == next) {
206 // Final step, return child
209 if (ret instanceof AbstractCompositeGenerator<?, ?> composite) {
210 // We know how to descend down
211 return composite.findGenerator(childStrategy, stmtPath, next);
213 // Yeah, don't know how to continue here
217 // At this point we are about to fork for augments or groupings. In either case only schema tree statements can
218 // be found this way. The fun part is that if we find a match and need to continue, we will use the same
219 // strategy for children as well. We now know that this (and subsequent) statements need to have a QName
221 if (stmt instanceof SchemaTreeEffectiveStatement) {
222 // grouping -> uses instantiation changes the namespace to the local namespace of the uses site. We are
223 // going the opposite direction, hence we are changing namespace from local to the grouping's namespace.
224 for (GroupingGenerator gen : groupings) {
225 final MatchStrategy strat = MatchStrategy.grouping(gen);
226 ret = gen.findGenerator(strat, stmtPath, offset);
232 // All augments are dead simple: they need to match on argument (which we expect to be a QName)
233 final MatchStrategy strat = MatchStrategy.augment();
234 for (AbstractAugmentGenerator gen : augments) {
235 ret = gen.findGenerator(strat, stmtPath, offset);
244 final @NonNull CollisionDomain domain() {
248 final void linkUsesDependencies(final GeneratorContext context) {
249 // We are establishing two linkages here:
250 // - we are resolving 'uses' statements to their corresponding 'grouping' definitions
251 // - we propagate those groupings as anchors to any augment statements, which takes out some amount of guesswork
252 // from augment+uses resolution case, as groupings know about their immediate augments as soon as uses linkage
254 final var tmp = new ArrayList<GroupingGenerator>();
255 for (var stmt : statement().effectiveSubstatements()) {
256 if (stmt instanceof UsesEffectiveStatement uses) {
257 final var grouping = context.resolveTreeScoped(GroupingGenerator.class, uses.argument());
260 // Trigger resolution of uses/augment statements. This looks like guesswork, but there may be multiple
261 // 'augment' statements in a 'uses' statement and keeping a ListMultimap here seems wasteful.
262 for (Generator gen : this) {
263 if (gen instanceof UsesAugmentGenerator usesGen) {
264 usesGen.resolveGrouping(uses, grouping);
269 groupings = List.copyOf(tmp);
272 final void startUsesAugmentLinkage(final List<AugmentRequirement> requirements) {
273 for (var child : childGenerators) {
274 if (child instanceof UsesAugmentGenerator uses) {
275 requirements.add(uses.startLinkage());
277 if (child instanceof AbstractCompositeGenerator<?, ?> composite) {
278 composite.startUsesAugmentLinkage(requirements);
283 final void addAugment(final AbstractAugmentGenerator augment) {
284 if (augments.isEmpty()) {
285 augments = new ArrayList<>(2);
287 augments.add(requireNonNull(augment));
291 * Attempt to link the generator corresponding to the original definition for this generator's statements as well as
292 * to all child generators.
294 * @return Progress indication
296 final @NonNull LinkageProgress linkOriginalGeneratorRecursive() {
297 if (unlinkedComposites == null) {
298 // We have unset this list (see below), and there is nothing left to do
299 return LinkageProgress.DONE;
302 if (unlinkedChildren == null) {
303 unlinkedChildren = childGenerators.stream()
304 .filter(AbstractExplicitGenerator.class::isInstance)
305 .map(child -> (AbstractExplicitGenerator<?, ?>) child)
306 .collect(Collectors.toList());
309 var progress = LinkageProgress.NONE;
310 if (!unlinkedChildren.isEmpty()) {
311 // Attempt to make progress on child linkage
312 final var it = unlinkedChildren.iterator();
313 while (it.hasNext()) {
314 if (it.next() instanceof AbstractExplicitGenerator<?, ?> explicit && explicit.linkOriginalGenerator()) {
315 progress = LinkageProgress.SOME;
318 // If this is a composite generator we need to process is further
319 if (explicit instanceof AbstractCompositeGenerator<?, ?> composite) {
320 if (unlinkedComposites.isEmpty()) {
321 unlinkedComposites = new ArrayList<>();
323 unlinkedComposites.add(composite);
328 if (unlinkedChildren.isEmpty()) {
329 // Nothing left to do, make sure any previously-allocated list can be scavenged
330 unlinkedChildren = List.of();
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;
341 if (tmp == LinkageProgress.DONE) {
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
349 unlinkedComposites = null;
350 return LinkageProgress.DONE;
357 final AbstractCompositeGenerator<S, R> getOriginal() {
358 return (AbstractCompositeGenerator<S, R>) super.getOriginal();
362 final AbstractCompositeGenerator<S, R> tryOriginal() {
363 return (AbstractCompositeGenerator<S, R>) super.tryOriginal();
366 final <X extends EffectiveStatement<?, ?>, Y extends RuntimeType> @Nullable OriginalLink<X, Y> originalChild(
367 final QName childQName) {
368 // First try groupings/augments ...
369 var found = findInferredGenerator(childQName);
371 return (OriginalLink<X, Y>) OriginalLink.partial(found);
374 // ... no luck, we really need to start looking at our origin
375 final var prev = previous();
377 final QName prevQName = childQName.bindTo(prev.getQName().getModule());
378 found = prev.findSchemaTreeGenerator(prevQName);
380 return (OriginalLink<X, Y>) found.originalLink();
388 final AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
389 final var found = super.findSchemaTreeGenerator(qname);
390 return found != null ? found : findInferredGenerator(qname);
393 final @Nullable AbstractAugmentGenerator findAugmentForGenerator(final QName qname) {
394 for (var augment : augments) {
395 final var gen = augment.findSchemaTreeGenerator(qname);
403 final @Nullable GroupingGenerator findGroupingForGenerator(final QName qname) {
404 for (var grouping : groupings) {
405 final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
413 private @Nullable AbstractExplicitGenerator<?, ?> findInferredGenerator(final QName qname) {
414 // First search our local groupings ...
415 for (var grouping : groupings) {
416 final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
421 // ... next try local augments, which may have groupings themselves
422 for (var augment : augments) {
423 final var gen = augment.findSchemaTreeGenerator(qname);
432 * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
435 * @param builder Target builder
436 * @param builderFactory factory for creating {@link TypeBuilder}s
437 * @return The number of groupings this type uses.
439 final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
440 for (var grp : groupings) {
441 builder.addImplementsType(grp.getGeneratedType(builderFactory));
443 return groupings.size();
446 static final void addAugmentable(final GeneratedTypeBuilder builder) {
447 builder.addImplementsType(BindingTypes.augmentable(builder));
450 final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
451 for (var child : this) {
452 // Only process explicit generators here
453 if (child instanceof AbstractExplicitGenerator<?, ?> explicit) {
454 explicit.addAsGetterMethod(builder, builderFactory);
457 final var enclosedType = child.enclosedType(builderFactory);
458 if (enclosedType instanceof GeneratedTransferObject gto) {
459 builder.addEnclosingTransferObject(gto);
460 } else if (enclosedType instanceof Enumeration enumeration) {
461 builder.addEnumeration(enumeration);
463 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
468 private @NonNull List<Generator> createChildren(final EffectiveStatement<?, ?> statement) {
469 final var tmp = new ArrayList<Generator>();
470 final var tmpAug = new ArrayList<AbstractAugmentGenerator>();
472 for (var stmt : statement.effectiveSubstatements()) {
473 if (stmt instanceof ActionEffectiveStatement action) {
474 if (!isAugmenting(action)) {
475 tmp.add(new ActionGenerator(action, this));
477 } else if (stmt instanceof AnydataEffectiveStatement anydata) {
478 if (!isAugmenting(anydata)) {
479 tmp.add(new OpaqueObjectGenerator.Anydata(anydata, this));
481 } else if (stmt instanceof AnyxmlEffectiveStatement anyxml) {
482 if (!isAugmenting(anyxml)) {
483 tmp.add(new OpaqueObjectGenerator.Anyxml(anyxml, this));
485 } else if (stmt instanceof CaseEffectiveStatement cast) {
486 tmp.add(new CaseGenerator(cast, this));
487 } else if (stmt instanceof ChoiceEffectiveStatement choice) {
488 // FIXME: use isOriginalDeclaration() ?
489 if (!isAddedByUses(choice)) {
490 tmp.add(new ChoiceGenerator(choice, this));
492 } else if (stmt instanceof ContainerEffectiveStatement container) {
493 if (isOriginalDeclaration(container)) {
494 tmp.add(new ContainerGenerator(container, this));
496 } else if (stmt instanceof FeatureEffectiveStatement feature && this instanceof ModuleGenerator parent) {
497 tmp.add(new FeatureGenerator(feature, parent));
498 } else if (stmt instanceof GroupingEffectiveStatement grouping) {
499 tmp.add(new GroupingGenerator(grouping, this));
500 } else if (stmt instanceof IdentityEffectiveStatement identity) {
501 tmp.add(new IdentityGenerator(identity, this));
502 } else if (stmt instanceof InputEffectiveStatement input) {
503 tmp.add(new InputGenerator(input, this));
504 } else if (stmt instanceof LeafEffectiveStatement leaf) {
505 if (!isAugmenting(leaf)) {
506 tmp.add(new LeafGenerator(leaf, this));
508 } else if (stmt instanceof LeafListEffectiveStatement leafList) {
509 if (!isAugmenting(leafList)) {
510 tmp.add(new LeafListGenerator(leafList, this));
512 } else if (stmt instanceof ListEffectiveStatement list) {
513 if (isOriginalDeclaration(list)) {
514 final var listGen = new ListGenerator(list, this);
517 final var keyGen = listGen.keyGenerator();
518 if (keyGen != null) {
522 } else if (stmt instanceof NotificationEffectiveStatement notification) {
523 if (!isAugmenting(notification)) {
524 tmp.add(new NotificationGenerator(notification, this));
526 } else if (stmt instanceof OutputEffectiveStatement output) {
527 tmp.add(new OutputGenerator(output, this));
528 } else if (stmt instanceof RpcEffectiveStatement rpc) {
529 if (this instanceof ModuleGenerator module) {
530 tmp.add(new RpcGenerator(rpc, module));
532 } else if (stmt instanceof TypedefEffectiveStatement typedef) {
533 tmp.add(new TypedefGenerator(typedef, this));
534 } else if (stmt instanceof AugmentEffectiveStatement augment) {
535 // FIXME: MDSAL-695: So here we are ignoring any augment which is not in a module, while the 'uses'
536 // processing takes care of the rest. There are two problems here:
538 // 1) this could be an augment introduced through uses -- in this case we are picking
539 // confusing it with this being its declaration site, we should probably be
540 // ignoring it, but then
542 // 2) we are losing track of AugmentEffectiveStatement for which we do not generate
543 // interfaces -- and recover it at runtime through explicit walk along the
544 // corresponding AugmentationSchemaNode.getOriginalDefinition() pointer
546 // So here is where we should decide how to handle this augment, and make sure we
547 // retain information about this being an alias. That will serve as the base for keys
548 // in the augment -> original map we provide to BindingRuntimeTypes.
549 if (this instanceof ModuleGenerator module) {
550 tmpAug.add(new ModuleAugmentGenerator(augment, module));
552 } else if (stmt instanceof UsesEffectiveStatement uses) {
553 for (var usesSub : uses.effectiveSubstatements()) {
554 if (usesSub instanceof AugmentEffectiveStatement usesAug) {
555 tmpAug.add(new UsesAugmentGenerator(usesAug, uses, this));
558 } else if (stmt instanceof YangDataEffectiveStatement yangData) {
559 if (this instanceof ModuleGenerator moduleGen) {
560 tmp.add(YangDataGenerator.of(yangData, moduleGen));
563 LOG.trace("Ignoring statement {}", stmt);
567 // Sort augments and add them last. This ensures child iteration order always reflects potential
568 // interdependencies, hence we do not need to worry about them. This is extremely important, as there are a
569 // number of places where we would have to either move the logic to parent statement and explicitly filter/sort
570 // substatements to establish this order.
571 tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
574 // Compatibility FooService and FooListener interfaces, only generated for modules.
575 if (this instanceof ModuleGenerator moduleGen) {
576 final var notifs = tmp.stream()
577 .filter(NotificationGenerator.class::isInstance)
578 .map(NotificationGenerator.class::cast)
579 .collect(Collectors.toUnmodifiableList());
580 if (!notifs.isEmpty()) {
581 tmp.add(new NotificationServiceGenerator(moduleGen, notifs));
585 return List.copyOf(tmp);
588 // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
589 // CopyableNode and AddedByUsesAware
590 private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
591 if (stmt instanceof AddedByUsesAware aware
592 && (aware.isAddedByUses() || stmt instanceof CopyableNode copyable && copyable.isAugmenting())) {
598 private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
599 return stmt instanceof AddedByUsesAware aware && aware.isAddedByUses();
602 private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
603 return stmt instanceof CopyableNode copyable && copyable.isAugmenting();