d34b4e19af1e6e313f630a9aa25da07f97ebeb97
[yangtools.git] / parser / 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.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.collect.HashMultimap;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Multimap;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
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.StatementSupportNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
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 class SupportedStatements
69             extends NamespaceBehaviour<QName, StatementSupport<?, ?, ?>, StatementSupportNamespace> {
70         private final QNameToStatementDefinitionMap statementDefinitions;
71
72         SupportedStatements(final QNameToStatementDefinitionMap statementDefinitions) {
73             super(StatementSupportNamespace.class);
74             this.statementDefinitions = requireNonNull(statementDefinitions);
75         }
76
77         @Override
78         public StatementSupport<?, ?, ?> getFrom(final NamespaceStorageNode storage, final QName key) {
79             return statementDefinitions.get(key);
80         }
81
82         @Override
83         public Map<QName, StatementSupport<?, ?, ?>> getAllFrom(final NamespaceStorageNode storage) {
84             throw new UnsupportedOperationException("StatementSupportNamespace is immutable");
85         }
86
87         @Override
88         public void addTo(final NamespaceStorageNode storage, final QName key, final StatementSupport<?, ?, ?> value) {
89             throw new UnsupportedOperationException("StatementSupportNamespace is immutable");
90         }
91     }
92
93     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
94
95     // TODO: consider keying by Byte equivalent of ExecutionOrder
96     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
97     private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
98     private final SupportedStatements statementSupports = new SupportedStatements(qnameToStmtDefMap);
99     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
100     private final @NonNull BuildGlobalContext globalContext;
101
102     // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
103     private StatementStreamSource source;
104
105     /*
106      * "imported" namespaces in this source -- this points to RootStatementContexts of
107      * - modules imported via 'import' statement
108      * - parent module, declared via 'belongs-to' statement
109      */
110     private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
111     private RootStatementContext<?, ?, ?> root;
112     // TODO: consider using ExecutionOrder byte for these two
113     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
114     private ModelProcessingPhase inProgressPhase;
115
116     // If not null, do not add anything to modifiers, but record it here.
117     private List<Entry<ModelProcessingPhase, ModifierImpl>> delayedModifiers;
118
119     SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
120         this.globalContext = requireNonNull(globalContext);
121         this.source = requireNonNull(source);
122     }
123
124     @NonNull BuildGlobalContext globalContext() {
125         return globalContext;
126     }
127
128     ModelProcessingPhase getInProgressPhase() {
129         return inProgressPhase;
130     }
131
132     AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
133             final int childId, final QName name, final String argument, final StatementSourceReference ref) {
134         StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
135         if (def == null) {
136             def = globalContext.getModelDefinedStatementDefinition(name);
137             if (def == null) {
138                 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
139                 if (extension != null) {
140                     def = new StatementDefinitionContext<>(extension);
141                     globalContext.putModelDefinedStatementDefinition(name, def);
142                 }
143             }
144         } else if (current != null) {
145             def = current.definition().overrideDefinition(def);
146         }
147
148         if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
149                 .getArgumentDefinition().isPresent()) {
150             SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
151         } else {
152             SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
153         }
154
155         /*
156          * If the current statement definition has argument specific
157          * sub-definitions, get argument specific sub-definition based on given
158          * argument (e.g. type statement need to be specialized based on its
159          * argument).
160          */
161         if (def.hasArgumentSpecificSubDefinitions()) {
162             def = def.getSubDefinitionSpecificForArgument(argument);
163         }
164
165         if (current != null) {
166             return current.createSubstatement(childId, def, ref, argument);
167         }
168
169         /*
170          * If root is null or root version is other than default,
171          * we need to create new root.
172          */
173         if (root == null) {
174             root = new RootStatementContext<>(this, def, ref, argument);
175         } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
176                 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
177             root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
178                     root.getRootIdentifier());
179         } else {
180             final QName rootStatement = root.definition().getStatementName();
181             final String rootArgument = root.rawArgument();
182
183             checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
184                 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
185         }
186         return root;
187     }
188
189     RootStatementContext<?, ?, ?> getRoot() {
190         return root;
191     }
192
193     /**
194      * Return version of root statement context.
195      *
196      * @return version of root statement context
197      */
198     YangVersion getRootVersion() {
199         return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
200     }
201
202     void startPhase(final ModelProcessingPhase phase) {
203         final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
204         verify(Objects.equals(previousPhase, finishedPhase),
205             "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
206             finishedPhase);
207
208         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
209         checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
210             previousPhase, previousModifiers, source);
211
212         inProgressPhase = phase;
213         LOG.debug("Source {} started phase {}", source, phase);
214     }
215
216     private void updateImportedNamespaces(final Class<?> type, final Object value) {
217         if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
218             if (importedNamespaces.isEmpty()) {
219                 importedNamespaces = new ArrayList<>(1);
220             }
221
222             verify(value instanceof RootStatementContext);
223             importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
224         }
225     }
226
227     @Override
228     public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
229            final V value) {
230         // RootStatementContext takes care of IncludedModuleContext and the rest...
231         final V ret = getRoot().putToLocalStorage(type, key, value);
232         // FIXME: what about duplicates?
233         updateImportedNamespaces(type, value);
234         return ret;
235     }
236
237     @Override
238     public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
239            final V value) {
240         // RootStatementContext takes care of IncludedModuleContext and the rest...
241         final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
242         if (ret == null) {
243             updateImportedNamespaces(type, value);
244         }
245         return ret;
246     }
247
248     @Override
249     public StorageNodeType getStorageNodeType() {
250         return StorageNodeType.SOURCE_LOCAL_SPECIAL;
251     }
252
253     @Override
254     public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
255         final V potentialLocal = getRoot().getFromLocalStorage(type, key);
256         if (potentialLocal != null) {
257             return potentialLocal;
258         }
259
260         for (final NamespaceStorageNode importedSource : importedNamespaces) {
261             final V potential = importedSource.getFromLocalStorage(type, key);
262             if (potential != null) {
263                 return potential;
264             }
265         }
266         return null;
267     }
268
269     @Override
270     public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
271         final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
272         if (potentialLocal != null) {
273             return potentialLocal;
274         }
275
276         for (final NamespaceStorageNode importedSource : importedNamespaces) {
277             final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
278
279             if (potential != null) {
280                 return potential;
281             }
282         }
283         return null;
284     }
285
286     @Override
287     @SuppressWarnings("unchecked")
288     public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
289             final Class<N> type) {
290         if (StatementSupportNamespace.class.equals(type)) {
291             return (NamespaceBehaviour<K, V, N>) statementSupports;
292         }
293         return globalContext.getNamespaceBehaviour(type);
294     }
295
296     @Override
297     public BuildGlobalContext getParentNamespaceStorage() {
298         return globalContext;
299     }
300
301     PhaseCompletionProgress tryToCompletePhase(final byte executionOrder) {
302         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(executionOrder));
303         final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
304
305         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
306         final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
307                 .tryToCompletePhase(executionOrder);
308
309         hasProgressed |= tryToProgress(currentPhaseModifiers);
310
311         // TODO: use executionOrder instead?
312         if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
313             finishedPhase = phase;
314             LOG.debug("Source {} finished phase {}", source, phase);
315             if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
316                 // We have the effective model acquired, which is the final phase of source interaction.
317                 LOG.trace("Releasing source {}", source);
318                 source = null;
319             }
320             return PhaseCompletionProgress.FINISHED;
321         }
322
323         return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
324     }
325
326     private boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
327         boolean hasProgressed = false;
328
329         // We are about to iterate over the modifiers and invoke callbacks. Those callbacks can end up circling back
330         // and modifying the same collection. This asserts that modifiers should not be modified.
331         delayedModifiers = List.of();
332
333         // Try making forward progress ...
334         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
335         while (modifier.hasNext()) {
336             if (modifier.next().tryApply()) {
337                 modifier.remove();
338                 hasProgressed = true;
339             }
340         }
341
342         // We have finished iterating, if we have any delayed modifiers, put them back. This may seem as if we want
343         // to retry the loop, but we do not have to, as we will be circling back anyway.
344         //
345         // The thing is, we are inherently single-threaded and therefore if we observe non-empty delayedModifiers, the
346         // only way that could happen is through a callback, which in turn means we have made progress.
347         if (!delayedModifiers.isEmpty()) {
348             verify(hasProgressed, "Delayed modifiers encountered without making progress in %s", this);
349             for (Entry<ModelProcessingPhase, ModifierImpl> entry : delayedModifiers) {
350                 modifiers.put(entry.getKey(), entry.getValue());
351             }
352         }
353         delayedModifiers = null;
354
355         return hasProgressed;
356     }
357
358     @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
359         final ModifierImpl action = new ModifierImpl();
360
361         if (delayedModifiers != null) {
362             if (delayedModifiers.isEmpty()) {
363                 delayedModifiers = new ArrayList<>(2);
364             }
365             delayedModifiers.add(Map.entry(phase,action));
366         } else {
367             modifiers.put(phase, action);
368         }
369
370         return action;
371     }
372
373     @Override
374     public String toString() {
375         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
376                 + finishedPhase + "]";
377     }
378
379     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
380         final List<SourceException> exceptions = new ArrayList<>();
381         for (final ModifierImpl mod : modifiers.get(identifier)) {
382             try {
383                 mod.failModifier();
384             } catch (final SourceException e) {
385                 exceptions.add(e);
386             }
387         }
388
389         switch (exceptions.size()) {
390             case 0:
391                 return Optional.empty();
392             case 1:
393                 return Optional.of(exceptions.get(0));
394             default:
395                 final String message = String.format("Yang model processing phase %s failed", identifier);
396                 final InferenceException ex = new InferenceException(message, root, exceptions.get(0));
397                 exceptions.listIterator(1).forEachRemaining(ex::addSuppressed);
398                 return Optional.of(ex);
399         }
400     }
401
402     void loadStatements() {
403         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
404
405         switch (inProgressPhase) {
406             case SOURCE_PRE_LINKAGE:
407                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
408                 break;
409             case SOURCE_LINKAGE:
410                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
411                     getRootVersion());
412                 break;
413             case STATEMENT_DEFINITION:
414                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
415                     prefixes(), getRootVersion());
416                 break;
417             case FULL_DECLARATION:
418                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
419                     getRootVersion());
420                 break;
421             default:
422                 break;
423         }
424     }
425
426     private PrefixToModule preLinkagePrefixes() {
427         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
428         final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
429         if (prefixToNamespaceMap == null) {
430             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
431             return null;
432         }
433
434         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
435         return preLinkagePrefixes;
436     }
437
438     private PrefixToModule prefixes() {
439         final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
440             ImportPrefixToModuleCtx.class);
441         if (allImports != null) {
442             allImports.forEach((key, value) ->
443                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
444         }
445
446         final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
447             BelongsToPrefixToModuleCtx.class);
448         if (allBelongsTo != null) {
449             allBelongsTo.forEach((key, value) ->
450                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
451         }
452
453         return prefixToModuleMap;
454     }
455
456     private QNameToStatementDefinition stmtDef() {
457         // regular YANG statements and extension supports added
458         final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
459         qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
460         qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
461
462         // No further actions needed
463         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
464             return qnameToStmtDefMap;
465         }
466
467         // We need to any and all extension statements which have been declared in the context
468         final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
469                 StatementDefinitionNamespace.class);
470         if (extensions != null) {
471             extensions.forEach((qname, support) -> {
472                 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
473                 if (existing != null) {
474                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
475                 } else {
476                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
477                 }
478             });
479         }
480
481         return qnameToStmtDefMap;
482     }
483
484     Collection<SourceIdentifier> getRequiredSources() {
485         return root.getRequiredSources();
486     }
487
488     SourceIdentifier getRootIdentifier() {
489         return root.getRootIdentifier();
490     }
491 }