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