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.IdentifierNamespace;
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;
77 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
78 private StatementStreamSource source;
81 * "imported" namespaces in this source -- this points to RootStatementContexts of
82 * - modules imported via 'import' statement
83 * - parent module, declared via 'belongs-to' statement
85 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
86 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
87 private ModelProcessingPhase inProgressPhase;
88 private RootStatementContext<?, ?, ?> root;
90 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
91 this.currentContext = requireNonNull(currentContext);
92 this.source = requireNonNull(source);
95 boolean isEnabledSemanticVersioning() {
96 return currentContext.isEnabledSemanticVersioning();
99 ModelProcessingPhase getInProgressPhase() {
100 return inProgressPhase;
103 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
104 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
105 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
107 def = currentContext.getModelDefinedStatementDefinition(name);
109 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
110 if (extension != null) {
111 def = new StatementDefinitionContext<>(extension);
112 currentContext.putModelDefinedStatementDefinition(name, def);
115 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
117 * This code wraps statements encountered inside an extension so
118 * they do not get confused with regular statements.
120 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
121 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
125 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
126 .getArgumentDefinition().isPresent()) {
127 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
129 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
133 * If the current statement definition has argument specific
134 * sub-definitions, get argument specific sub-definition based on given
135 * argument (e.g. type statement need to be specialized based on its
138 if (def.hasArgumentSpecificSubDefinitions()) {
139 def = def.getSubDefinitionSpecificForArgument(argument);
142 if (current != null) {
143 return current.createSubstatement(childId, def, ref, argument);
147 * If root is null or root version is other than default,
148 * we need to create new root.
151 root = new RootStatementContext<>(this, def, ref, argument);
152 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
153 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
154 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
155 root.getRootIdentifier());
157 final QName rootStatement = root.definition().getStatementName();
158 final String rootArgument = root.rawStatementArgument();
160 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
161 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
166 RootStatementContext<?, ?, ?> getRoot() {
171 * Return version of root statement context.
173 * @return version of root statement context
175 YangVersion getRootVersion() {
176 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
179 void startPhase(final ModelProcessingPhase phase) {
180 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
181 verify(Objects.equals(previousPhase, finishedPhase),
182 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
185 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
186 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
187 previousPhase, previousModifiers, source);
189 inProgressPhase = phase;
190 LOG.debug("Source {} started phase {}", source, phase);
193 private void updateImportedNamespaces(final Class<?> type, final Object value) {
194 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
195 if (importedNamespaces.isEmpty()) {
196 importedNamespaces = new ArrayList<>(1);
199 verify(value instanceof RootStatementContext);
200 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
205 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
207 // RootStatementContext takes care of IncludedModuleContext and the rest...
208 final V ret = getRoot().putToLocalStorage(type, key, value);
209 // FIXME: what about duplicates?
210 updateImportedNamespaces(type, value);
215 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
217 // RootStatementContext takes care of IncludedModuleContext and the rest...
218 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
220 updateImportedNamespaces(type, value);
226 public StorageNodeType getStorageNodeType() {
227 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
231 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
232 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
233 if (potentialLocal != null) {
234 return potentialLocal;
237 for (final NamespaceStorageNode importedSource : importedNamespaces) {
238 final V potential = importedSource.getFromLocalStorage(type, key);
239 if (potential != null) {
247 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
248 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
249 if (potentialLocal != null) {
250 return potentialLocal;
253 for (final NamespaceStorageNode importedSource : importedNamespaces) {
254 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
256 if (potential != null) {
264 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
265 final Class<N> type) {
266 return currentContext.getNamespaceBehaviour(type);
270 public BuildGlobalContext getParentNamespaceStorage() {
271 return currentContext;
274 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
275 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
277 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
278 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
279 .tryToCompletePhase(phase);
281 hasProgressed |= tryToProgress(currentPhaseModifiers);
283 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
284 finishedPhase = phase;
285 LOG.debug("Source {} finished phase {}", source, phase);
286 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
287 // We have the effective model acquired, which is the final phase of source interaction.
288 LOG.trace("Releasing source {}", source);
291 return PhaseCompletionProgress.FINISHED;
294 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
297 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
298 boolean hasProgressed = false;
300 // Try making forward progress ...
301 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
302 while (modifier.hasNext()) {
303 if (modifier.next().tryApply()) {
305 hasProgressed = true;
309 return hasProgressed;
312 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
313 final ModifierImpl action = new ModifierImpl();
314 modifiers.put(phase, action);
319 public String toString() {
320 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
321 + finishedPhase + "]";
324 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
325 final List<SourceException> exceptions = new ArrayList<>();
326 for (final ModifierImpl mod : modifiers.get(identifier)) {
329 } catch (final SourceException e) {
334 if (exceptions.isEmpty()) {
335 return Optional.empty();
338 final String message = String.format("Yang model processing phase %s failed", identifier);
339 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
341 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
343 return Optional.of(e);
346 void loadStatements() {
347 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
349 switch (inProgressPhase) {
350 case SOURCE_PRE_LINKAGE:
351 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
354 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
357 case STATEMENT_DEFINITION:
358 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
359 prefixes(), getRootVersion());
361 case FULL_DECLARATION:
362 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
370 private PrefixToModule preLinkagePrefixes() {
371 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
372 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
373 if (prefixToNamespaceMap == null) {
374 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
378 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
379 return preLinkagePrefixes;
382 private PrefixToModule prefixes() {
383 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
384 ImportPrefixToModuleCtx.class);
385 if (allImports != null) {
386 allImports.forEach((key, value) ->
387 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
390 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
391 BelongsToPrefixToModuleCtx.class);
392 if (allBelongsTo != null) {
393 allBelongsTo.forEach((key, value) ->
394 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
397 return prefixToModuleMap;
400 private QNameToStatementDefinition stmtDef() {
401 // regular YANG statements and extension supports added
402 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
403 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
404 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
406 // No further actions needed
407 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
408 return qnameToStmtDefMap;
411 // We need to any and all extension statements which have been declared in the context
412 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getNamespace(
413 StatementDefinitionNamespace.class);
414 if (extensions != null) {
415 extensions.forEach((qname, support) -> {
416 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
417 if (existing != null) {
418 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
420 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
425 return qnameToStmtDefMap;
428 public Set<YangVersion> getSupportedVersions() {
429 return currentContext.getSupportedVersions();
432 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
433 currentContext.addMutableStmtToSeal(mutableStatement);
436 Collection<SourceIdentifier> getRequiredSources() {
437 return root.getRequiredSources();
440 SourceIdentifier getRootIdentifier() {
441 return root.getRootIdentifier();