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