ce2681193362f09a9ad1f632c288378896bc23d4
[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 Map<?, AbstractTypeAwareGenerator<?>> leafGenerators;
71     private State state = State.INITIALIZED;
72
73     public GeneratorReactor(final EffectiveModelContext context) {
74         inferenceStack = SchemaInferenceStack.of(context);
75
76         // Construct modules and their subtrees. Dependency sort is very much needed here, as it establishes order of
77         // module evaluation, and that (along with the sort in AbstractCompositeGenerator) ensures we visit
78         // AugmentGenerators without having forward references.
79         // FIXME: migrate to new ModuleDependencySort when it is available, which streamline things here
80         children = ModuleDependencySort.sort(context.getModules()).stream()
81             .map(module -> {
82                 verify(module instanceof ModuleEffectiveStatement, "Unexpected module %s", module);
83                 return new ModuleGenerator((ModuleEffectiveStatement) module);
84             })
85             .collect(Collectors.toUnmodifiableList());
86         generators = Maps.uniqueIndex(children, gen -> gen.statement().localQNameModule());
87     }
88
89     /**
90      * Execute the reactor. Execution follows the following steps:
91      * <ol>
92      *   <li>link the statement inheritance graph along {@code uses}/{@code grouping} statements</li>
93      *   <li>link the {@code typedef} inheritance hierarchy by visiting all {@link TypedefGenerator}s and memoizing the
94      *       {@code type} lookup</li>
95      *   <li>link the {@code identity} inheritance hierarchy by visiting all {@link IdentityGenerator}s and memoizing
96      *       the {@code base} lookup</li>
97      *   <li>link the {@code type} statements and resolve type restriction hierarchy, determining the set of Java
98              classes required for Java equivalent of effective YANG type definitions</li>
99      *   <li>bind {@code leafref} and {@code identityref} references to their Java class roots</li>
100      *   <li>resolve {@link ChoiceIn}/{@link ChildOf} hierarchy</li>
101      *   <li>assign Java package names and {@link JavaTypeName}s to all generated classes</li>
102      *   <li>create {@link Type} instances</li>
103      * </ol>
104      *
105      * @param builderFactory factory for creating {@link TypeBuilder}s for resulting types
106      * @return Resolved generators
107      * @throws IllegalStateException if the reactor has failed execution
108      * @throws NullPointerException if {@code builderFactory} is {@code null}
109      */
110     public @NonNull Map<QNameModule, ModuleGenerator> execute(final TypeBuilderFactory builderFactory) {
111         switch (state) {
112             case INITIALIZED:
113                 state = State.EXECUTING;
114                 break;
115             case FINISHED:
116                 return generators;
117             case EXECUTING:
118                 throw new IllegalStateException("Cannot resume partial execution");
119             default:
120                 throw new IllegalStateException("Unhandled state" + state);
121         }
122
123         // Start measuring time...
124         final Stopwatch sw = Stopwatch.createStarted();
125
126         // Step 1a: walk all composite generators and resolve 'uses' statements to the corresponding grouping node,
127         //          establishing implied inheritance ...
128         linkUsesDependencies(children);
129
130         // Step 1b: ... and also link augments and their targets in a separate pass, as we need groupings fully resolved
131         //          before we attempt augmentation lookups ...
132         for (ModuleGenerator module : children) {
133             for (Generator child : module) {
134                 if (child instanceof ModuleAugmentGenerator) {
135                     ((ModuleAugmentGenerator) child).linkAugmentationTarget(this);
136                 }
137             }
138         }
139
140         // Step 1c: ... finally establish linkage along the reverse uses/augment axis. This is needed to route generated
141         //          type manifestations (isAddedByUses/isAugmenting) to their type generation sites.
142         linkOriginalGenerator(children);
143
144         /*
145          * Step 2: link typedef statements, so that typedef's 'type' axis is fully established
146          * Step 3: link all identity statements, so that identity's 'base' axis is fully established
147          * Step 4: link all type statements, so that leafs and leaf-lists have restrictions established
148          *
149          * Since our implementation class hierarchy captures all four statements involved in a common superclass, we can
150          * perform this in a single pass.
151          */
152         linkDependencies(children);
153
154         // Step five: resolve all 'type leafref' and 'type identityref' statements, so they point to their
155         //            corresponding Java type representation.
156         bindTypeDefinition(children);
157
158         // Step six: walk all composite generators and link ChildOf/ChoiceIn relationships with parents. We have taken
159         //           care of this step during tree construction, hence this now a no-op.
160
161         /*
162          * Step seven: assign java packages and JavaTypeNames
163          *
164          * This is a really tricky part, as we have large number of factors to consider:
165          * - we are mapping grouping, typedef, identity and schema tree namespaces into Fully Qualified Class Names,
166          *   i.e. four namespaces into one
167          * - our source of class naming are YANG identifiers, which allow characters not allowed by Java
168          * - we generate class names as well as nested package hierarchy
169          * - we want to generate names which look like Java as much as possible
170          * - we need to always have an (arbitrarily-ugly) fail-safe name
171          *
172          * To deal with all that, we split this problem into multiple manageable chunks.
173          *
174          * The first chunk is here: we walk all generators and ask them to do two things:
175          * - instantiate their CollisionMembers and link them to appropriate CollisionDomains
176          * - return their collision domain
177          *
178          * Then we process we ask collision domains until all domains are resolved, driving the second chunk of the
179          * algorithm in CollisionDomain. Note that we may need to walk the domains multiple times, as the process of
180          * solving a domain may cause another domain's solution to be invalidated.
181          */
182         final List<CollisionDomain> domains = new ArrayList<>();
183         collectCollisionDomains(domains, children);
184         boolean haveUnresolved;
185         do {
186             haveUnresolved = false;
187             for (CollisionDomain domain : domains) {
188                 if (domain.findSolution()) {
189                     haveUnresolved = true;
190                 }
191             }
192         } while (haveUnresolved);
193
194         // Step eight: generate actual Types
195         //
196         // We have now properly cross-linked all generators and have assigned their naming roots, so from this point
197         // it looks as though we are performing a simple recursive execution. In reality, though, the actual path taken
198         // through generators is dictated by us as well as generator linkage.
199         for (ModuleGenerator module : children) {
200             module.ensureType(builderFactory);
201         }
202
203         LOG.debug("Processed {} modules in {}", generators.size(), sw);
204         state = State.FINISHED;
205         return generators;
206     }
207
208     private void collectCollisionDomains(final List<CollisionDomain> result,
209             final Iterable<? extends Generator> parent) {
210         for (Generator gen : parent) {
211             gen.ensureMember();
212             collectCollisionDomains(result, gen);
213             if (gen instanceof AbstractCompositeGenerator) {
214                 result.add(((AbstractCompositeGenerator<?>) gen).domain());
215             }
216         }
217     }
218
219     @Override
220     <E extends EffectiveStatement<QName, ?>, G extends AbstractExplicitGenerator<E>> G resolveTreeScoped(
221             final Class<G> type, final QName argument) {
222         LOG.trace("Searching for tree-scoped argument {} at {}", argument, stack);
223
224         // Check if the requested QName matches current module, if it does search the stack
225         final Iterable<? extends Generator> last = stack.getLast();
226         verify(last instanceof ModuleGenerator, "Unexpected last stack item %s", last);
227
228         if (argument.getModule().equals(((ModuleGenerator) last).statement().localQNameModule())) {
229             for (Iterable<? extends Generator> ancestor : stack) {
230                 for (Generator child : ancestor) {
231                     if (type.isInstance(child)) {
232                         final G cast = type.cast(child);
233                         if (argument.equals(cast.statement().argument())) {
234                             LOG.trace("Found matching {}", child);
235                             return cast;
236                         }
237                     }
238                 }
239             }
240         } else {
241             final ModuleGenerator module = generators.get(argument.getModule());
242             if (module != null) {
243                 for (Generator child : module) {
244                     if (type.isInstance(child)) {
245                         final G cast = type.cast(child);
246                         if (argument.equals(cast.statement().argument())) {
247                             LOG.trace("Found matching {}", child);
248                             return cast;
249                         }
250                     }
251                 }
252             }
253         }
254
255         throw new IllegalStateException("Could not find " + type + " argument " + argument + " in " + stack);
256     }
257
258     @Override
259     ModuleGenerator resolveModule(final QNameModule namespace) {
260         final ModuleGenerator module = generators.get(requireNonNull(namespace));
261         checkState(module != null, "Failed to find module for %s", namespace);
262         return module;
263     }
264
265     @Override
266     AbstractTypeObjectGenerator<?> resolveLeafref(final PathExpression path) {
267         LOG.trace("Resolving path {}", path);
268         verify(inferenceStack.isEmpty(), "Unexpected data tree state %s", inferenceStack);
269         try {
270             // Populate inferenceStack with a grouping + data tree equivalent of current stack's state.
271             final Iterator<Iterable<? extends Generator>> it = stack.descendingIterator();
272             // Skip first item, as it points to our children
273             verify(it.hasNext(), "Unexpected empty stack");
274             it.next();
275
276             while (it.hasNext()) {
277                 final Iterable<? extends Generator> item = it.next();
278                 verify(item instanceof Generator, "Unexpected stack item %s", item);
279                 ((Generator) item).pushToInference(inferenceStack);
280             }
281
282             return inferenceStack.inGrouping() ? lenientResolveLeafref(path) : strictResolvePath(path);
283         } finally {
284             inferenceStack.clear();
285         }
286     }
287
288     private @NonNull AbstractTypeAwareGenerator<?> strictResolvePath(final @NonNull PathExpression path) {
289         try {
290             inferenceStack.resolvePathExpression(path);
291         } catch (IllegalArgumentException e) {
292             throw new IllegalArgumentException("Failed to find leafref target " + path.getOriginalString(), e);
293         }
294         return mapToGenerator();
295     }
296
297     private @Nullable AbstractTypeAwareGenerator<?> lenientResolveLeafref(final @NonNull PathExpression path) {
298         try {
299             inferenceStack.resolvePathExpression(path);
300         } catch (IllegalArgumentException e) {
301             LOG.debug("Ignoring unresolved path {}", path, e);
302             return null;
303         }
304         return mapToGenerator();
305     }
306
307     // Map a statement to the corresponding generator
308     private @NonNull AbstractTypeAwareGenerator<?> mapToGenerator() {
309         // Some preliminaries first: we need to be in the correct module to walk the path
310         final ModuleEffectiveStatement module = inferenceStack.currentModule();
311         final ModuleGenerator gen = verifyNotNull(generators.get(module.localQNameModule()),
312             "Cannot find generator for %s", module);
313
314         // Now kick of the search
315         final List<EffectiveStatement<?, ?>> stmtPath = inferenceStack.toInference().statementPath();
316         final AbstractExplicitGenerator<?> found = gen.findGenerator(stmtPath);
317         if (found instanceof AbstractTypeAwareGenerator) {
318             return (AbstractTypeAwareGenerator<?>) found;
319         }
320         throw new VerifyException("Statements " + stmtPath + " resulted in unexpected " + found);
321     }
322
323     // Note: unlike other methods, this method pushes matching child to the stack
324     private void linkUsesDependencies(final Iterable<? extends Generator> parent) {
325         for (Generator child : parent) {
326             if (child instanceof AbstractCompositeGenerator) {
327                 LOG.trace("Visiting composite {}", child);
328                 final AbstractCompositeGenerator<?> composite = (AbstractCompositeGenerator<?>) child;
329                 stack.push(composite);
330                 composite.linkUsesDependencies(this);
331                 linkUsesDependencies(composite);
332                 stack.pop();
333             }
334         }
335     }
336
337     private void linkDependencies(final Iterable<? extends Generator> parent) {
338         for (Generator child : parent) {
339             if (child instanceof AbstractDependentGenerator) {
340                 ((AbstractDependentGenerator<?>) child).linkDependencies(this);
341             } else if (child instanceof AbstractCompositeGenerator) {
342                 stack.push(child);
343                 linkDependencies(child);
344                 stack.pop();
345             }
346         }
347     }
348
349     private void linkOriginalGenerator(final Iterable<? extends Generator> parent) {
350         for (Generator child : parent) {
351             if (child instanceof AbstractExplicitGenerator) {
352                 ((AbstractExplicitGenerator<?>) child).linkOriginalGenerator(this);
353             }
354             if (child instanceof AbstractCompositeGenerator) {
355                 stack.push(child);
356                 linkOriginalGenerator(child);
357                 stack.pop();
358             }
359         }
360     }
361
362     private void bindTypeDefinition(final Iterable<? extends Generator> parent) {
363         for (Generator child : parent) {
364             stack.push(child);
365             if (child instanceof AbstractTypeObjectGenerator) {
366                 ((AbstractTypeObjectGenerator<?>) child).bindTypeDefinition(this);
367             } else if (child instanceof AbstractCompositeGenerator) {
368                 bindTypeDefinition(child);
369             }
370             stack.pop();
371         }
372     }
373 }