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);
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 BuildGlobalContext currentContext;
75 private final StatementStreamSource source;
78 * "imported" namespaces in this source -- this points to RootStatementContexts of
79 * - modules imported via 'import' statement
80 * - parent module, declared via 'belongs-to' statement
82 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
83 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
84 private ModelProcessingPhase inProgressPhase;
85 private RootStatementContext<?, ?, ?> root;
87 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
88 this.currentContext = Preconditions.checkNotNull(currentContext);
89 this.source = Preconditions.checkNotNull(source);
92 boolean isEnabledSemanticVersioning() {
93 return currentContext.isEnabledSemanticVersioning();
96 ModelProcessingPhase getInProgressPhase() {
97 return inProgressPhase;
100 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
101 final QName name, final String argument, final StatementSourceReference ref) {
102 if (current != null) {
103 // Fast path: we are entering a statement which was emitted in previous phase
104 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
105 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
106 existing = existing.lookupSubstatement(childId);
108 if (existing != null) {
113 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
115 def = currentContext.getModelDefinedStatementDefinition(name);
117 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
118 if (extension != null) {
119 def = new StatementDefinitionContext<>(extension);
120 currentContext.putModelDefinedStatementDefinition(name, def);
123 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
125 * This code wraps statements encountered inside an extension so
126 * they do not get confused with regular statements.
128 def = Preconditions.checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
129 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
133 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
134 if (def.hasArgument()) {
135 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
137 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
141 * If the current statement definition has argument specific
142 * sub-definitions, get argument specific sub-definition based on given
143 * argument (e.g. type statement need to be specialized based on its
146 if (def.hasArgumentSpecificSubDefinitions()) {
147 def = def.getSubDefinitionSpecificForArgument(argument);
150 if (current != null) {
151 return current.createSubstatement(childId, def, ref, argument);
155 * If root is null or root version is other than default,
156 * we need to create new root.
159 root = new RootStatementContext<>(this, def, ref, argument);
160 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
161 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
162 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
163 root.getRootIdentifier());
165 final QName rootStatement = root.definition().getStatementName();
166 final String rootArgument = root.rawStatementArgument();
168 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
169 && Objects.equals(argument, rootArgument), "Root statement was already defined as '%s %s'.",
170 rootStatement, rootArgument);
175 RootStatementContext<?, ?, ?> getRoot() {
180 * Return version of root statement context.
182 * @return version of root statement context
184 YangVersion getRootVersion() {
185 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
188 DeclaredStatement<?> buildDeclared() {
189 return root.buildDeclared();
192 EffectiveStatement<?, ?> buildEffective() {
193 return root.buildEffective();
196 void startPhase(final ModelProcessingPhase phase) {
197 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
198 Verify.verify(Objects.equals(previousPhase, finishedPhase),
199 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
202 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
203 Preconditions.checkState(previousModifiers.isEmpty(),
204 "Previous phase %s has unresolved modifiers %s in source %s", previousPhase, previousModifiers, source);
206 inProgressPhase = phase;
207 LOG.debug("Source {} started phase {}", source, phase);
210 private void updateImportedNamespaces(final Class<?> type, final Object value) {
211 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
212 if (importedNamespaces.isEmpty()) {
213 importedNamespaces = new ArrayList<>(1);
216 Verify.verify(value instanceof RootStatementContext);
217 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
222 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
224 // RootStatementContext takes care of IncludedModuleContext and the rest...
225 final V ret = getRoot().putToLocalStorage(type, key, value);
226 // FIXME: what about duplicates?
227 updateImportedNamespaces(type, value);
232 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
234 // RootStatementContext takes care of IncludedModuleContext and the rest...
235 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
237 updateImportedNamespaces(type, value);
243 public StorageNodeType getStorageNodeType() {
244 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
248 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
249 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
250 if (potentialLocal != null) {
251 return potentialLocal;
254 for (final NamespaceStorageNode importedSource : importedNamespaces) {
255 final V potential = importedSource.getFromLocalStorage(type, key);
256 if (potential != null) {
265 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
266 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
267 if (potentialLocal != null) {
268 return potentialLocal;
271 for (final NamespaceStorageNode importedSource : importedNamespaces) {
272 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
274 if (potential != null) {
282 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
283 final Class<N> type) {
284 return currentContext.getNamespaceBehaviour(type);
288 public NamespaceStorageNode getParentNamespaceStorage() {
289 return currentContext;
292 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
293 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
295 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
297 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
298 final boolean phaseCompleted = root.tryToCompletePhase(phase);
300 hasProgressed |= tryToProgress(currentPhaseModifiers);
302 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
303 finishedPhase = phase;
304 LOG.debug("Source {} finished phase {}", source, phase);
305 return PhaseCompletionProgress.FINISHED;
309 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
312 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
313 boolean hasProgressed = false;
315 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
316 while (modifier.hasNext()) {
317 if (modifier.next().tryApply()) {
319 hasProgressed = true;
323 return hasProgressed;
326 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
327 final ModifierImpl action = new ModifierImpl();
328 modifiers.put(phase, action);
333 public String toString() {
334 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
335 + finishedPhase + "]";
338 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
339 final List<SourceException> exceptions = new ArrayList<>();
340 for (final ModifierImpl mod : modifiers.get(identifier)) {
343 } catch (final SourceException e) {
348 if (exceptions.isEmpty()) {
349 return Optional.empty();
352 final String message = String.format("Yang model processing phase %s failed", identifier);
353 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
355 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
357 return Optional.of(e);
360 void loadStatements() throws SourceException {
361 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
363 switch (inProgressPhase) {
364 case SOURCE_PRE_LINKAGE:
365 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
368 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
371 case STATEMENT_DEFINITION:
372 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
373 prefixes(), getRootVersion());
375 case FULL_DECLARATION:
376 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
384 private PrefixToModule preLinkagePrefixes() {
385 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
386 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
387 if (prefixToNamespaceMap == null) {
388 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
392 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
393 return preLinkagePrefixes;
396 private PrefixToModule prefixes() {
397 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(
398 ImpPrefixToModuleIdentifier.class);
399 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace(
400 BelongsToPrefixToModuleIdentifier.class);
401 if (belongsToPrefixes != null) {
402 allPrefixes.putAll(belongsToPrefixes);
405 allPrefixes.forEach((key, value) ->
406 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
408 return prefixToModuleMap;
411 private QNameToStatementDefinition stmtDef() {
412 // regular YANG statements and extension supports added
413 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
414 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
415 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
417 // No further actions needed
418 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
419 return qnameToStmtDefMap;
422 // We need to any and all extension statements which have been declared in the context
423 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
424 StatementDefinitionNamespace.class);
425 if (extensions != null) {
426 extensions.forEach((qname, support) -> {
427 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
428 if (existing != null) {
429 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
431 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
436 return qnameToStmtDefMap;
439 public Set<YangVersion> getSupportedVersions() {
440 return currentContext.getSupportedVersions();
443 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
444 currentContext.addMutableStmtToSeal(mutableStatement);
447 Collection<ModuleIdentifier> getRequiredModules() {
448 return root.getRequiredModules();
451 ModuleIdentifier getRootIdentifier() {
452 return root.getRootIdentifier();