2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.HashMultimap;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Multimap;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Objects;
22 import java.util.Optional;
24 import javax.annotation.Nullable;
25 import org.opendaylight.yangtools.concepts.Mutable;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.common.YangVersion;
29 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
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.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
46 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
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;
61 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
63 public enum PhaseCompletionProgress {
69 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
70 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
71 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
72 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
73 private final BuildGlobalContext currentContext;
74 private final StatementStreamSource source;
77 * "imported" namespaces in this source -- this points to RootStatementContexts of
78 * - modules imported via 'import' statement
79 * - parent module, declared via 'belongs-to' statement
81 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
82 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
83 private ModelProcessingPhase inProgressPhase;
84 private RootStatementContext<?, ?, ?> root;
86 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
87 this.currentContext = Preconditions.checkNotNull(currentContext);
88 this.source = Preconditions.checkNotNull(source);
91 boolean isEnabledSemanticVersioning(){
92 return currentContext.isEnabledSemanticVersioning();
95 ModelProcessingPhase getInProgressPhase() {
96 return inProgressPhase;
99 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
100 final QName name, final String argument, final StatementSourceReference ref) {
101 if (current != null) {
102 // Fast path: we are entering a statement which was emitted in previous phase
103 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
104 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
105 existing = existing.lookupSubstatement(childId);
107 if (existing != null) {
112 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
114 def = currentContext.getModelDefinedStatementDefinition(name);
116 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
117 if (extension != null) {
118 def = new StatementDefinitionContext<>(extension);
119 currentContext.putModelDefinedStatementDefinition(name, def);
122 } else if (current != null && StmtContextUtils.isUnknownStatement(current)) {
124 * This code wraps statements encountered inside an extension so
125 * they do not get confused with regular statements.
127 def = Preconditions.checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
128 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
132 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
133 if (def.hasArgument()) {
134 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
136 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
140 * If the current statement definition has argument specific
141 * sub-definitions, get argument specific sub-definition based on given
142 * argument (e.g. type statement need to be specialized based on its
145 if (def.hasArgumentSpecificSubDefinitions()) {
146 def = def.getSubDefinitionSpecificForArgument(argument);
149 if (current != null) {
150 return current.createSubstatement(childId, def, ref, argument);
154 * If root is null or root version is other than default,
155 * we need to create new root.
158 root = new RootStatementContext<>(this, def, ref, argument);
159 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
160 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
161 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(), root.getRootIdentifier());
163 final QName rootStatement = root.definition().getStatementName();
164 final String rootArgument = root.rawStatementArgument();
166 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
167 && Objects.equals(argument, rootArgument),
168 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
173 RootStatementContext<?, ?, ?> getRoot() {
178 * Return version of root statement context.
180 * @return version of root statement context
182 YangVersion getRootVersion() {
183 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
186 DeclaredStatement<?> buildDeclared() {
187 return root.buildDeclared();
190 EffectiveStatement<?, ?> buildEffective() {
191 return root.buildEffective();
194 void startPhase(final ModelProcessingPhase phase) {
195 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
196 Verify.verify(Objects.equals(previousPhase, finishedPhase),
197 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
200 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
201 Preconditions.checkState(previousModifiers.isEmpty(),
202 "Previous phase %s has unresolved modifiers %s in source %s",
203 previousPhase, previousModifiers, source);
205 inProgressPhase = phase;
206 LOG.debug("Source {} started phase {}", source, phase);
209 private void updateImportedNamespaces(final Class<?> type, final Object value) {
210 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
211 if (importedNamespaces.isEmpty()) {
212 importedNamespaces = new ArrayList<>(1);
215 Verify.verify(value instanceof RootStatementContext);
216 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
221 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
223 // RootStatementContext takes care of IncludedModuleContext and the rest...
224 final V ret = getRoot().putToLocalStorage(type, key, value);
225 // FIXME: what about duplicates?
226 updateImportedNamespaces(type, value);
231 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
233 // RootStatementContext takes care of IncludedModuleContext and the rest...
234 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
236 updateImportedNamespaces(type, value);
242 public StorageNodeType getStorageNodeType() {
243 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
247 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
248 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
249 if (potentialLocal != null) {
250 return potentialLocal;
253 for (final NamespaceStorageNode importedSource : importedNamespaces) {
254 final V potential = importedSource.getFromLocalStorage(type, key);
255 if (potential != null) {
264 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
265 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
266 if (potentialLocal != null) {
267 return potentialLocal;
270 for (final NamespaceStorageNode importedSource : importedNamespaces) {
271 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
273 if (potential != null) {
281 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
282 final Class<N> type) {
283 return currentContext.getNamespaceBehaviour(type);
287 public NamespaceStorageNode getParentNamespaceStorage() {
288 return currentContext;
291 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
292 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
294 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
296 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
297 final boolean phaseCompleted = root.tryToCompletePhase(phase);
299 hasProgressed |= tryToProgress(currentPhaseModifiers);
301 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
302 finishedPhase = phase;
303 LOG.debug("Source {} finished phase {}", source, phase);
304 return PhaseCompletionProgress.FINISHED;
308 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
311 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
312 boolean hasProgressed = false;
314 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
315 while (modifier.hasNext()) {
316 if (modifier.next().tryApply()) {
318 hasProgressed = true;
322 return hasProgressed;
325 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
326 final ModifierImpl action = new ModifierImpl(phase);
327 modifiers.put(phase, action);
332 public String toString() {
333 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
334 + finishedPhase + "]";
337 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
338 final List<SourceException> exceptions = new ArrayList<>();
339 for (final ModifierImpl mod : modifiers.get(identifier)) {
342 } catch (final SourceException e) {
347 if (exceptions.isEmpty()) {
348 return Optional.empty();
351 final String message = String.format("Yang model processing phase %s failed", identifier);
352 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
354 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
356 return Optional.of(e);
359 void loadStatements() throws SourceException {
360 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
362 switch (inProgressPhase) {
363 case SOURCE_PRE_LINKAGE:
364 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
367 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(), getRootVersion());
369 case STATEMENT_DEFINITION:
370 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
372 case FULL_DECLARATION:
373 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
380 private PrefixToModule preLinkagePrefixes() {
381 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
382 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
383 if (prefixToNamespaceMap == null) {
384 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
388 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
389 return preLinkagePrefixes;
392 private PrefixToModule prefixes() {
393 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
395 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
396 (BelongsToPrefixToModuleIdentifier.class);
397 if (belongsToPrefixes != null) {
398 allPrefixes.putAll(belongsToPrefixes);
401 allPrefixes.forEach((key, value) ->
402 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
404 return prefixToModuleMap;
407 private QNameToStatementDefinition stmtDef() {
408 // regular YANG statements and extension supports added
409 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
410 qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
411 qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
413 // No further actions needed
414 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
415 return qNameToStmtDefMap;
418 // We need to any and all extension statements which have been declared in the context
419 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
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);
427 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
432 return qNameToStmtDefMap;
435 public Set<YangVersion> getSupportedVersions() {
436 return currentContext.getSupportedVersions();
439 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
440 currentContext.addMutableStmtToSeal(mutableStatement);
443 Collection<ModuleIdentifier> getRequiredModules() {
444 return root.getRequiredModules();
447 ModuleIdentifier getRootIdentifier() {
448 return root.getRootIdentifier();