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.api.meta.StatementSource;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
49 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
55 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
56 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
57 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
58 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
67 public enum PhaseCompletionProgress {
73 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
75 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
76 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
77 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
78 private final BuildGlobalContext currentContext;
80 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
81 private StatementStreamSource source;
84 * "imported" namespaces in this source -- this points to RootStatementContexts of
85 * - modules imported via 'import' statement
86 * - parent module, declared via 'belongs-to' statement
88 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
89 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
90 private ModelProcessingPhase inProgressPhase;
91 private RootStatementContext<?, ?, ?> root;
93 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
94 this.currentContext = requireNonNull(currentContext);
95 this.source = requireNonNull(source);
98 boolean isEnabledSemanticVersioning() {
99 return currentContext.isEnabledSemanticVersioning();
102 ModelProcessingPhase getInProgressPhase() {
103 return inProgressPhase;
106 Optional<AbstractResumedStatement<?, ?, ?>> lookupDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
108 if (current == null) {
109 return Optional.empty();
112 // Fast path: we are entering a statement which was emitted in previous phase
113 AbstractResumedStatement<?, ?, ?> existing = current.lookupSubstatement(childId);
114 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
115 existing = existing.lookupSubstatement(childId);
118 return Optional.ofNullable(existing);
121 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
122 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
123 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
125 def = currentContext.getModelDefinedStatementDefinition(name);
127 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
128 if (extension != null) {
129 def = new StatementDefinitionContext<>(extension);
130 currentContext.putModelDefinedStatementDefinition(name, def);
133 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
135 * This code wraps statements encountered inside an extension so
136 * they do not get confused with regular statements.
138 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
139 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
143 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
144 .getArgumentDefinition().isPresent()) {
145 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
147 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
151 * If the current statement definition has argument specific
152 * sub-definitions, get argument specific sub-definition based on given
153 * argument (e.g. type statement need to be specialized based on its
156 if (def.hasArgumentSpecificSubDefinitions()) {
157 def = def.getSubDefinitionSpecificForArgument(argument);
160 if (current != null) {
161 return current.createSubstatement(childId, def, ref, argument);
165 * If root is null or root version is other than default,
166 * we need to create new root.
169 root = new RootStatementContext<>(this, def, ref, argument);
170 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
171 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
172 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
173 root.getRootIdentifier());
175 final QName rootStatement = root.definition().getStatementName();
176 final String rootArgument = root.rawStatementArgument();
178 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
179 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
184 RootStatementContext<?, ?, ?> getRoot() {
189 * Return version of root statement context.
191 * @return version of root statement context
193 YangVersion getRootVersion() {
194 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
197 DeclaredStatement<?> buildDeclared() {
198 return root.buildDeclared();
201 EffectiveStatement<?, ?> buildEffective() {
202 return root.buildEffective();
205 void startPhase(final ModelProcessingPhase phase) {
206 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
207 verify(Objects.equals(previousPhase, finishedPhase),
208 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
211 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
212 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
213 previousPhase, previousModifiers, source);
215 inProgressPhase = phase;
216 LOG.debug("Source {} started phase {}", source, phase);
219 private void updateImportedNamespaces(final Class<?> type, final Object value) {
220 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
221 if (importedNamespaces.isEmpty()) {
222 importedNamespaces = new ArrayList<>(1);
225 verify(value instanceof RootStatementContext);
226 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
231 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
233 // RootStatementContext takes care of IncludedModuleContext and the rest...
234 final V ret = getRoot().putToLocalStorage(type, key, value);
235 // FIXME: what about duplicates?
236 updateImportedNamespaces(type, value);
241 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
243 // RootStatementContext takes care of IncludedModuleContext and the rest...
244 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
246 updateImportedNamespaces(type, value);
252 public StorageNodeType getStorageNodeType() {
253 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
257 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
258 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
259 if (potentialLocal != null) {
260 return potentialLocal;
263 for (final NamespaceStorageNode importedSource : importedNamespaces) {
264 final V potential = importedSource.getFromLocalStorage(type, key);
265 if (potential != null) {
273 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
274 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
275 if (potentialLocal != null) {
276 return potentialLocal;
279 for (final NamespaceStorageNode importedSource : importedNamespaces) {
280 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
282 if (potential != null) {
290 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
291 final Class<N> type) {
292 return currentContext.getNamespaceBehaviour(type);
296 public NamespaceStorageNode getParentNamespaceStorage() {
297 return currentContext;
300 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
301 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
303 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
304 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
305 .tryToCompletePhase(phase);
307 hasProgressed |= tryToProgress(currentPhaseModifiers);
309 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
310 finishedPhase = phase;
311 LOG.debug("Source {} finished phase {}", source, phase);
312 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
313 // We have the effective model acquired, which is the final phase of source interaction.
314 LOG.trace("Releasing source {}", source);
317 return PhaseCompletionProgress.FINISHED;
320 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
323 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
324 boolean hasProgressed = false;
326 // Try making forward progress ...
327 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
328 while (modifier.hasNext()) {
329 if (modifier.next().tryApply()) {
331 hasProgressed = true;
335 return hasProgressed;
338 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
339 final ModifierImpl action = new ModifierImpl();
340 modifiers.put(phase, action);
345 public String toString() {
346 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
347 + finishedPhase + "]";
350 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
351 final List<SourceException> exceptions = new ArrayList<>();
352 for (final ModifierImpl mod : modifiers.get(identifier)) {
355 } catch (final SourceException e) {
360 if (exceptions.isEmpty()) {
361 return Optional.empty();
364 final String message = String.format("Yang model processing phase %s failed", identifier);
365 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
367 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
369 return Optional.of(e);
372 void loadStatements() {
373 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
375 switch (inProgressPhase) {
376 case SOURCE_PRE_LINKAGE:
377 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
380 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
383 case STATEMENT_DEFINITION:
384 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
385 prefixes(), getRootVersion());
387 case FULL_DECLARATION:
388 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
396 private PrefixToModule preLinkagePrefixes() {
397 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
398 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
399 if (prefixToNamespaceMap == null) {
400 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
404 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
405 return preLinkagePrefixes;
408 private PrefixToModule prefixes() {
409 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
410 ImportPrefixToModuleCtx.class);
411 if (allImports != null) {
412 allImports.forEach((key, value) ->
413 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
416 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
417 BelongsToPrefixToModuleCtx.class);
418 if (allBelongsTo != null) {
419 allBelongsTo.forEach((key, value) ->
420 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
423 return prefixToModuleMap;
426 private QNameToStatementDefinition stmtDef() {
427 // regular YANG statements and extension supports added
428 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
429 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
430 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
432 // No further actions needed
433 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
434 return qnameToStmtDefMap;
437 // We need to any and all extension statements which have been declared in the context
438 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getNamespace(
439 StatementDefinitionNamespace.class);
440 if (extensions != null) {
441 extensions.forEach((qname, support) -> {
442 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
443 if (existing != null) {
444 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
446 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
451 return qnameToStmtDefMap;
454 public Set<YangVersion> getSupportedVersions() {
455 return currentContext.getSupportedVersions();
458 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
459 currentContext.addMutableStmtToSeal(mutableStatement);
462 Collection<SourceIdentifier> getRequiredSources() {
463 return root.getRequiredSources();
466 SourceIdentifier getRootIdentifier() {
467 return root.getRootIdentifier();