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;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.yangtools.concepts.Mutable;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.YangVersion;
31 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
34 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
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 final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
63 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 @NonNull BuildGlobalContext globalContext;
76 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
77 private StatementStreamSource source;
80 * "imported" namespaces in this source -- this points to RootStatementContexts of
81 * - modules imported via 'import' statement
82 * - parent module, declared via 'belongs-to' statement
84 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
85 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
86 private ModelProcessingPhase inProgressPhase;
87 private RootStatementContext<?, ?, ?> root;
89 SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
90 this.globalContext = requireNonNull(globalContext);
91 this.source = requireNonNull(source);
94 @NonNull BuildGlobalContext globalContext() {
98 ModelProcessingPhase getInProgressPhase() {
99 return inProgressPhase;
102 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
103 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
104 StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
106 def = globalContext.getModelDefinedStatementDefinition(name);
108 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
109 if (extension != null) {
110 def = new StatementDefinitionContext<>(extension);
111 globalContext.putModelDefinedStatementDefinition(name, def);
114 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
116 * This code wraps statements encountered inside an extension so
117 * they do not get confused with regular statements.
119 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
120 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
124 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
125 .getArgumentDefinition().isPresent()) {
126 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
128 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
132 * If the current statement definition has argument specific
133 * sub-definitions, get argument specific sub-definition based on given
134 * argument (e.g. type statement need to be specialized based on its
137 if (def.hasArgumentSpecificSubDefinitions()) {
138 def = def.getSubDefinitionSpecificForArgument(argument);
141 if (current != null) {
142 return current.createSubstatement(childId, def, ref, argument);
146 * If root is null or root version is other than default,
147 * we need to create new root.
150 root = new RootStatementContext<>(this, def, ref, argument);
151 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
152 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
153 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
154 root.getRootIdentifier());
156 final QName rootStatement = root.definition().getStatementName();
157 final String rootArgument = root.rawStatementArgument();
159 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
160 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
165 RootStatementContext<?, ?, ?> getRoot() {
170 * Return version of root statement context.
172 * @return version of root statement context
174 YangVersion getRootVersion() {
175 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
178 DeclaredStatement<?> buildDeclared() {
179 return root.buildDeclared();
182 EffectiveStatement<?, ?> buildEffective() {
183 return root.buildEffective();
186 void startPhase(final ModelProcessingPhase phase) {
187 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
188 verify(Objects.equals(previousPhase, finishedPhase),
189 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
192 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
193 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
194 previousPhase, previousModifiers, source);
196 inProgressPhase = phase;
197 LOG.debug("Source {} started phase {}", source, phase);
200 private void updateImportedNamespaces(final Class<?> type, final Object value) {
201 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
202 if (importedNamespaces.isEmpty()) {
203 importedNamespaces = new ArrayList<>(1);
206 verify(value instanceof RootStatementContext);
207 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
212 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
214 // RootStatementContext takes care of IncludedModuleContext and the rest...
215 final V ret = getRoot().putToLocalStorage(type, key, value);
216 // FIXME: what about duplicates?
217 updateImportedNamespaces(type, value);
222 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
224 // RootStatementContext takes care of IncludedModuleContext and the rest...
225 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
227 updateImportedNamespaces(type, value);
233 public StorageNodeType getStorageNodeType() {
234 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
238 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
239 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
240 if (potentialLocal != null) {
241 return potentialLocal;
244 for (final NamespaceStorageNode importedSource : importedNamespaces) {
245 final V potential = importedSource.getFromLocalStorage(type, key);
246 if (potential != null) {
254 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
255 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
256 if (potentialLocal != null) {
257 return potentialLocal;
260 for (final NamespaceStorageNode importedSource : importedNamespaces) {
261 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
263 if (potential != null) {
271 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
272 final Class<N> type) {
273 return globalContext.getNamespaceBehaviour(type);
277 public BuildGlobalContext getParentNamespaceStorage() {
278 return globalContext;
281 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
282 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
284 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
285 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
286 .tryToCompletePhase(phase);
288 hasProgressed |= tryToProgress(currentPhaseModifiers);
290 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
291 finishedPhase = phase;
292 LOG.debug("Source {} finished phase {}", source, phase);
293 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
294 // We have the effective model acquired, which is the final phase of source interaction.
295 LOG.trace("Releasing source {}", source);
298 return PhaseCompletionProgress.FINISHED;
301 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
304 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
305 boolean hasProgressed = false;
307 // Try making forward progress ...
308 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
309 while (modifier.hasNext()) {
310 if (modifier.next().tryApply()) {
312 hasProgressed = true;
316 return hasProgressed;
319 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
320 final ModifierImpl action = new ModifierImpl();
321 modifiers.put(phase, action);
326 public String toString() {
327 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
328 + finishedPhase + "]";
331 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
332 final List<SourceException> exceptions = new ArrayList<>();
333 for (final ModifierImpl mod : modifiers.get(identifier)) {
336 } catch (final SourceException e) {
341 if (exceptions.isEmpty()) {
342 return Optional.empty();
345 final String message = String.format("Yang model processing phase %s failed", identifier);
346 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
348 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
350 return Optional.of(e);
353 void loadStatements() {
354 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
356 switch (inProgressPhase) {
357 case SOURCE_PRE_LINKAGE:
358 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
361 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
364 case STATEMENT_DEFINITION:
365 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
366 prefixes(), getRootVersion());
368 case FULL_DECLARATION:
369 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
377 private PrefixToModule preLinkagePrefixes() {
378 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
379 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
380 if (prefixToNamespaceMap == null) {
381 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
385 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
386 return preLinkagePrefixes;
389 private PrefixToModule prefixes() {
390 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
391 ImportPrefixToModuleCtx.class);
392 if (allImports != null) {
393 allImports.forEach((key, value) ->
394 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
397 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
398 BelongsToPrefixToModuleCtx.class);
399 if (allBelongsTo != null) {
400 allBelongsTo.forEach((key, value) ->
401 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
404 return prefixToModuleMap;
407 private QNameToStatementDefinition stmtDef() {
408 // regular YANG statements and extension supports added
409 final StatementSupportBundle supportsForPhase = globalContext.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 = globalContext.getNamespace(
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 Collection<SourceIdentifier> getRequiredSources() {
436 return root.getRequiredSources();
439 SourceIdentifier getRootIdentifier() {
440 return root.getRootIdentifier();