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;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.collect.Maps;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Deque;
18 import java.util.IdentityHashMap;
19 import java.util.Iterator;
20 import java.util.List;
22 import java.util.stream.Collectors;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
26 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
27 import org.opendaylight.mdsal.binding.model.api.Type;
28 import org.opendaylight.yangtools.concepts.Mutable;
29 import org.opendaylight.yangtools.yang.binding.ChildOf;
30 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.QNameModule;
33 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
35 import org.opendaylight.yangtools.yang.model.api.PathExpression;
36 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
40 import org.opendaylight.yangtools.yang.model.ri.type.TypeBuilder;
41 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
42 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * A multi-stage reactor for generating {@link GeneratedType} instances from an {@link EffectiveModelContext}.
50 * The reason for multi-stage processing is that the problem ahead of us involves:
52 * <li>mapping {@code typedef} and restricted {@code type} statements onto Java classes</li>
53 * <li>mapping a number of schema tree nodes into Java interfaces with properties</li>
54 * <li>taking advantage of Java composition to provide {@code grouping} mobility</li>
57 public final class GeneratorReactor extends GeneratorContext implements Mutable {
64 private static final Logger LOG = LoggerFactory.getLogger(GeneratorReactor.class);
66 private final Deque<Iterable<? extends Generator>> stack = new ArrayDeque<>();
67 private final @NonNull Map<QNameModule, ModuleGenerator> generators;
68 private final @NonNull List<ModuleGenerator> children;
69 private final @NonNull SchemaInferenceStack inferenceStack;
71 private Map<?, AbstractTypeAwareGenerator<?>> leafGenerators;
72 private State state = State.INITIALIZED;
74 public GeneratorReactor(final EffectiveModelContext context) {
75 inferenceStack = SchemaInferenceStack.of(context);
77 // Construct modules and their subtrees. Dependency sort is very much needed here, as it establishes order of
78 // module evaluation, and that (along with the sort in AbstractCompositeGenerator) ensures we visit
79 // AugmentGenerators without having forward references.
80 // FIXME: migrate to new ModuleDependencySort when it is available, which streamline things here
81 children = ModuleDependencySort.sort(context.getModules()).stream()
83 verify(module instanceof ModuleEffectiveStatement, "Unexpected module %s", module);
84 return new ModuleGenerator((ModuleEffectiveStatement) module);
86 .collect(Collectors.toUnmodifiableList());
87 generators = Maps.uniqueIndex(children, gen -> gen.statement().localQNameModule());
91 * Execute the reactor. Execution follows the following steps:
93 * <li>link the statement inheritance graph along {@code uses}/{@code grouping} statements</li>
94 * <li>link the {@code typedef} inheritance hierarchy by visiting all {@link TypedefGenerator}s and memoizing the
95 * {@code type} lookup</li>
96 * <li>link the {@code identity} inheritance hierarchy by visiting all {@link IdentityGenerator}s and memoizing
97 * the {@code base} lookup</li>
98 * <li>link the {@code type} statements and resolve type restriction hierarchy, determining the set of Java
99 classes required for Java equivalent of effective YANG type definitions</li>
100 * <li>bind {@code leafref} and {@code identityref} references to their Java class roots</li>
101 * <li>resolve {@link ChoiceIn}/{@link ChildOf} hierarchy</li>
102 * <li>assign Java package names and {@link JavaTypeName}s to all generated classes</li>
103 * <li>create {@link Type} instances</li>
106 * @param builderFactory factory for creating {@link TypeBuilder}s for resulting types
107 * @return Resolved generators
108 * @throws IllegalStateException if the reactor has failed execution
109 * @throws NullPointerException if {@code builderFactory} is {@code null}
111 public @NonNull Map<QNameModule, ModuleGenerator> execute(final TypeBuilderFactory builderFactory) {
114 state = State.EXECUTING;
119 throw new IllegalStateException("Cannot resume partial execution");
121 throw new IllegalStateException("Unhandled state" + state);
124 // Step 1a: walk all composite generators and resolve 'uses' statements to the corresponding grouping node,
125 // establishing implied inheritance ...
126 linkUsesDependencies(children);
128 // Step 1b: ... and also link augments and their targets in a separate pass, as we need groupings fully resolved
129 // before we attempt augmentation lookups ...
130 for (ModuleGenerator module : children) {
131 for (Generator child : module) {
132 if (child instanceof ModuleAugmentGenerator) {
133 ((ModuleAugmentGenerator) child).linkAugmentationTarget(this);
138 // Step 1c: ... finally establish linkage along the reverse uses/augment axis. This is needed to route generated
139 // type manifestations (isAddedByUses/isAugmenting) to their type generation sites.
140 linkOriginalGenerator(children);
143 * Step 2: link typedef statements, so that typedef's 'type' axis is fully established
144 * Step 3: link all identity statements, so that identity's 'base' axis is fully established
145 * Step 4: link all type statements, so that leafs and leaf-lists have restrictions established
147 * Since our implementation class hierarchy captures all four statements involved in a common superclass, we can
148 * perform this in a single pass.
150 final Stopwatch sw = Stopwatch.createStarted();
151 linkDependencies(children);
153 // Step five: resolve all 'type leafref' and 'type identityref' statements, so they point to their
154 // corresponding Java type representation.
155 bindTypeDefinition(children);
157 // Step six: walk all composite generators and link ChildOf/ChoiceIn relationships with parents. We have taken
158 // care of this step during tree construction, hence this now a no-op.
161 * Step seven: assign java packages and JavaTypeNames
163 * This is a really tricky part, as we have large number of factors to consider:
164 * - we are mapping grouping, typedef, identity and schema tree namespaces into Fully Qualified Class Names,
165 * i.e. four namespaces into one
166 * - our source of class naming are YANG identifiers, which allow characters not allowed by Java
167 * - we generate class names as well as nested package hierarchy
168 * - we want to generate names which look like Java as much as possible
169 * - we need to always have an (arbitrarily-ugly) fail-safe name
171 * To deal with all that, we split this problem into multiple manageable chunks.
173 * The first chunk is here: we walk all generators and ask them to do two things:
174 * - instantiate their CollisionMembers and link them to appropriate CollisionDomains
175 * - return their collision domain
177 * Then we process we ask collision domains until all domains are resolved, driving the second chunk of the
178 * algorithm in CollisionDomain. Note that we may need to walk the domains multiple times, as the process of
179 * solving a domain may cause another domain's solution to be invalidated.
181 final List<CollisionDomain> domains = new ArrayList<>();
182 collectCollisionDomains(domains, children);
183 boolean haveUnresolved;
185 haveUnresolved = false;
186 for (CollisionDomain domain : domains) {
187 if (domain.findSolution()) {
188 haveUnresolved = true;
191 } while (haveUnresolved);
193 // Step eight: generate actual Types
195 // We have now properly cross-linked all generators and have assigned their naming roots, so from this point
196 // it looks as though we are performing a simple recursive execution. In reality, though, the actual path taken
197 // through generators is dictated by us as well as generator linkage.
198 for (ModuleGenerator module : children) {
199 module.ensureType(builderFactory);
202 LOG.debug("Processed {} modules in {}", generators.size(), sw);
203 state = State.FINISHED;
207 private void collectCollisionDomains(final List<CollisionDomain> result,
208 final Iterable<? extends Generator> parent) {
209 for (Generator gen : parent) {
211 collectCollisionDomains(result, gen);
212 if (gen instanceof AbstractCompositeGenerator) {
213 result.add(((AbstractCompositeGenerator<?>) gen).domain());
219 AbstractExplicitGenerator<?> resolveSchemaNode(final SchemaNodeIdentifier path) {
220 verify(path instanceof SchemaNodeIdentifier.Absolute, "Unexpected path %s", path);
221 return verifyNotNull(generators.get(path.firstNodeIdentifier().getModule()), "Cannot find module for %s", path)
222 .resolveSchemaNode(path, null);
226 <E extends EffectiveStatement<QName, ?>, G extends AbstractExplicitGenerator<E>> G resolveTreeScoped(
227 final Class<G> type, final QName argument) {
228 LOG.trace("Searching for tree-scoped argument {} at {}", argument, stack);
230 // Check if the requested QName matches current module, if it does search the stack
231 final Iterable<? extends Generator> last = stack.getLast();
232 verify(last instanceof ModuleGenerator, "Unexpected last stack item %s", last);
234 if (argument.getModule().equals(((ModuleGenerator) last).statement().localQNameModule())) {
235 for (Iterable<? extends Generator> ancestor : stack) {
236 for (Generator child : ancestor) {
237 if (type.isInstance(child)) {
238 final G cast = type.cast(child);
239 if (argument.equals(cast.statement().argument())) {
240 LOG.trace("Found matching {}", child);
247 final ModuleGenerator module = generators.get(argument.getModule());
248 if (module != null) {
249 for (Generator child : module) {
250 if (type.isInstance(child)) {
251 final G cast = type.cast(child);
252 if (argument.equals(cast.statement().argument())) {
253 LOG.trace("Found matching {}", child);
261 throw new IllegalStateException("Could not find " + type + " argument " + argument + " in " + stack);
265 IdentityGenerator resolveIdentity(final QName name) {
266 final ModuleGenerator module = generators.get(name.getModule());
267 if (module != null) {
268 for (Generator gen : module) {
269 if (gen instanceof IdentityGenerator) {
270 final IdentityGenerator idgen = (IdentityGenerator) gen;
271 if (name.equals(idgen.statement().argument())) {
277 throw new IllegalStateException("Failed to find identity " + name);
281 AbstractTypeObjectGenerator<?> resolveLeafref(final PathExpression path) {
282 LOG.trace("Resolving path {}", path);
283 verify(inferenceStack.isEmpty(), "Unexpected data tree state %s", inferenceStack);
285 // Populate inferenceStack with a grouping + data tree equivalent of current stack's state.
286 final Iterator<Iterable<? extends Generator>> it = stack.descendingIterator();
287 // Skip first item, as it points to our children
288 verify(it.hasNext(), "Unexpected empty stack");
291 while (it.hasNext()) {
292 final Iterable<? extends Generator> item = it.next();
293 verify(item instanceof Generator, "Unexpected stack item %s", item);
294 ((Generator) item).pushToInference(inferenceStack);
297 return inferenceStack.inGrouping() ? lenientResolveLeafref(path) : strictResolvePath(path);
299 inferenceStack.clear();
303 private @NonNull AbstractTypeAwareGenerator<?> strictResolvePath(final @NonNull PathExpression path) {
304 final EffectiveStatement<?, ?> stmt;
306 stmt = inferenceStack.resolvePathExpression(path);
307 } catch (IllegalArgumentException e) {
308 throw new IllegalArgumentException("Failed to find leafref target " + path, e);
310 return mapToGenerator(stmt);
313 private @Nullable AbstractTypeAwareGenerator<?> lenientResolveLeafref(final @NonNull PathExpression path) {
314 final EffectiveStatement<?, ?> stmt;
316 stmt = inferenceStack.resolvePathExpression(path);
317 } catch (IllegalArgumentException e) {
318 LOG.debug("Ignoring unresolved path {}", path, e);
321 return mapToGenerator(stmt);
324 // Map a statement to the corresponding generator
325 private @NonNull AbstractTypeAwareGenerator<?> mapToGenerator(final EffectiveStatement<?, ?> stmt) {
326 if (leafGenerators == null) {
327 final Map<EffectiveStatement<?, ?>, AbstractTypeAwareGenerator<?>> map = new IdentityHashMap<>();
328 indexLeafGenerators(map, children);
329 leafGenerators = map;
332 AbstractTypeAwareGenerator<?> match = leafGenerators.get(stmt);
333 if (match == null && stmt instanceof DerivableSchemaNode) {
334 final SchemaNode orig = ((DerivableSchemaNode) stmt).getOriginal().orElse(null);
335 if (orig instanceof EffectiveStatement) {
336 match = leafGenerators.get(orig);
340 return verifyNotNull(match, "Cannot resolve generator for %s", stmt);
343 private static void indexLeafGenerators(final Map<EffectiveStatement<?, ?>, AbstractTypeAwareGenerator<?>> map,
344 final Iterable<? extends Generator> parent) {
345 for (Generator child : parent) {
346 if (child instanceof AbstractTypeAwareGenerator) {
347 final AbstractTypeAwareGenerator<?> value = (AbstractTypeAwareGenerator<?>) child;
348 final EffectiveStatement<?, ?> key = value.statement();
349 final AbstractTypeAwareGenerator<?> prev = map.putIfAbsent(key, value);
350 verify(prev == null, "Conflict on %s between %s and %s", key, prev, value);
352 indexLeafGenerators(map, child);
356 // Note: unlike other methods, this method pushes matching child to the stack
357 private void linkUsesDependencies(final Iterable<? extends Generator> parent) {
358 for (Generator child : parent) {
359 if (child instanceof AbstractCompositeGenerator) {
360 LOG.trace("Visiting composite {}", child);
361 final AbstractCompositeGenerator<?> composite = (AbstractCompositeGenerator<?>) child;
362 stack.push(composite);
363 composite.linkUsesDependencies(this);
364 linkUsesDependencies(composite);
370 private void linkDependencies(final Iterable<? extends Generator> parent) {
371 for (Generator child : parent) {
372 if (child instanceof AbstractDependentGenerator) {
373 ((AbstractDependentGenerator<?>) child).linkDependencies(this);
374 } else if (child instanceof AbstractCompositeGenerator) {
376 linkDependencies(child);
382 private void linkOriginalGenerator(final Iterable<? extends Generator> parent) {
383 for (Generator child : parent) {
384 if (child instanceof AbstractExplicitGenerator) {
385 ((AbstractExplicitGenerator<?>) child).linkOriginalGenerator(this);
387 if (child instanceof AbstractCompositeGenerator) {
389 linkOriginalGenerator(child);
395 private void bindTypeDefinition(final Iterable<? extends Generator> parent) {
396 for (Generator child : parent) {
398 if (child instanceof AbstractTypeObjectGenerator) {
399 ((AbstractTypeObjectGenerator<?>) child).bindTypeDefinition(this);
400 } else if (child instanceof AbstractCompositeGenerator) {
401 bindTypeDefinition(child);