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.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.base.Stopwatch;
16 import com.google.common.base.VerifyException;
17 import com.google.common.collect.Maps;
18 import java.util.ArrayDeque;
19 import java.util.ArrayList;
20 import java.util.Deque;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.stream.Collectors;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
28 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
29 import org.opendaylight.mdsal.binding.model.api.Type;
30 import org.opendaylight.yangtools.concepts.Mutable;
31 import org.opendaylight.yangtools.yang.binding.ChildOf;
32 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
36 import org.opendaylight.yangtools.yang.model.api.PathExpression;
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.ri.type.TypeBuilder;
40 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
41 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * A multi-stage reactor for generating {@link GeneratedType} instances from an {@link EffectiveModelContext}.
49 * The reason for multi-stage processing is that the problem ahead of us involves:
51 * <li>mapping {@code typedef} and restricted {@code type} statements onto Java classes</li>
52 * <li>mapping a number of schema tree nodes into Java interfaces with properties</li>
53 * <li>taking advantage of Java composition to provide {@code grouping} mobility</li>
56 public final class GeneratorReactor extends GeneratorContext implements Mutable {
63 private static final Logger LOG = LoggerFactory.getLogger(GeneratorReactor.class);
65 private final Deque<Iterable<? extends Generator>> stack = new ArrayDeque<>();
66 private final @NonNull Map<QNameModule, ModuleGenerator> generators;
67 private final @NonNull List<ModuleGenerator> children;
68 private final @NonNull SchemaInferenceStack inferenceStack;
70 private State state = State.INITIALIZED;
72 public GeneratorReactor(final EffectiveModelContext context) {
73 inferenceStack = SchemaInferenceStack.of(context);
75 // Construct modules and their subtrees. Dependency sort is very much needed here, as it establishes order of
76 // module evaluation, and that (along with the sort in AbstractCompositeGenerator) ensures we visit
77 // AugmentGenerators without having forward references.
78 // FIXME: migrate to new ModuleDependencySort when it is available, which streamline things here
79 children = ModuleDependencySort.sort(context.getModules()).stream()
81 verify(module instanceof ModuleEffectiveStatement, "Unexpected module %s", module);
82 return new ModuleGenerator((ModuleEffectiveStatement) module);
84 .collect(Collectors.toUnmodifiableList());
85 generators = Maps.uniqueIndex(children, gen -> gen.statement().localQNameModule());
89 * Execute the reactor. Execution follows the following steps:
91 * <li>link the statement inheritance graph along {@code uses}/{@code grouping} statements</li>
92 * <li>link the {@code typedef} inheritance hierarchy by visiting all {@link TypedefGenerator}s and memoizing the
93 * {@code type} lookup</li>
94 * <li>link the {@code identity} inheritance hierarchy by visiting all {@link IdentityGenerator}s and memoizing
95 * the {@code base} lookup</li>
96 * <li>link the {@code type} statements and resolve type restriction hierarchy, determining the set of Java
97 classes required for Java equivalent of effective YANG type definitions</li>
98 * <li>bind {@code leafref} and {@code identityref} references to their Java class roots</li>
99 * <li>resolve {@link ChoiceIn}/{@link ChildOf} hierarchy</li>
100 * <li>assign Java package names and {@link JavaTypeName}s to all generated classes</li>
101 * <li>create {@link Type} instances</li>
104 * @param builderFactory factory for creating {@link TypeBuilder}s for resulting types
105 * @return Resolved generators
106 * @throws IllegalStateException if the reactor has failed execution
107 * @throws NullPointerException if {@code builderFactory} is {@code null}
109 public @NonNull Map<QNameModule, ModuleGenerator> execute(final TypeBuilderFactory builderFactory) {
112 state = State.EXECUTING;
117 throw new IllegalStateException("Cannot resume partial execution");
119 throw new IllegalStateException("Unhandled state" + state);
122 // Start measuring time...
123 final Stopwatch sw = Stopwatch.createStarted();
125 // Step 1a: walk all composite generators and resolve 'uses' statements to the corresponding grouping node,
126 // establishing implied inheritance ...
127 linkUsesDependencies(children);
129 // Step 1b: ... and also link augments and their targets in a separate pass, as we need groupings fully resolved
130 // before we attempt augmentation lookups ...
131 for (ModuleGenerator module : children) {
132 for (Generator child : module) {
133 if (child instanceof ModuleAugmentGenerator) {
134 ((ModuleAugmentGenerator) child).linkAugmentationTarget(this);
139 // Step 1c: ... finally establish linkage along the reverse uses/augment axis. This is needed to route generated
140 // type manifestations (isAddedByUses/isAugmenting) to their type generation sites.
141 linkOriginalGenerator(children);
144 * Step 2: link typedef statements, so that typedef's 'type' axis is fully established
145 * Step 3: link all identity statements, so that identity's 'base' axis is fully established
146 * Step 4: link all type statements, so that leafs and leaf-lists have restrictions established
148 * Since our implementation class hierarchy captures all four statements involved in a common superclass, we can
149 * perform this in a single pass.
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 <E extends EffectiveStatement<QName, ?>, G extends AbstractExplicitGenerator<E>> G resolveTreeScoped(
220 final Class<G> type, final QName argument) {
221 LOG.trace("Searching for tree-scoped argument {} at {}", argument, stack);
223 // Check if the requested QName matches current module, if it does search the stack
224 final Iterable<? extends Generator> last = stack.getLast();
225 verify(last instanceof ModuleGenerator, "Unexpected last stack item %s", last);
227 if (argument.getModule().equals(((ModuleGenerator) last).statement().localQNameModule())) {
228 for (Iterable<? extends Generator> ancestor : stack) {
229 for (Generator child : ancestor) {
230 if (type.isInstance(child)) {
231 final G cast = type.cast(child);
232 if (argument.equals(cast.statement().argument())) {
233 LOG.trace("Found matching {}", child);
240 final ModuleGenerator module = generators.get(argument.getModule());
241 if (module != null) {
242 for (Generator child : module) {
243 if (type.isInstance(child)) {
244 final G cast = type.cast(child);
245 if (argument.equals(cast.statement().argument())) {
246 LOG.trace("Found matching {}", child);
254 throw new IllegalStateException("Could not find " + type + " argument " + argument + " in " + stack);
258 ModuleGenerator resolveModule(final QNameModule namespace) {
259 final ModuleGenerator module = generators.get(requireNonNull(namespace));
260 checkState(module != null, "Failed to find module for %s", namespace);
265 AbstractTypeObjectGenerator<?> resolveLeafref(final PathExpression path) {
266 LOG.trace("Resolving path {}", path);
267 verify(inferenceStack.isEmpty(), "Unexpected data tree state %s", inferenceStack);
269 // Populate inferenceStack with a grouping + data tree equivalent of current stack's state.
270 final Iterator<Iterable<? extends Generator>> it = stack.descendingIterator();
271 // Skip first item, as it points to our children
272 verify(it.hasNext(), "Unexpected empty stack");
275 while (it.hasNext()) {
276 final Iterable<? extends Generator> item = it.next();
277 verify(item instanceof Generator, "Unexpected stack item %s", item);
278 ((Generator) item).pushToInference(inferenceStack);
281 return inferenceStack.inGrouping() ? lenientResolveLeafref(path) : strictResolvePath(path);
283 inferenceStack.clear();
287 private @NonNull AbstractTypeAwareGenerator<?> strictResolvePath(final @NonNull PathExpression path) {
289 inferenceStack.resolvePathExpression(path);
290 } catch (IllegalArgumentException e) {
291 throw new IllegalArgumentException("Failed to find leafref target " + path.getOriginalString(), e);
293 return mapToGenerator();
296 private @Nullable AbstractTypeAwareGenerator<?> lenientResolveLeafref(final @NonNull PathExpression path) {
298 inferenceStack.resolvePathExpression(path);
299 } catch (IllegalArgumentException e) {
300 LOG.debug("Ignoring unresolved path {}", path, e);
303 return mapToGenerator();
306 // Map a statement to the corresponding generator
307 private @NonNull AbstractTypeAwareGenerator<?> mapToGenerator() {
308 // Some preliminaries first: we need to be in the correct module to walk the path
309 final ModuleEffectiveStatement module = inferenceStack.currentModule();
310 final ModuleGenerator gen = verifyNotNull(generators.get(module.localQNameModule()),
311 "Cannot find generator for %s", module);
313 // Now kick of the search
314 final List<EffectiveStatement<?, ?>> stmtPath = inferenceStack.toInference().statementPath();
315 final AbstractExplicitGenerator<?> found = gen.findGenerator(stmtPath);
316 if (found instanceof AbstractTypeAwareGenerator) {
317 return (AbstractTypeAwareGenerator<?>) found;
319 throw new VerifyException("Statements " + stmtPath + " resulted in unexpected " + found);
322 // Note: unlike other methods, this method pushes matching child to the stack
323 private void linkUsesDependencies(final Iterable<? extends Generator> parent) {
324 for (Generator child : parent) {
325 if (child instanceof AbstractCompositeGenerator) {
326 LOG.trace("Visiting composite {}", child);
327 final AbstractCompositeGenerator<?> composite = (AbstractCompositeGenerator<?>) child;
328 stack.push(composite);
329 composite.linkUsesDependencies(this);
330 linkUsesDependencies(composite);
336 private static void linkOriginalGenerator(final Iterable<? extends Generator> parent) {
337 for (Generator child : parent) {
338 if (child instanceof AbstractExplicitGenerator) {
339 ((AbstractExplicitGenerator<?>) child).linkOriginalGenerator();
341 if (child instanceof AbstractCompositeGenerator) {
342 linkOriginalGenerator(child);
347 private void linkDependencies(final Iterable<? extends Generator> parent) {
348 for (Generator child : parent) {
349 if (child instanceof AbstractDependentGenerator) {
350 ((AbstractDependentGenerator<?>) child).linkDependencies(this);
351 } else if (child instanceof AbstractCompositeGenerator) {
353 linkDependencies(child);
359 private void bindTypeDefinition(final Iterable<? extends Generator> parent) {
360 for (Generator child : parent) {
362 if (child instanceof AbstractTypeObjectGenerator) {
363 ((AbstractTypeObjectGenerator<?>) child).bindTypeDefinition(this);
364 } else if (child instanceof AbstractCompositeGenerator) {
365 bindTypeDefinition(child);