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.generator.impl.reactor.OriginalLink.Partial;
21 import org.opendaylight.mdsal.binding.model.api.Enumeration;
22 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
23 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
24 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
25 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
29 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.AnydataEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.AnyxmlEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.ContainerEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.IdentityEffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.InputEffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.stmt.LeafEffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.stmt.LeafListEffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ListEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.OutputEffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
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;
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
60 abstract class AbstractCompositeGenerator<T extends EffectiveStatement<?, ?>> extends AbstractExplicitGenerator<T> {
61 private static final Logger LOG = LoggerFactory.getLogger(AbstractCompositeGenerator.class);
63 private final @NonNull CollisionDomain domain = new CollisionDomain(this);
64 private final List<Generator> children;
66 private List<AbstractAugmentGenerator> augments = List.of();
67 private List<GroupingGenerator> groupings;
69 // Performance optimization: if this is true, we have ascertained our original definition as well that of all our
71 private boolean originalsResolved;
73 AbstractCompositeGenerator(final T statement) {
75 children = createChildren(statement);
78 AbstractCompositeGenerator(final T statement, final AbstractCompositeGenerator<?> parent) {
79 super(statement, parent);
80 children = createChildren(statement);
84 public final Iterator<Generator> iterator() {
85 return children.iterator();
89 final boolean isEmpty() {
90 return children.isEmpty();
93 final @Nullable AbstractExplicitGenerator<?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
94 return findGenerator(MatchStrategy.identity(), stmtPath, 0);
97 final @Nullable AbstractExplicitGenerator<?> findGenerator(final MatchStrategy childStrategy,
98 // TODO: Wouldn't this method be nicer with Deque<EffectiveStatement<?, ?>> ?
99 final List<EffectiveStatement<?, ?>> stmtPath, final int offset) {
100 final EffectiveStatement<?, ?> stmt = stmtPath.get(offset);
102 // Try direct children first, which is simple
103 AbstractExplicitGenerator<?> ret = childStrategy.findGenerator(stmt, children);
105 final int next = offset + 1;
106 if (stmtPath.size() == next) {
107 // Final step, return child
110 if (ret instanceof AbstractCompositeGenerator) {
111 // We know how to descend down
112 return ((AbstractCompositeGenerator<?>) ret).findGenerator(childStrategy, stmtPath, next);
114 // Yeah, don't know how to continue here
118 // At this point we are about to fork for augments or groupings. In either case only schema tree statements can
119 // be found this way. The fun part is that if we find a match and need to continue, we will use the same
120 // strategy for children as well. We now know that this (and subsequent) statements need to have a QName
122 if (stmt instanceof SchemaTreeEffectiveStatement) {
123 // grouping -> uses instantiation changes the namespace to the local namespace of the uses site. We are
124 // going the opposite direction, hence we are changing namespace from local to the grouping's namespace.
125 for (GroupingGenerator gen : groupings) {
126 final MatchStrategy strat = MatchStrategy.grouping(gen);
127 ret = gen.findGenerator(strat, stmtPath, offset);
133 // All augments are dead simple: they need to match on argument (which we expect to be a QName)
134 final MatchStrategy strat = MatchStrategy.augment();
135 for (AbstractAugmentGenerator gen : augments) {
136 ret = gen.findGenerator(strat, stmtPath, offset);
145 final @NonNull CollisionDomain domain() {
149 final void linkUsesDependencies(final GeneratorContext context) {
150 // We are resolving 'uses' statements to their corresponding 'grouping' definitions
151 final List<GroupingGenerator> tmp = new ArrayList<>();
152 for (EffectiveStatement<?, ?> stmt : statement().effectiveSubstatements()) {
153 if (stmt instanceof UsesEffectiveStatement) {
154 tmp.add(context.resolveTreeScoped(GroupingGenerator.class, ((UsesEffectiveStatement) stmt).argument()));
157 groupings = List.copyOf(tmp);
160 final void addAugment(final AbstractAugmentGenerator augment) {
161 if (augments.isEmpty()) {
162 augments = new ArrayList<>(2);
164 augments.add(requireNonNull(augment));
168 long linkOriginalGenerator() {
169 if (originalsResolved) {
173 long remaining = super.linkOriginalGenerator();
174 if (remaining == 0) {
175 for (Generator child : children) {
176 if (child instanceof AbstractExplicitGenerator) {
177 remaining += ((AbstractExplicitGenerator<?>) child).linkOriginalGenerator();
180 if (remaining == 0) {
181 originalsResolved = true;
188 final AbstractCompositeGenerator<?> getOriginal() {
189 return (AbstractCompositeGenerator<?>) super.getOriginal();
192 final @NonNull OriginalLink getOriginalChild(final QName childQName) {
193 // First try groupings/augments ...
194 final AbstractExplicitGenerator<?> found = findInferredGenerator(childQName);
196 return new Partial(found);
199 // ... no luck, we really need to start looking at our origin
200 final AbstractExplicitGenerator<?> prev = verifyNotNull(previous(),
201 "Failed to find %s in scope of %s", childQName, this);
203 final QName prevQName = childQName.bindTo(prev.getQName().getModule());
204 return verifyNotNull(prev.findSchemaTreeGenerator(prevQName),
205 "Failed to find child %s (proxy for %s) in %s", prevQName, childQName, prev).originalLink();
209 final AbstractExplicitGenerator<?> findSchemaTreeGenerator(final QName qname) {
210 final AbstractExplicitGenerator<?> found = super.findSchemaTreeGenerator(qname);
211 return found != null ? found : findInferredGenerator(qname);
214 private @Nullable AbstractExplicitGenerator<?> findInferredGenerator(final QName qname) {
215 // First search our local groupings ...
216 for (GroupingGenerator grouping : groupings) {
217 final AbstractExplicitGenerator<?> gen = grouping.findSchemaTreeGenerator(
218 qname.bindTo(grouping.statement().argument().getModule()));
223 // ... next try local augments, which may have groupings themselves
224 for (AbstractAugmentGenerator augment : augments) {
225 final AbstractExplicitGenerator<?> gen = augment.findSchemaTreeGenerator(qname);
233 final @NonNull AbstractExplicitGenerator<?> resolveSchemaNode(final SchemaNodeIdentifier path) {
234 // This is not quite straightforward. 'path' works on top of schema tree, which is instantiated view. Since we
235 // do not generate duplicate instantiations along 'uses' path, findSchemaTreeGenerator() would satisfy our
236 // request by returning a child of the source 'grouping'.
238 // When that happens, our subsequent lookups need to adjust the namespace being looked up to the grouping's
239 // namespace... except for the case when the step is actually an augmentation, in which case we must not make
242 // Hence we deal with this lookup recursively, dropping namespace hints when we cross into groupings.
243 return resolveSchemaNode(path.getNodeIdentifiers().iterator(), null);
246 private @NonNull AbstractExplicitGenerator<?> resolveSchemaNode(final Iterator<QName> qnames,
247 final @Nullable QNameModule localNamespace) {
248 final QName qname = qnames.next();
250 // First try local augments, as those are guaranteed to match namespace exactly
251 for (AbstractAugmentGenerator augment : augments) {
252 final AbstractExplicitGenerator<?> gen = augment.findSchemaTreeGenerator(qname);
254 return resolveNext(gen, qnames, null);
258 // Second try local groupings, as those perform their own adjustment
259 for (GroupingGenerator grouping : groupings) {
260 final QNameModule ns = grouping.statement().argument().getModule();
261 final AbstractExplicitGenerator<?> gen = grouping.findSchemaTreeGenerator(qname.bindTo(ns));
263 return resolveNext(gen, qnames, ns);
267 // Lastly try local statements adjusted with namespace, if applicable
268 final QName lookup = localNamespace == null ? qname : qname.bindTo(localNamespace);
269 final AbstractExplicitGenerator<?> gen = verifyNotNull(super.findSchemaTreeGenerator(lookup),
270 "Failed to find %s as %s in %s", qname, lookup, this);
271 return resolveNext(gen, qnames, localNamespace);
274 private static @NonNull AbstractExplicitGenerator<?> resolveNext(final @NonNull AbstractExplicitGenerator<?> gen,
275 final Iterator<QName> qnames, final QNameModule localNamespace) {
276 if (qnames.hasNext()) {
277 verify(gen instanceof AbstractCompositeGenerator, "Unexpected generator %s", gen);
278 return ((AbstractCompositeGenerator<?>) gen).resolveSchemaNode(qnames, localNamespace);
284 * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
287 * @param builder Target builder
288 * @param builderFactory factory for creating {@link TypeBuilder}s
289 * @return The number of groupings this type uses.
291 final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
292 for (GroupingGenerator grp : groupings) {
293 builder.addImplementsType(grp.getGeneratedType(builderFactory));
295 return groupings.size();
298 static final void addAugmentable(final GeneratedTypeBuilder builder) {
299 builder.addImplementsType(BindingTypes.augmentable(builder));
302 final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
303 for (Generator child : this) {
304 // Only process explicit generators here
305 if (child instanceof AbstractExplicitGenerator) {
306 ((AbstractExplicitGenerator<?>) child).addAsGetterMethod(builder, builderFactory);
309 final GeneratedType enclosedType = child.enclosedType(builderFactory);
310 if (enclosedType instanceof GeneratedTransferObject) {
311 builder.addEnclosingTransferObject((GeneratedTransferObject) enclosedType);
312 } else if (enclosedType instanceof Enumeration) {
313 builder.addEnumeration((Enumeration) enclosedType);
315 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
320 private List<Generator> createChildren(final EffectiveStatement<?, ?> statement) {
321 final List<Generator> tmp = new ArrayList<>();
322 final List<AbstractAugmentGenerator> tmpAug = new ArrayList<>();
324 for (EffectiveStatement<?, ?> stmt : statement.effectiveSubstatements()) {
325 if (stmt instanceof ActionEffectiveStatement) {
326 if (!isAugmenting(stmt)) {
327 tmp.add(new ActionGenerator((ActionEffectiveStatement) stmt, this));
329 } else if (stmt instanceof AnydataEffectiveStatement) {
330 if (!isAugmenting(stmt)) {
331 tmp.add(new OpaqueObjectGenerator<>((AnydataEffectiveStatement) stmt, this));
333 } else if (stmt instanceof AnyxmlEffectiveStatement) {
334 if (!isAugmenting(stmt)) {
335 tmp.add(new OpaqueObjectGenerator<>((AnyxmlEffectiveStatement) stmt, this));
337 } else if (stmt instanceof CaseEffectiveStatement) {
338 tmp.add(new CaseGenerator((CaseEffectiveStatement) stmt, this));
339 } else if (stmt instanceof ChoiceEffectiveStatement) {
340 // FIXME: use isOriginalDeclaration() ?
341 if (!isAddedByUses(stmt)) {
342 tmp.add(new ChoiceGenerator((ChoiceEffectiveStatement) stmt, this));
344 } else if (stmt instanceof ContainerEffectiveStatement) {
345 if (isOriginalDeclaration(stmt)) {
346 tmp.add(new ContainerGenerator((ContainerEffectiveStatement) stmt, this));
348 } else if (stmt instanceof GroupingEffectiveStatement) {
349 tmp.add(new GroupingGenerator((GroupingEffectiveStatement) stmt, this));
350 } else if (stmt instanceof IdentityEffectiveStatement) {
351 tmp.add(new IdentityGenerator((IdentityEffectiveStatement) stmt, this));
352 } else if (stmt instanceof InputEffectiveStatement) {
353 // FIXME: do not generate legacy RPC layout
354 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((InputEffectiveStatement) stmt, this)
355 : new OperationContainerGenerator((InputEffectiveStatement) stmt, this));
356 } else if (stmt instanceof LeafEffectiveStatement) {
357 if (!isAugmenting(stmt)) {
358 tmp.add(new LeafGenerator((LeafEffectiveStatement) stmt, this));
360 } else if (stmt instanceof LeafListEffectiveStatement) {
361 if (!isAugmenting(stmt)) {
362 tmp.add(new LeafListGenerator((LeafListEffectiveStatement) stmt, this));
364 } else if (stmt instanceof ListEffectiveStatement) {
365 if (isOriginalDeclaration(stmt)) {
366 final ListGenerator listGen = new ListGenerator((ListEffectiveStatement) stmt, this);
369 final KeyGenerator keyGen = listGen.keyGenerator();
370 if (keyGen != null) {
374 } else if (stmt instanceof NotificationEffectiveStatement) {
375 if (!isAugmenting(stmt)) {
376 tmp.add(new NotificationGenerator((NotificationEffectiveStatement) stmt, this));
378 } else if (stmt instanceof OutputEffectiveStatement) {
379 // FIXME: do not generate legacy RPC layout
380 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((OutputEffectiveStatement) stmt, this)
381 : new OperationContainerGenerator((OutputEffectiveStatement) stmt, this));
382 } else if (stmt instanceof RpcEffectiveStatement) {
383 tmp.add(new RpcGenerator((RpcEffectiveStatement) stmt, this));
384 } else if (stmt instanceof TypedefEffectiveStatement) {
385 tmp.add(new TypedefGenerator((TypedefEffectiveStatement) stmt, this));
386 } else if (stmt instanceof AugmentEffectiveStatement) {
387 // FIXME: MDSAL-695: So here we are ignoring any augment which is not in a module, while the 'uses'
388 // processing takes care of the rest. There are two problems here:
390 // 1) this could be an augment introduced through uses -- in this case we are picking
391 // confusing it with this being its declaration site, we should probably be
392 // ignoring it, but then
394 // 2) we are losing track of AugmentEffectiveStatement for which we do not generate
395 // interfaces -- and recover it at runtime through explicit walk along the
396 // corresponding AugmentationSchemaNode.getOriginalDefinition() pointer
398 // So here is where we should decide how to handle this augment, and make sure we
399 // retain information about this being an alias. That will serve as the base for keys
400 // in the augment -> original map we provide to BindingRuntimeTypes.
401 if (this instanceof ModuleGenerator) {
402 tmpAug.add(new ModuleAugmentGenerator((AugmentEffectiveStatement) stmt, this));
404 } else if (stmt instanceof UsesEffectiveStatement) {
405 final UsesEffectiveStatement uses = (UsesEffectiveStatement) stmt;
406 for (EffectiveStatement<?, ?> usesSub : uses.effectiveSubstatements()) {
407 if (usesSub instanceof AugmentEffectiveStatement) {
408 tmpAug.add(new UsesAugmentGenerator((AugmentEffectiveStatement) usesSub, this));
412 LOG.trace("Ignoring statement {}", stmt);
417 // Sort augments and add them last. This ensures child iteration order always reflects potential
418 // interdependencies, hence we do not need to worry about them.
419 tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
422 // Compatibility FooService and FooListener interfaces, only generated for modules.
423 if (this instanceof ModuleGenerator) {
424 final ModuleGenerator moduleGen = (ModuleGenerator) this;
426 final List<NotificationGenerator> notifs = tmp.stream()
427 .filter(NotificationGenerator.class::isInstance)
428 .map(NotificationGenerator.class::cast)
429 .collect(Collectors.toUnmodifiableList());
430 if (!notifs.isEmpty()) {
431 tmp.add(new NotificationServiceGenerator(moduleGen, notifs));
434 final List<RpcGenerator> rpcs = tmp.stream()
435 .filter(RpcGenerator.class::isInstance)
436 .map(RpcGenerator.class::cast)
437 .collect(Collectors.toUnmodifiableList());
438 if (!rpcs.isEmpty()) {
439 tmp.add(new RpcServiceGenerator(moduleGen, rpcs));
443 return List.copyOf(tmp);
446 // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
447 // CopyableNode and AddedByUsesAware
448 private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
449 if (stmt instanceof AddedByUsesAware) {
450 if (((AddedByUsesAware) stmt).isAddedByUses()
451 || stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting()) {
458 private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
459 return stmt instanceof AddedByUsesAware && ((AddedByUsesAware) stmt).isAddedByUses();
462 private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
463 return stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting();