14889c53dd0642a6a34f7988564375a506ce72a6
[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.builder.GeneratedTypeBuilder;
24 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
27 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.AnydataEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.AnyxmlEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.ContainerEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.IdentityEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.InputEffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.LeafEffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.LeafListEffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.stmt.ListEffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationEffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.OutputEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
48 import org.opendaylight.yangtools.yang.model.ri.type.TypeBuilder;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * A composite generator. Composite generators may contain additional children, which end up being mapped into
54  * the naming hierarchy 'under' the composite generator. To support this use case, each composite has a Java package
55  * name assigned.
56  */
57 abstract class AbstractCompositeGenerator<T extends EffectiveStatement<?, ?>> extends AbstractExplicitGenerator<T> {
58     private static final Logger LOG = LoggerFactory.getLogger(AbstractCompositeGenerator.class);
59
60     private final @NonNull CollisionDomain domain = new CollisionDomain(this);
61     private final List<Generator> children;
62
63     private List<AbstractAugmentGenerator> augments = List.of();
64     private List<GroupingGenerator> groupings;
65
66     AbstractCompositeGenerator(final T statement) {
67         super(statement);
68         children = createChildren(statement);
69     }
70
71     AbstractCompositeGenerator(final T statement, final AbstractCompositeGenerator<?> parent) {
72         super(statement, parent);
73         children = createChildren(statement);
74     }
75
76     @Override
77     public final Iterator<Generator> iterator() {
78         return children.iterator();
79     }
80
81     @Override
82     final boolean isEmpty() {
83         return children.isEmpty();
84     }
85
86     final @Nullable AbstractExplicitGenerator<?> findGenerator(final List<EffectiveStatement<?, ?>> stmtPath) {
87         return findGenerator(MatchStrategy.identity(), stmtPath, 0);
88     }
89
90     final @Nullable AbstractExplicitGenerator<?> findGenerator(final MatchStrategy childStrategy,
91             // TODO: Wouldn't this method be nicer with Deque<EffectiveStatement<?, ?>> ?
92             final List<EffectiveStatement<?, ?>> stmtPath, final int offset) {
93         final EffectiveStatement<?, ?> stmt = stmtPath.get(offset);
94
95         // Try direct children first, which is simple
96         AbstractExplicitGenerator<?> ret = childStrategy.findGenerator(stmt, children);
97         if (ret != null) {
98             final int next = offset + 1;
99             if (stmtPath.size() == next) {
100                 // Final step, return child
101                 return ret;
102             }
103             if (ret instanceof AbstractCompositeGenerator) {
104                 // We know how to descend down
105                 return ((AbstractCompositeGenerator<?>) ret).findGenerator(childStrategy, stmtPath, next);
106             }
107             // Yeah, don't know how to continue here
108             return null;
109         }
110
111         // At this point we are about to fork for augments or groupings. In either case only schema tree statements can
112         // be found this way. The fun part is that if we find a match and need to continue, we will use the same
113         // strategy for children as well. We now know that this (and subsequent) statements need to have a QName
114         // argument.
115         if (stmt instanceof SchemaTreeEffectiveStatement) {
116             // grouping -> uses instantiation changes the namespace to the local namespace of the uses site. We are
117             // going the opposite direction, hence we are changing namespace from local to the grouping's namespace.
118             for (GroupingGenerator gen : groupings) {
119                 final MatchStrategy strat = MatchStrategy.grouping(gen);
120                 ret = gen.findGenerator(strat, stmtPath, offset);
121                 if (ret != null) {
122                     return ret;
123                 }
124             }
125
126             // All augments are dead simple: they need to match on argument (which we expect to be a QName)
127             final MatchStrategy strat = MatchStrategy.augment();
128             for (AbstractAugmentGenerator gen : augments) {
129                 ret = gen.findGenerator(strat, stmtPath, offset);
130                 if (ret != null) {
131                     return ret;
132                 }
133             }
134         }
135         return null;
136     }
137
138     final @NonNull CollisionDomain domain() {
139         return domain;
140     }
141
142     final void linkUsesDependencies(final GeneratorContext context) {
143         // We are establishing two linkages here:
144         // - we are resolving 'uses' statements to their corresponding 'grouping' definitions
145         // - we propagate those groupings as anchors to any augment statements
146         final List<GroupingGenerator> tmp = new ArrayList<>();
147         for (EffectiveStatement<?, ?> stmt : statement().effectiveSubstatements()) {
148             if (stmt instanceof UsesEffectiveStatement) {
149                 final UsesEffectiveStatement uses = (UsesEffectiveStatement) stmt;
150                 final GroupingGenerator grouping = context.resolveTreeScoped(GroupingGenerator.class, uses.argument());
151                 tmp.add(grouping);
152
153                 for (Generator gen : this) {
154                     if (gen instanceof UsesAugmentGenerator) {
155                         ((UsesAugmentGenerator) gen).linkGroupingDependency(uses, grouping);
156                     }
157                 }
158             }
159         }
160         groupings = List.copyOf(tmp);
161     }
162
163     final void addAugment(final AbstractAugmentGenerator augment) {
164         if (augments.isEmpty()) {
165             augments = new ArrayList<>(2);
166         }
167         augments.add(requireNonNull(augment));
168     }
169
170     @Override
171     final AbstractCompositeGenerator<?> getOriginal() {
172         return (AbstractCompositeGenerator<?>) super.getOriginal();
173     }
174
175     final @NonNull AbstractExplicitGenerator<?> getOriginalChild(final QName childQName) {
176         // First try groupings/augments ...
177         final AbstractExplicitGenerator<?> found = findInferredGenerator(childQName);
178         if (found != null) {
179             return found;
180         }
181
182         // ... no luck, we really need to start looking at our origin
183         final AbstractExplicitGenerator<?> prev = verifyNotNull(previous(),
184             "Failed to find %s in scope of %s", childQName, this);
185
186         final QName prevQName = childQName.bindTo(prev.getQName().getModule());
187         return verifyNotNull(prev.findSchemaTreeGenerator(prevQName),
188             "Failed to find child %s (proxy for %s) in %s", prevQName, childQName, prev).getOriginal();
189     }
190
191     @Override
192     final @Nullable AbstractExplicitGenerator<?> findSchemaTreeGenerator(final QName qname) {
193         final AbstractExplicitGenerator<?> found = super.findSchemaTreeGenerator(qname);
194         return found != null ? found : findInferredGenerator(qname);
195     }
196
197     private @Nullable AbstractExplicitGenerator<?> findInferredGenerator(final QName qname) {
198         // First search our local groupings ...
199         for (GroupingGenerator grouping : groupings) {
200             final AbstractExplicitGenerator<?> gen = grouping.findSchemaTreeGenerator(
201                 qname.bindTo(grouping.statement().argument().getModule()));
202             if (gen != null) {
203                 return gen;
204             }
205         }
206         // ... next try local augments, which may have groupings themselves
207         for (AbstractAugmentGenerator augment : augments) {
208             final AbstractExplicitGenerator<?> gen = augment.findSchemaTreeGenerator(qname);
209             if (gen != null) {
210                 return gen;
211             }
212         }
213         return null;
214     }
215
216     /**
217      * Update the specified builder to implement interfaces generated for the {@code grouping} statements this generator
218      * is using.
219      *
220      * @param builder Target builder
221      * @param builderFactory factory for creating {@link TypeBuilder}s
222      * @return The number of groupings this type uses.
223      */
224     final int addUsesInterfaces(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
225         for (GroupingGenerator grp : groupings) {
226             builder.addImplementsType(grp.getGeneratedType(builderFactory));
227         }
228         return groupings.size();
229     }
230
231     static final void addAugmentable(final GeneratedTypeBuilder builder) {
232         builder.addImplementsType(BindingTypes.augmentable(builder));
233     }
234
235     final void addGetterMethods(final GeneratedTypeBuilder builder, final TypeBuilderFactory builderFactory) {
236         for (Generator child : this) {
237             // Only process explicit generators here
238             if (child instanceof AbstractExplicitGenerator) {
239                 ((AbstractExplicitGenerator<?>) child).addAsGetterMethod(builder, builderFactory);
240             }
241
242             final GeneratedType enclosedType = child.enclosedType(builderFactory);
243             if (enclosedType instanceof GeneratedTransferObject) {
244                 builder.addEnclosingTransferObject((GeneratedTransferObject) enclosedType);
245             } else if (enclosedType instanceof Enumeration) {
246                 builder.addEnumeration((Enumeration) enclosedType);
247             } else {
248                 verify(enclosedType == null, "Unhandled enclosed type %s in %s", enclosedType, child);
249             }
250         }
251     }
252
253     private List<Generator> createChildren(final EffectiveStatement<?, ?> statement) {
254         final List<Generator> tmp = new ArrayList<>();
255         final List<AbstractAugmentGenerator> tmpAug = new ArrayList<>();
256
257         for (EffectiveStatement<?, ?> stmt : statement.effectiveSubstatements()) {
258             if (stmt instanceof ActionEffectiveStatement) {
259                 if (!isAugmenting(stmt)) {
260                     tmp.add(new ActionGenerator((ActionEffectiveStatement) stmt, this));
261                 }
262             } else if (stmt instanceof AnydataEffectiveStatement) {
263                 if (!isAugmenting(stmt)) {
264                     tmp.add(new OpaqueObjectGenerator<>((AnydataEffectiveStatement) stmt, this));
265                 }
266             } else if (stmt instanceof AnyxmlEffectiveStatement) {
267                 if (!isAugmenting(stmt)) {
268                     tmp.add(new OpaqueObjectGenerator<>((AnyxmlEffectiveStatement) stmt, this));
269                 }
270             } else if (stmt instanceof CaseEffectiveStatement) {
271                 tmp.add(new CaseGenerator((CaseEffectiveStatement) stmt, this));
272             } else if (stmt instanceof ChoiceEffectiveStatement) {
273                 // FIXME: use isOriginalDeclaration() ?
274                 if (!isAddedByUses(stmt)) {
275                     tmp.add(new ChoiceGenerator((ChoiceEffectiveStatement) stmt, this));
276                 }
277             } else if (stmt instanceof ContainerEffectiveStatement) {
278                 if (isOriginalDeclaration(stmt)) {
279                     tmp.add(new ContainerGenerator((ContainerEffectiveStatement) stmt, this));
280                 }
281             } else if (stmt instanceof GroupingEffectiveStatement) {
282                 tmp.add(new GroupingGenerator((GroupingEffectiveStatement) stmt, this));
283             } else if (stmt instanceof IdentityEffectiveStatement) {
284                 tmp.add(new IdentityGenerator((IdentityEffectiveStatement) stmt, this));
285             } else if (stmt instanceof InputEffectiveStatement) {
286                 // FIXME: do not generate legacy RPC layout
287                 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((InputEffectiveStatement) stmt, this)
288                     : new OperationContainerGenerator((InputEffectiveStatement) stmt, this));
289             } else if (stmt instanceof LeafEffectiveStatement) {
290                 if (!isAugmenting(stmt)) {
291                     tmp.add(new LeafGenerator((LeafEffectiveStatement) stmt, this));
292                 }
293             } else if (stmt instanceof LeafListEffectiveStatement) {
294                 if (!isAugmenting(stmt)) {
295                     tmp.add(new LeafListGenerator((LeafListEffectiveStatement) stmt, this));
296                 }
297             } else if (stmt instanceof ListEffectiveStatement) {
298                 if (isOriginalDeclaration(stmt)) {
299                     final ListGenerator listGen = new ListGenerator((ListEffectiveStatement) stmt, this);
300                     tmp.add(listGen);
301
302                     final KeyGenerator keyGen = listGen.keyGenerator();
303                     if (keyGen != null) {
304                         tmp.add(keyGen);
305                     }
306                 }
307             } else if (stmt instanceof NotificationEffectiveStatement) {
308                 if (!isAugmenting(stmt)) {
309                     tmp.add(new NotificationGenerator((NotificationEffectiveStatement) stmt, this));
310                 }
311             } else if (stmt instanceof OutputEffectiveStatement) {
312                 // FIXME: do not generate legacy RPC layout
313                 tmp.add(this instanceof RpcGenerator ? new RpcContainerGenerator((OutputEffectiveStatement) stmt, this)
314                     : new OperationContainerGenerator((OutputEffectiveStatement) stmt, this));
315             } else if (stmt instanceof RpcEffectiveStatement) {
316                 tmp.add(new RpcGenerator((RpcEffectiveStatement) stmt, this));
317             } else if (stmt instanceof TypedefEffectiveStatement) {
318                 tmp.add(new TypedefGenerator((TypedefEffectiveStatement) stmt, this));
319             } else if (stmt instanceof AugmentEffectiveStatement) {
320                 if (this instanceof ModuleGenerator) {
321                     tmpAug.add(new ModuleAugmentGenerator((AugmentEffectiveStatement) stmt, this));
322                 }
323             } else if (stmt instanceof UsesEffectiveStatement) {
324                 final UsesEffectiveStatement uses = (UsesEffectiveStatement) stmt;
325                 for (EffectiveStatement<?, ?> usesSub : uses.effectiveSubstatements()) {
326                     if (usesSub instanceof AugmentEffectiveStatement) {
327                         tmpAug.add(new UsesAugmentGenerator((AugmentEffectiveStatement) usesSub, this, uses));
328                     }
329                 }
330             } else {
331                 LOG.trace("Ignoring statement {}", stmt);
332                 continue;
333             }
334         }
335
336         // Sort augments and add them last. This ensures child iteration order always reflects potential
337         // interdependencies, hence we do not need to worry about them.
338         tmpAug.sort(AbstractAugmentGenerator.COMPARATOR);
339         tmp.addAll(tmpAug);
340
341         // Compatibility FooService and FooListener interfaces, only generated for modules.
342         if (this instanceof ModuleGenerator) {
343             final ModuleGenerator moduleGen = (ModuleGenerator) this;
344
345             final List<NotificationGenerator> notifs = tmp.stream()
346                 .filter(NotificationGenerator.class::isInstance)
347                 .map(NotificationGenerator.class::cast)
348                 .collect(Collectors.toUnmodifiableList());
349             if (!notifs.isEmpty()) {
350                 tmp.add(new NotificationServiceGenerator(moduleGen, notifs));
351             }
352
353             final List<RpcGenerator> rpcs = tmp.stream()
354                 .filter(RpcGenerator.class::isInstance)
355                 .map(RpcGenerator.class::cast)
356                 .collect(Collectors.toUnmodifiableList());
357             if (!rpcs.isEmpty()) {
358                 tmp.add(new RpcServiceGenerator(moduleGen, rpcs));
359             }
360         }
361
362         return List.copyOf(tmp);
363     }
364
365     // Utility equivalent of (!isAddedByUses(stmt) && !isAugmenting(stmt)). Takes advantage of relationship between
366     // CopyableNode and AddedByUsesAware
367     private static boolean isOriginalDeclaration(final EffectiveStatement<?, ?> stmt) {
368         if (stmt instanceof AddedByUsesAware) {
369             if (((AddedByUsesAware) stmt).isAddedByUses()
370                 || stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting()) {
371                 return false;
372             }
373         }
374         return true;
375     }
376
377     private static boolean isAddedByUses(final EffectiveStatement<?, ?> stmt) {
378         return stmt instanceof AddedByUsesAware && ((AddedByUsesAware) stmt).isAddedByUses();
379     }
380
381     private static boolean isAugmenting(final EffectiveStatement<?, ?> stmt) {
382         return stmt instanceof CopyableNode && ((CopyableNode) stmt).isAugmenting();
383     }
384 }