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 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;
15 import com.google.common.collect.HashMultimap;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Multimap;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.Objects;
25 import java.util.Optional;
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.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
48 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
49 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
55 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
56 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
57 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
58 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
59 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
66 public enum PhaseCompletionProgress {
72 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
74 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
75 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
76 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
77 private final BuildGlobalContext currentContext;
79 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
80 private StatementStreamSource source;
83 * "imported" namespaces in this source -- this points to RootStatementContexts of
84 * - modules imported via 'import' statement
85 * - parent module, declared via 'belongs-to' statement
87 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
88 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
89 private ModelProcessingPhase inProgressPhase;
90 private RootStatementContext<?, ?, ?> root;
92 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
93 this.currentContext = requireNonNull(currentContext);
94 this.source = requireNonNull(source);
97 boolean isEnabledSemanticVersioning() {
98 return currentContext.isEnabledSemanticVersioning();
101 ModelProcessingPhase getInProgressPhase() {
102 return inProgressPhase;
105 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
106 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
107 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
109 def = currentContext.getModelDefinedStatementDefinition(name);
111 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
112 if (extension != null) {
113 def = new StatementDefinitionContext<>(extension);
114 currentContext.putModelDefinedStatementDefinition(name, def);
117 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
119 * This code wraps statements encountered inside an extension so
120 * they do not get confused with regular statements.
122 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
123 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
127 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
128 .getArgumentDefinition().isPresent()) {
129 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
131 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
135 * If the current statement definition has argument specific
136 * sub-definitions, get argument specific sub-definition based on given
137 * argument (e.g. type statement need to be specialized based on its
140 if (def.hasArgumentSpecificSubDefinitions()) {
141 def = def.getSubDefinitionSpecificForArgument(argument);
144 if (current != null) {
145 return current.createSubstatement(childId, def, ref, argument);
149 * If root is null or root version is other than default,
150 * we need to create new root.
153 root = new RootStatementContext<>(this, def, ref, argument);
154 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
155 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
156 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
157 root.getRootIdentifier());
159 final QName rootStatement = root.definition().getStatementName();
160 final String rootArgument = root.rawStatementArgument();
162 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
163 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
168 RootStatementContext<?, ?, ?> getRoot() {
173 * Return version of root statement context.
175 * @return version of root statement context
177 YangVersion getRootVersion() {
178 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
181 DeclaredStatement<?> buildDeclared() {
182 return root.buildDeclared();
185 EffectiveStatement<?, ?> buildEffective() {
186 return root.buildEffective();
189 void startPhase(final ModelProcessingPhase phase) {
190 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
191 verify(Objects.equals(previousPhase, finishedPhase),
192 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
195 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
196 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
197 previousPhase, previousModifiers, source);
199 inProgressPhase = phase;
200 LOG.debug("Source {} started phase {}", source, phase);
203 private void updateImportedNamespaces(final Class<?> type, final Object value) {
204 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
205 if (importedNamespaces.isEmpty()) {
206 importedNamespaces = new ArrayList<>(1);
209 verify(value instanceof RootStatementContext);
210 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
215 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
217 // RootStatementContext takes care of IncludedModuleContext and the rest...
218 final V ret = getRoot().putToLocalStorage(type, key, value);
219 // FIXME: what about duplicates?
220 updateImportedNamespaces(type, value);
225 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
227 // RootStatementContext takes care of IncludedModuleContext and the rest...
228 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
230 updateImportedNamespaces(type, value);
236 public StorageNodeType getStorageNodeType() {
237 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
241 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
242 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
243 if (potentialLocal != null) {
244 return potentialLocal;
247 for (final NamespaceStorageNode importedSource : importedNamespaces) {
248 final V potential = importedSource.getFromLocalStorage(type, key);
249 if (potential != null) {
257 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
258 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
259 if (potentialLocal != null) {
260 return potentialLocal;
263 for (final NamespaceStorageNode importedSource : importedNamespaces) {
264 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
266 if (potential != null) {
274 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
275 final Class<N> type) {
276 return currentContext.getNamespaceBehaviour(type);
280 public NamespaceStorageNode getParentNamespaceStorage() {
281 return currentContext;
284 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
285 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
287 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
288 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
289 .tryToCompletePhase(phase);
291 hasProgressed |= tryToProgress(currentPhaseModifiers);
293 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
294 finishedPhase = phase;
295 LOG.debug("Source {} finished phase {}", source, phase);
296 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
297 // We have the effective model acquired, which is the final phase of source interaction.
298 LOG.trace("Releasing source {}", source);
301 return PhaseCompletionProgress.FINISHED;
304 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
307 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
308 boolean hasProgressed = false;
310 // Try making forward progress ...
311 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
312 while (modifier.hasNext()) {
313 if (modifier.next().tryApply()) {
315 hasProgressed = true;
319 return hasProgressed;
322 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
323 final ModifierImpl action = new ModifierImpl();
324 modifiers.put(phase, action);
329 public String toString() {
330 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
331 + finishedPhase + "]";
334 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
335 final List<SourceException> exceptions = new ArrayList<>();
336 for (final ModifierImpl mod : modifiers.get(identifier)) {
339 } catch (final SourceException e) {
344 if (exceptions.isEmpty()) {
345 return Optional.empty();
348 final String message = String.format("Yang model processing phase %s failed", identifier);
349 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
351 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
353 return Optional.of(e);
356 void loadStatements() {
357 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
359 switch (inProgressPhase) {
360 case SOURCE_PRE_LINKAGE:
361 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
364 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
367 case STATEMENT_DEFINITION:
368 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
369 prefixes(), getRootVersion());
371 case FULL_DECLARATION:
372 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
380 private PrefixToModule preLinkagePrefixes() {
381 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
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)));
389 return preLinkagePrefixes;
392 private PrefixToModule prefixes() {
393 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
394 ImportPrefixToModuleCtx.class);
395 if (allImports != null) {
396 allImports.forEach((key, value) ->
397 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
400 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
401 BelongsToPrefixToModuleCtx.class);
402 if (allBelongsTo != null) {
403 allBelongsTo.forEach((key, value) ->
404 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
407 return prefixToModuleMap;
410 private QNameToStatementDefinition stmtDef() {
411 // regular YANG statements and extension supports added
412 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
413 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
414 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
416 // No further actions needed
417 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
418 return qnameToStmtDefMap;
421 // We need to any and all extension statements which have been declared in the context
422 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getNamespace(
423 StatementDefinitionNamespace.class);
424 if (extensions != null) {
425 extensions.forEach((qname, support) -> {
426 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
427 if (existing != null) {
428 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
430 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
435 return qnameToStmtDefMap;
438 public Set<YangVersion> getSupportedVersions() {
439 return currentContext.getSupportedVersions();
442 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
443 currentContext.addMutableStmtToSeal(mutableStatement);
446 Collection<SourceIdentifier> getRequiredSources() {
447 return root.getRequiredSources();
450 SourceIdentifier getRootIdentifier() {
451 return root.getRootIdentifier();