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;
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.model.ri.BindingTypes;
22 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
23 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
24 import org.opendaylight.yangtools.binding.model.api.Enumeration;
25 import org.opendaylight.yangtools.binding.model.api.GeneratedTransferObject;
26 import org.opendaylight.yangtools.binding.model.api.Type;
27 import org.opendaylight.yangtools.binding.model.api.type.builder.GeneratedTypeBuilder;
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 return createBuilder(statement()).populate(new AugmentResolver(), this).build(verifyGeneratedType(type));
178 abstract @NonNull CompositeRuntimeTypeBuilder<S, R> createBuilder(S statement);
181 final R createInternalRuntimeType(final AugmentResolver resolver, final S statement, final Type type) {
182 return createBuilder(statement).populate(resolver, this).build(verifyGeneratedType(type));
186 final boolean isEmpty() {
187 return childGenerators.isEmpty();
190 final @Nullable AbstractExplicitGenerator<?, ?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
191 return findGenerator(MatchStrategy.identity(), stmtPath, 0);
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);
199 // Try direct children first, which is simple
200 var ret = childStrategy.findGenerator(stmt, childGenerators);
202 final int next = offset + 1;
203 if (stmtPath.size() == next) {
204 // Final step, return child
207 if (ret instanceof AbstractCompositeGenerator<?, ?> composite) {
208 // We know how to descend down
209 return composite.findGenerator(childStrategy, stmtPath, next);
211 // Yeah, don't know how to continue here
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
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);
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);
242 final @NonNull CollisionDomain domain() {
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
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());
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);
267 groupings = List.copyOf(tmp);
270 // Iterate over a some generators recursively, linking them to the GroupingGenerators they use. GroupingGenerators
271 // are skipped and added to unprocessedGroupings for later processing.
272 final void linkUsedGroupings(final Set<GroupingGenerator> skippedChildren) {
273 // Link to used groupings IFF we have a corresponding generated Java class
274 switch (classPlacement()) {
279 for (var grouping : groupings()) {
280 grouping.addUser(this);
284 for (var child : childGenerators) {
285 if (child instanceof GroupingGenerator grouping) {
286 skippedChildren.add(grouping);
287 } else if (child instanceof AbstractCompositeGenerator<?, ?> composite) {
288 composite.linkUsedGroupings(skippedChildren);
293 final void startUsesAugmentLinkage(final List<AugmentRequirement> requirements) {
294 for (var child : childGenerators) {
295 if (child instanceof UsesAugmentGenerator uses) {
296 requirements.add(uses.startLinkage());
298 if (child instanceof AbstractCompositeGenerator<?, ?> composite) {
299 composite.startUsesAugmentLinkage(requirements);
304 final void addAugment(final AbstractAugmentGenerator augment) {
305 if (augments.isEmpty()) {
306 augments = new ArrayList<>(2);
308 augments.add(requireNonNull(augment));
312 * Attempt to link the generator corresponding to the original definition for this generator's statements as well as
313 * to all child generators.
315 * @return Progress indication
317 final @NonNull LinkageProgress linkOriginalGeneratorRecursive() {
318 if (unlinkedComposites == null) {
319 // We have unset this list (see below), and there is nothing left to do
320 return LinkageProgress.DONE;
323 if (unlinkedChildren == null) {
324 unlinkedChildren = childGenerators.stream()
325 .filter(AbstractExplicitGenerator.class::isInstance)
326 .map(child -> (AbstractExplicitGenerator<?, ?>) child)
327 .collect(Collectors.toList());
330 var progress = LinkageProgress.NONE;
331 if (!unlinkedChildren.isEmpty()) {
332 // Attempt to make progress on child linkage
333 final var it = unlinkedChildren.iterator();
334 while (it.hasNext()) {
335 if (it.next() instanceof AbstractExplicitGenerator<?, ?> explicit && explicit.linkOriginalGenerator()) {
336 progress = LinkageProgress.SOME;
339 // If this is a composite generator we need to process is further
340 if (explicit instanceof AbstractCompositeGenerator<?, ?> composite) {
341 if (unlinkedComposites.isEmpty()) {
342 unlinkedComposites = new ArrayList<>();
344 unlinkedComposites.add(composite);
349 if (unlinkedChildren.isEmpty()) {
350 // Nothing left to do, make sure any previously-allocated list can be scavenged
351 unlinkedChildren = List.of();
355 // Process children of any composite children we have.
356 final var it = unlinkedComposites.iterator();
357 while (it.hasNext()) {
358 final var tmp = it.next().linkOriginalGeneratorRecursive();
359 if (tmp != LinkageProgress.NONE) {
360 progress = LinkageProgress.SOME;
362 if (tmp == LinkageProgress.DONE) {
367 if (unlinkedChildren.isEmpty() && unlinkedComposites.isEmpty()) {
368 // All done, set the list to null to indicate there is nothing left to do in this generator or any of our
370 unlinkedComposites = null;
371 return LinkageProgress.DONE;
378 final AbstractCompositeGenerator<S, R> getOriginal() {
379 return (AbstractCompositeGenerator<S, R>) super.getOriginal();
383 final AbstractCompositeGenerator<S, R> tryOriginal() {
384 return (AbstractCompositeGenerator<S, R>) super.tryOriginal();
387 final <X extends EffectiveStatement<?, ?>, Y extends RuntimeType> @Nullable OriginalLink<X, Y> originalChild(
388 final QName childQName) {
389 // First try groupings/augments ...
390 var found = findInferredGenerator(childQName);
392 return (OriginalLink<X, Y>) OriginalLink.partial(found);
395 // ... no luck, we really need to start looking at our origin
396 final var prev = previous();
398 final QName prevQName = childQName.bindTo(prev.getQName().getModule());
399 found = prev.findSchemaTreeGenerator(prevQName);
401 return (OriginalLink<X, Y>) found.originalLink();
409 final AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
410 final var found = super.findSchemaTreeGenerator(qname);
411 return found != null ? found : findInferredGenerator(qname);
414 final @Nullable AbstractAugmentGenerator findAugmentForGenerator(final QName qname) {
415 for (var augment : augments) {
416 final var gen = augment.findSchemaTreeGenerator(qname);
424 final @Nullable GroupingGenerator findGroupingForGenerator(final QName qname) {
425 for (var grouping : groupings) {
426 final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
434 private @Nullable AbstractExplicitGenerator<?, ?> findInferredGenerator(final QName qname) {
435 // First search our local groupings ...
436 for (var grouping : groupings) {
437 final var gen = grouping.findSchemaTreeGenerator(qname.bindTo(grouping.statement().argument().getModule()));
442 // ... next try local augments, which may have groupings themselves
443 for (var augment : augments) {
444 final var gen = augment.findSchemaTreeGenerator(qname);
453 * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
456 * @param builder Target builder
457 * @param builderFactory factory for creating {@link TypeBuilder}s
458 * @return The number of groupings this type uses.
460 final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
461 for (var grp : groupings) {
462 builder.addImplementsType(grp.getGeneratedType(builderFactory));
464 return groupings.size();
467 static final void addAugmentable(final GeneratedTypeBuilder builder) {
468 builder.addImplementsType(BindingTypes.augmentable(builder));
471 final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
472 for (var child : this) {
473 // Only process explicit generators here
474 if (child instanceof AbstractExplicitGenerator<?, ?> explicit) {
475 explicit.addAsGetterMethod(builder, builderFactory);
478 final var enclosedType = child.enclosedType(builderFactory);
479 if (enclosedType instanceof GeneratedTransferObject gto) {
480 builder.addEnclosingTransferObject(gto);
481 } else if (enclosedType instanceof Enumeration enumeration) {
482 builder.addEnumeration(enumeration);
484 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
489 private @NonNull List<Generator> createChildren(final EffectiveStatement<?, ?> statement) {
490 final var tmp = new ArrayList<Generator>();
491 final var tmpAug = new ArrayList<AbstractAugmentGenerator>();
493 for (var stmt : statement.effectiveSubstatements()) {
494 if (stmt instanceof ActionEffectiveStatement action) {
495 if (!isAugmenting(action)) {
496 tmp.add(new ActionGenerator(action, this));
498 } else if (stmt instanceof AnydataEffectiveStatement anydata) {
499 if (!isAugmenting(anydata)) {
500 tmp.add(new OpaqueObjectGenerator.Anydata(anydata, this));
502 } else if (stmt instanceof AnyxmlEffectiveStatement anyxml) {
503 if (!isAugmenting(anyxml)) {
504 tmp.add(new OpaqueObjectGenerator.Anyxml(anyxml, this));
506 } else if (stmt instanceof CaseEffectiveStatement cast) {
507 tmp.add(new CaseGenerator(cast, this));
508 } else if (stmt instanceof ChoiceEffectiveStatement choice) {
509 // FIXME: use isOriginalDeclaration() ?
510 if (!isAddedByUses(choice)) {
511 tmp.add(new ChoiceGenerator(choice, this));
513 } else if (stmt instanceof ContainerEffectiveStatement container) {
514 if (isOriginalDeclaration(container)) {
515 tmp.add(new ContainerGenerator(container, this));
517 } else if (stmt instanceof FeatureEffectiveStatement feature && this instanceof ModuleGenerator parent) {
518 tmp.add(new FeatureGenerator(feature, parent));
519 } else if (stmt instanceof GroupingEffectiveStatement grouping) {
520 tmp.add(new GroupingGenerator(grouping, this));
521 } else if (stmt instanceof IdentityEffectiveStatement identity) {
522 tmp.add(new IdentityGenerator(identity, this));
523 } else if (stmt instanceof InputEffectiveStatement input) {
524 tmp.add(new InputGenerator(input, this));
525 } else if (stmt instanceof LeafEffectiveStatement leaf) {
526 if (!isAugmenting(leaf)) {
527 tmp.add(new LeafGenerator(leaf, this));
529 } else if (stmt instanceof LeafListEffectiveStatement leafList) {
530 if (!isAugmenting(leafList)) {
531 tmp.add(new LeafListGenerator(leafList, this));
533 } else if (stmt instanceof ListEffectiveStatement list) {
534 if (isOriginalDeclaration(list)) {
535 final var listGen = new ListGenerator(list, this);
538 final var keyGen = listGen.keyGenerator();
539 if (keyGen != null) {
543 } else if (stmt instanceof NotificationEffectiveStatement notification) {
544 if (!isAugmenting(notification)) {
545 tmp.add(new NotificationGenerator(notification, this));
547 } else if (stmt instanceof OutputEffectiveStatement output) {
548 tmp.add(new OutputGenerator(output, this));
549 } else if (stmt instanceof RpcEffectiveStatement rpc) {
550 if (this instanceof ModuleGenerator module) {
551 tmp.add(new RpcGenerator(rpc, module));
553 } else if (stmt instanceof TypedefEffectiveStatement typedef) {
554 tmp.add(new TypedefGenerator(typedef, this));
555 } else if (stmt instanceof AugmentEffectiveStatement augment) {
556 // FIXME: MDSAL-695: So here we are ignoring any augment which is not in a module, while the 'uses'
557 // processing takes care of the rest. There are two problems here:
559 // 1) this could be an augment introduced through uses -- in this case we are picking
560 // confusing it with this being its declaration site, we should probably be
561 // ignoring it, but then
563 // 2) we are losing track of AugmentEffectiveStatement for which we do not generate
564 // interfaces -- and recover it at runtime through explicit walk along the
565 // corresponding AugmentationSchemaNode.getOriginalDefinition() pointer
567 // So here is where we should decide how to handle this augment, and make sure we
568 // retain information about this being an alias. That will serve as the base for keys
569 // in the augment -> original map we provide to BindingRuntimeTypes.
570 if (this instanceof ModuleGenerator module) {
571 tmpAug.add(new ModuleAugmentGenerator(augment, module));
573 } else if (stmt instanceof UsesEffectiveStatement uses) {
574 for (var usesSub : uses.effectiveSubstatements()) {
575 if (usesSub instanceof AugmentEffectiveStatement usesAug) {
576 tmpAug.add(new UsesAugmentGenerator(usesAug, uses, this));
579 } else if (stmt instanceof YangDataEffectiveStatement yangData) {
580 if (this instanceof ModuleGenerator moduleGen) {
581 tmp.add(YangDataGenerator.of(yangData, moduleGen));
584 LOG.trace("Ignoring statement {}", stmt);
588 // Sort augments and add them last. This ensures child iteration order always reflects potential
589 // interdependencies, hence we do not need to worry about them. This is extremely important, as there are a
590 // number of places where we would have to either move the logic to parent statement and explicitly filter/sort
591 // substatements to establish this order.
592 tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
594 return List.copyOf(tmp);
597 // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
598 // CopyableNode and AddedByUsesAware
599 private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
600 if (stmt instanceof AddedByUsesAware aware
601 && (aware.isAddedByUses() || aware instanceof CopyableNode copyable && copyable.isAugmenting())) {
607 private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
608 return stmt instanceof AddedByUsesAware aware && aware.isAddedByUses();
611 private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
612 return stmt instanceof CopyableNode copyable && copyable.isAugmenting();