GeneratorReactor.linkOriginalGenerator() should be stateless
[mdsal.git] / binding / mdsal-binding-generator / src / main / java / org / opendaylight / mdsal / binding / generator / impl / reactor / GeneratorReactor.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.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;
14
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;
23 import java.util.Map;
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;
44
45 /**
46  * A multi-stage reactor for generating {@link GeneratedType} instances from an {@link EffectiveModelContext}.
47  *
48  * <p>
49  * The reason for multi-stage processing is that the problem ahead of us involves:
50  * <ul>
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>
54  * </ul>
55  */
56 public final class GeneratorReactor extends GeneratorContext implements Mutable {
57     private enum State {
58         INITIALIZED,
59         EXECUTING,
60         FINISHED
61     }
62
63     private static final Logger LOG = LoggerFactory.getLogger(GeneratorReactor.class);
64
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;
69
70     private State state = State.INITIALIZED;
71
72     public GeneratorReactor(final EffectiveModelContext context) {
73         inferenceStack = SchemaInferenceStack.of(context);
74
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()
80             .map(module -> {
81                 verify(module instanceof ModuleEffectiveStatement, "Unexpected module %s", module);
82                 return new ModuleGenerator((ModuleEffectiveStatement) module);
83             })
84             .collect(Collectors.toUnmodifiableList());
85         generators = Maps.uniqueIndex(children, gen -> gen.statement().localQNameModule());
86     }
87
88     /**
89      * Execute the reactor. Execution follows the following steps:
90      * <ol>
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>
102      * </ol>
103      *
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}
108      */
109     public @NonNull Map<QNameModule, ModuleGenerator> execute(final TypeBuilderFactory builderFactory) {
110         switch (state) {
111             case INITIALIZED:
112                 state = State.EXECUTING;
113                 break;
114             case FINISHED:
115                 return generators;
116             case EXECUTING:
117                 throw new IllegalStateException("Cannot resume partial execution");
118             default:
119                 throw new IllegalStateException("Unhandled state" + state);
120         }
121
122         // Start measuring time...
123         final Stopwatch sw = Stopwatch.createStarted();
124
125         // Step 1a: walk all composite generators and resolve 'uses' statements to the corresponding grouping node,
126         //          establishing implied inheritance ...
127         linkUsesDependencies(children);
128
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);
135                 }
136             }
137         }
138
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);
142
143         /*
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
147          *
148          * Since our implementation class hierarchy captures all four statements involved in a common superclass, we can
149          * perform this in a single pass.
150          */
151         linkDependencies(children);
152
153         // Step five: resolve all 'type leafref' and 'type identityref' statements, so they point to their
154         //            corresponding Java type representation.
155         bindTypeDefinition(children);
156
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.
159
160         /*
161          * Step seven: assign java packages and JavaTypeNames
162          *
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
170          *
171          * To deal with all that, we split this problem into multiple manageable chunks.
172          *
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
176          *
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.
180          */
181         final List<CollisionDomain> domains = new ArrayList<>();
182         collectCollisionDomains(domains, children);
183         boolean haveUnresolved;
184         do {
185             haveUnresolved = false;
186             for (CollisionDomain domain : domains) {
187                 if (domain.findSolution()) {
188                     haveUnresolved = true;
189                 }
190             }
191         } while (haveUnresolved);
192
193         // Step eight: generate actual Types
194         //
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);
200         }
201
202         LOG.debug("Processed {} modules in {}", generators.size(), sw);
203         state = State.FINISHED;
204         return generators;
205     }
206
207     private void collectCollisionDomains(final List<CollisionDomain> result,
208             final Iterable<? extends Generator> parent) {
209         for (Generator gen : parent) {
210             gen.ensureMember();
211             collectCollisionDomains(result, gen);
212             if (gen instanceof AbstractCompositeGenerator) {
213                 result.add(((AbstractCompositeGenerator<?>) gen).domain());
214             }
215         }
216     }
217
218     @Override
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);
222
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);
226
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);
234                             return cast;
235                         }
236                     }
237                 }
238             }
239         } else {
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);
247                             return cast;
248                         }
249                     }
250                 }
251             }
252         }
253
254         throw new IllegalStateException("Could not find " + type + " argument " + argument + " in " + stack);
255     }
256
257     @Override
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);
261         return module;
262     }
263
264     @Override
265     AbstractTypeObjectGenerator<?> resolveLeafref(final PathExpression path) {
266         LOG.trace("Resolving path {}", path);
267         verify(inferenceStack.isEmpty(), "Unexpected data tree state %s", inferenceStack);
268         try {
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");
273             it.next();
274
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);
279             }
280
281             return inferenceStack.inGrouping() ? lenientResolveLeafref(path) : strictResolvePath(path);
282         } finally {
283             inferenceStack.clear();
284         }
285     }
286
287     private @NonNull AbstractTypeAwareGenerator<?> strictResolvePath(final @NonNull PathExpression path) {
288         try {
289             inferenceStack.resolvePathExpression(path);
290         } catch (IllegalArgumentException e) {
291             throw new IllegalArgumentException("Failed to find leafref target " + path.getOriginalString(), e);
292         }
293         return mapToGenerator();
294     }
295
296     private @Nullable AbstractTypeAwareGenerator<?> lenientResolveLeafref(final @NonNull PathExpression path) {
297         try {
298             inferenceStack.resolvePathExpression(path);
299         } catch (IllegalArgumentException e) {
300             LOG.debug("Ignoring unresolved path {}", path, e);
301             return null;
302         }
303         return mapToGenerator();
304     }
305
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);
312
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;
318         }
319         throw new VerifyException("Statements " + stmtPath + " resulted in unexpected " + found);
320     }
321
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);
331                 stack.pop();
332             }
333         }
334     }
335
336     private static void linkOriginalGenerator(final Iterable<? extends Generator> parent) {
337         for (Generator child : parent) {
338             if (child instanceof AbstractExplicitGenerator) {
339                 ((AbstractExplicitGenerator<?>) child).linkOriginalGenerator();
340             }
341             if (child instanceof AbstractCompositeGenerator) {
342                 linkOriginalGenerator(child);
343             }
344         }
345     }
346
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) {
352                 stack.push(child);
353                 linkDependencies(child);
354                 stack.pop();
355             }
356         }
357     }
358
359     private void bindTypeDefinition(final Iterable<? extends Generator> parent) {
360         for (Generator child : parent) {
361             stack.push(child);
362             if (child instanceof AbstractTypeObjectGenerator) {
363                 ((AbstractTypeObjectGenerator<?>) child).bindTypeDefinition(this);
364             } else if (child instanceof AbstractCompositeGenerator) {
365                 bindTypeDefinition(child);
366             }
367             stack.pop();
368         }
369     }
370 }