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.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
33 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
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.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;
62 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
64 public enum PhaseCompletionProgress {
70 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
72 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
73 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
74 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
75 private final BuildGlobalContext currentContext;
76 private final StatementStreamSource source;
79 * "imported" namespaces in this source -- this points to RootStatementContexts of
80 * - modules imported via 'import' statement
81 * - parent module, declared via 'belongs-to' statement
83 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
84 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
85 private ModelProcessingPhase inProgressPhase;
86 private RootStatementContext<?, ?, ?> root;
88 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
89 this.currentContext = Preconditions.checkNotNull(currentContext);
90 this.source = Preconditions.checkNotNull(source);
93 boolean isEnabledSemanticVersioning() {
94 return currentContext.isEnabledSemanticVersioning();
97 ModelProcessingPhase getInProgressPhase() {
98 return inProgressPhase;
101 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
102 final QName name, final String argument, final StatementSourceReference ref) {
103 if (current != null) {
104 // Fast path: we are entering a statement which was emitted in previous phase
105 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
106 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
107 existing = existing.lookupSubstatement(childId);
109 if (existing != null) {
114 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
116 def = currentContext.getModelDefinedStatementDefinition(name);
118 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
119 if (extension != null) {
120 def = new StatementDefinitionContext<>(extension);
121 currentContext.putModelDefinedStatementDefinition(name, def);
124 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
126 * This code wraps statements encountered inside an extension so
127 * they do not get confused with regular statements.
129 def = Preconditions.checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
130 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
134 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
135 if (def.hasArgument()) {
136 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
138 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
142 * If the current statement definition has argument specific
143 * sub-definitions, get argument specific sub-definition based on given
144 * argument (e.g. type statement need to be specialized based on its
147 if (def.hasArgumentSpecificSubDefinitions()) {
148 def = def.getSubDefinitionSpecificForArgument(argument);
151 if (current != null) {
152 return current.createSubstatement(childId, def, ref, argument);
156 * If root is null or root version is other than default,
157 * we need to create new root.
160 root = new RootStatementContext<>(this, def, ref, argument);
161 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
162 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
163 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
164 root.getRootIdentifier());
166 final QName rootStatement = root.definition().getStatementName();
167 final String rootArgument = root.rawStatementArgument();
169 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
170 && Objects.equals(argument, rootArgument), "Root statement was already defined as '%s %s'.",
171 rootStatement, rootArgument);
176 RootStatementContext<?, ?, ?> getRoot() {
181 * Return version of root statement context.
183 * @return version of root statement context
185 YangVersion getRootVersion() {
186 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
189 DeclaredStatement<?> buildDeclared() {
190 return root.buildDeclared();
193 EffectiveStatement<?, ?> buildEffective() {
194 return root.buildEffective();
197 void startPhase(final ModelProcessingPhase phase) {
198 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
199 Verify.verify(Objects.equals(previousPhase, finishedPhase),
200 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
203 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
204 Preconditions.checkState(previousModifiers.isEmpty(),
205 "Previous phase %s has unresolved modifiers %s in source %s", previousPhase, previousModifiers, source);
207 inProgressPhase = phase;
208 LOG.debug("Source {} started phase {}", source, phase);
211 private void updateImportedNamespaces(final Class<?> type, final Object value) {
212 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
213 if (importedNamespaces.isEmpty()) {
214 importedNamespaces = new ArrayList<>(1);
217 Verify.verify(value instanceof RootStatementContext);
218 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
223 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
225 // RootStatementContext takes care of IncludedModuleContext and the rest...
226 final V ret = getRoot().putToLocalStorage(type, key, value);
227 // FIXME: what about duplicates?
228 updateImportedNamespaces(type, value);
233 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
235 // RootStatementContext takes care of IncludedModuleContext and the rest...
236 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
238 updateImportedNamespaces(type, value);
244 public StorageNodeType getStorageNodeType() {
245 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
249 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
250 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
251 if (potentialLocal != null) {
252 return potentialLocal;
255 for (final NamespaceStorageNode importedSource : importedNamespaces) {
256 final V potential = importedSource.getFromLocalStorage(type, key);
257 if (potential != null) {
266 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
267 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
268 if (potentialLocal != null) {
269 return potentialLocal;
272 for (final NamespaceStorageNode importedSource : importedNamespaces) {
273 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
275 if (potential != null) {
283 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
284 final Class<N> type) {
285 return currentContext.getNamespaceBehaviour(type);
289 public NamespaceStorageNode getParentNamespaceStorage() {
290 return currentContext;
293 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
294 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
296 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
298 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
299 final boolean phaseCompleted = root.tryToCompletePhase(phase);
301 hasProgressed |= tryToProgress(currentPhaseModifiers);
303 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
304 finishedPhase = phase;
305 LOG.debug("Source {} finished phase {}", source, phase);
306 return PhaseCompletionProgress.FINISHED;
310 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
313 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
314 boolean hasProgressed = false;
316 // Try making forward progress ...
317 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
318 while (modifier.hasNext()) {
319 if (modifier.next().tryApply()) {
321 hasProgressed = true;
325 return hasProgressed;
328 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
329 final ModifierImpl action = new ModifierImpl();
330 modifiers.put(phase, action);
335 public String toString() {
336 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
337 + finishedPhase + "]";
340 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
341 final List<SourceException> exceptions = new ArrayList<>();
342 for (final ModifierImpl mod : modifiers.get(identifier)) {
345 } catch (final SourceException e) {
350 if (exceptions.isEmpty()) {
351 return Optional.empty();
354 final String message = String.format("Yang model processing phase %s failed", identifier);
355 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
357 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
359 return Optional.of(e);
362 void loadStatements() throws SourceException {
363 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
365 switch (inProgressPhase) {
366 case SOURCE_PRE_LINKAGE:
367 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
370 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
373 case STATEMENT_DEFINITION:
374 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
375 prefixes(), getRootVersion());
377 case FULL_DECLARATION:
378 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
386 private PrefixToModule preLinkagePrefixes() {
387 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
388 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
389 if (prefixToNamespaceMap == null) {
390 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
394 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
395 return preLinkagePrefixes;
398 private PrefixToModule prefixes() {
399 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
400 ImportPrefixToModuleCtx.class);
401 if (allImports != null) {
402 allImports.forEach((key, value) ->
403 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
406 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
407 BelongsToPrefixToModuleCtx.class);
408 if (allBelongsTo != null) {
409 allBelongsTo.forEach((key, value) ->
410 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
413 return prefixToModuleMap;
416 private QNameToStatementDefinition stmtDef() {
417 // regular YANG statements and extension supports added
418 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
419 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
420 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
422 // No further actions needed
423 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
424 return qnameToStmtDefMap;
427 // We need to any and all extension statements which have been declared in the context
428 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
429 StatementDefinitionNamespace.class);
430 if (extensions != null) {
431 extensions.forEach((qname, support) -> {
432 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
433 if (existing != null) {
434 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
436 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
441 return qnameToStmtDefMap;
444 public Set<YangVersion> getSupportedVersions() {
445 return currentContext.getSupportedVersions();
448 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
449 currentContext.addMutableStmtToSeal(mutableStatement);
452 Collection<SourceIdentifier> getRequiredSources() {
453 return root.getRequiredSources();
456 SourceIdentifier getRootIdentifier() {
457 return root.getRootIdentifier();