Define ExecutionOrder
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SourceSpecificContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.yangtools.yang.parser.stmt.reactor;
9
10 import static com.google.common.base.Preconditions.checkNotNull;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.collect.HashMultimap;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.Multimap;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.yangtools.concepts.Mutable;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.XMLNamespace;
31 import org.opendaylight.yangtools.yang.common.YangVersion;
32 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
46 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
51 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
52 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
53 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
54 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
62     enum PhaseCompletionProgress {
63         NO_PROGRESS,
64         PROGRESS,
65         FINISHED
66     }
67
68     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
69
70     // TODO: consider keying by Byte equivalent of ExecutionOrder
71     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
72     private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
73     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
74     private final @NonNull BuildGlobalContext globalContext;
75
76     // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
77     private StatementStreamSource source;
78
79     /*
80      * "imported" namespaces in this source -- this points to RootStatementContexts of
81      * - modules imported via 'import' statement
82      * - parent module, declared via 'belongs-to' statement
83      */
84     private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
85     private RootStatementContext<?, ?, ?> root;
86     // TODO: consider using ExecutionOrder byte for these two
87     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
88     private ModelProcessingPhase inProgressPhase;
89
90     SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
91         this.globalContext = requireNonNull(globalContext);
92         this.source = requireNonNull(source);
93     }
94
95     @NonNull BuildGlobalContext globalContext() {
96         return globalContext;
97     }
98
99     ModelProcessingPhase getInProgressPhase() {
100         return inProgressPhase;
101     }
102
103     AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
104             final int childId, final QName name, final String argument, final StatementSourceReference ref) {
105         StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
106         if (def == null) {
107             def = globalContext.getModelDefinedStatementDefinition(name);
108             if (def == null) {
109                 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
110                 if (extension != null) {
111                     def = new StatementDefinitionContext<>(extension);
112                     globalContext.putModelDefinedStatementDefinition(name, def);
113                 }
114             }
115         } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
116             /*
117              * This code wraps statements encountered inside an extension so
118              * they do not get confused with regular statements.
119              */
120             def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
121                     "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
122                     current);
123         }
124
125         if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
126                 .getArgumentDefinition().isPresent()) {
127             SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
128         } else {
129             SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
130         }
131
132         /*
133          * If the current statement definition has argument specific
134          * sub-definitions, get argument specific sub-definition based on given
135          * argument (e.g. type statement need to be specialized based on its
136          * argument).
137          */
138         if (def.hasArgumentSpecificSubDefinitions()) {
139             def = def.getSubDefinitionSpecificForArgument(argument);
140         }
141
142         if (current != null) {
143             return current.createSubstatement(childId, def, ref, argument);
144         }
145
146         /*
147          * If root is null or root version is other than default,
148          * we need to create new root.
149          */
150         if (root == null) {
151             root = new RootStatementContext<>(this, def, ref, argument);
152         } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
153                 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
154             root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
155                     root.getRootIdentifier());
156         } else {
157             final QName rootStatement = root.definition().getStatementName();
158             final String rootArgument = root.rawArgument();
159
160             checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
161                 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
162         }
163         return root;
164     }
165
166     RootStatementContext<?, ?, ?> getRoot() {
167         return root;
168     }
169
170     /**
171      * Return version of root statement context.
172      *
173      * @return version of root statement context
174      */
175     YangVersion getRootVersion() {
176         return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
177     }
178
179     void startPhase(final ModelProcessingPhase phase) {
180         final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
181         verify(Objects.equals(previousPhase, finishedPhase),
182             "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
183             finishedPhase);
184
185         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
186         checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
187             previousPhase, previousModifiers, source);
188
189         inProgressPhase = phase;
190         LOG.debug("Source {} started phase {}", source, phase);
191     }
192
193     private void updateImportedNamespaces(final Class<?> type, final Object value) {
194         if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
195             if (importedNamespaces.isEmpty()) {
196                 importedNamespaces = new ArrayList<>(1);
197             }
198
199             verify(value instanceof RootStatementContext);
200             importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
201         }
202     }
203
204     @Override
205     public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
206            final V value) {
207         // RootStatementContext takes care of IncludedModuleContext and the rest...
208         final V ret = getRoot().putToLocalStorage(type, key, value);
209         // FIXME: what about duplicates?
210         updateImportedNamespaces(type, value);
211         return ret;
212     }
213
214     @Override
215     public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
216            final V value) {
217         // RootStatementContext takes care of IncludedModuleContext and the rest...
218         final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
219         if (ret == null) {
220             updateImportedNamespaces(type, value);
221         }
222         return ret;
223     }
224
225     @Override
226     public StorageNodeType getStorageNodeType() {
227         return StorageNodeType.SOURCE_LOCAL_SPECIAL;
228     }
229
230     @Override
231     public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
232         final V potentialLocal = getRoot().getFromLocalStorage(type, key);
233         if (potentialLocal != null) {
234             return potentialLocal;
235         }
236
237         for (final NamespaceStorageNode importedSource : importedNamespaces) {
238             final V potential = importedSource.getFromLocalStorage(type, key);
239             if (potential != null) {
240                 return potential;
241             }
242         }
243         return null;
244     }
245
246     @Override
247     public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
248         final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
249         if (potentialLocal != null) {
250             return potentialLocal;
251         }
252
253         for (final NamespaceStorageNode importedSource : importedNamespaces) {
254             final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
255
256             if (potential != null) {
257                 return potential;
258             }
259         }
260         return null;
261     }
262
263     @Override
264     public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
265             final Class<N> type) {
266         return globalContext.getNamespaceBehaviour(type);
267     }
268
269     @Override
270     public BuildGlobalContext getParentNamespaceStorage() {
271         return globalContext;
272     }
273
274     PhaseCompletionProgress tryToCompletePhase(final byte executionOrder) {
275         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(executionOrder));
276         final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
277
278         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
279         final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
280                 .tryToCompletePhase(executionOrder);
281
282         hasProgressed |= tryToProgress(currentPhaseModifiers);
283
284         // TODO: use executionOrder instead?
285         if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
286             finishedPhase = phase;
287             LOG.debug("Source {} finished phase {}", source, phase);
288             if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
289                 // We have the effective model acquired, which is the final phase of source interaction.
290                 LOG.trace("Releasing source {}", source);
291                 source = null;
292             }
293             return PhaseCompletionProgress.FINISHED;
294         }
295
296         return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
297     }
298
299     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
300         boolean hasProgressed = false;
301
302         // Try making forward progress ...
303         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
304         while (modifier.hasNext()) {
305             if (modifier.next().tryApply()) {
306                 modifier.remove();
307                 hasProgressed = true;
308             }
309         }
310
311         return hasProgressed;
312     }
313
314     @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
315         final ModifierImpl action = new ModifierImpl();
316         modifiers.put(phase, action);
317         return action;
318     }
319
320     @Override
321     public String toString() {
322         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
323                 + finishedPhase + "]";
324     }
325
326     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
327         final List<SourceException> exceptions = new ArrayList<>();
328         for (final ModifierImpl mod : modifiers.get(identifier)) {
329             try {
330                 mod.failModifier();
331             } catch (final SourceException e) {
332                 exceptions.add(e);
333             }
334         }
335
336         if (exceptions.isEmpty()) {
337             return Optional.empty();
338         }
339
340         final String message = String.format("Yang model processing phase %s failed", identifier);
341         final InferenceException e = new InferenceException(message, root, exceptions.get(0));
342         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
343
344         return Optional.of(e);
345     }
346
347     void loadStatements() {
348         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
349
350         switch (inProgressPhase) {
351             case SOURCE_PRE_LINKAGE:
352                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
353                 break;
354             case SOURCE_LINKAGE:
355                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
356                     getRootVersion());
357                 break;
358             case STATEMENT_DEFINITION:
359                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
360                     prefixes(), getRootVersion());
361                 break;
362             case FULL_DECLARATION:
363                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
364                     getRootVersion());
365                 break;
366             default:
367                 break;
368         }
369     }
370
371     private PrefixToModule preLinkagePrefixes() {
372         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
373         final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
374         if (prefixToNamespaceMap == null) {
375             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
376             return null;
377         }
378
379         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
380         return preLinkagePrefixes;
381     }
382
383     private PrefixToModule prefixes() {
384         final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
385             ImportPrefixToModuleCtx.class);
386         if (allImports != null) {
387             allImports.forEach((key, value) ->
388                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
389         }
390
391         final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
392             BelongsToPrefixToModuleCtx.class);
393         if (allBelongsTo != null) {
394             allBelongsTo.forEach((key, value) ->
395                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
396         }
397
398         return prefixToModuleMap;
399     }
400
401     private QNameToStatementDefinition stmtDef() {
402         // regular YANG statements and extension supports added
403         final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
404         qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
405         qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
406
407         // No further actions needed
408         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
409             return qnameToStmtDefMap;
410         }
411
412         // We need to any and all extension statements which have been declared in the context
413         final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
414                 StatementDefinitionNamespace.class);
415         if (extensions != null) {
416             extensions.forEach((qname, support) -> {
417                 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
418                 if (existing != null) {
419                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
420                 } else {
421                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
422                 }
423             });
424         }
425
426         return qnameToStmtDefMap;
427     }
428
429     Collection<SourceIdentifier> getRequiredSources() {
430         return root.getRequiredSources();
431     }
432
433     SourceIdentifier getRootIdentifier() {
434         return root.getRootIdentifier();
435     }
436 }