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