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.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
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;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Iterator;
21 import java.util.List;
23 import java.util.Map.Entry;
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.XMLNamespace;
31 import org.opendaylight.yangtools.yang.common.YangVersion;
32 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
46 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
51 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
52 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
53 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
54 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
62 enum PhaseCompletionProgress {
68 private static final class SupportedStatements
69 extends NamespaceBehaviour<QName, StatementSupport<?, ?, ?>, StatementSupportNamespace> {
70 private final QNameToStatementDefinitionMap statementDefinitions;
72 SupportedStatements(final QNameToStatementDefinitionMap statementDefinitions) {
73 super(StatementSupportNamespace.class);
74 this.statementDefinitions = requireNonNull(statementDefinitions);
78 public StatementSupport<?, ?, ?> getFrom(final NamespaceStorageNode storage, final QName key) {
79 return statementDefinitions.get(key);
83 public Map<QName, StatementSupport<?, ?, ?>> getAllFrom(final NamespaceStorageNode storage) {
84 throw new UnsupportedOperationException("StatementSupportNamespace is immutable");
88 public void addTo(final NamespaceStorageNode storage, final QName key, final StatementSupport<?, ?, ?> value) {
89 throw new UnsupportedOperationException("StatementSupportNamespace is immutable");
93 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
95 // TODO: consider keying by Byte equivalent of ExecutionOrder
96 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
97 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
98 private final SupportedStatements statementSupports = new SupportedStatements(qnameToStmtDefMap);
99 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
100 private final @NonNull BuildGlobalContext globalContext;
102 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
103 private StatementStreamSource source;
106 * "imported" namespaces in this source -- this points to RootStatementContexts of
107 * - modules imported via 'import' statement
108 * - parent module, declared via 'belongs-to' statement
110 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
111 private RootStatementContext<?, ?, ?> root;
112 // TODO: consider using ExecutionOrder byte for these two
113 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
114 private ModelProcessingPhase inProgressPhase;
116 // If not null, do not add anything to modifiers, but record it here.
117 private List<Entry<ModelProcessingPhase, ModifierImpl>> delayedModifiers;
119 SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
120 this.globalContext = requireNonNull(globalContext);
121 this.source = requireNonNull(source);
124 @NonNull BuildGlobalContext globalContext() {
125 return globalContext;
128 ModelProcessingPhase getInProgressPhase() {
129 return inProgressPhase;
132 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
133 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
134 StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
136 def = globalContext.getModelDefinedStatementDefinition(name);
138 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
139 if (extension != null) {
140 def = new StatementDefinitionContext<>(extension);
141 globalContext.putModelDefinedStatementDefinition(name, def);
144 } else if (current != null) {
145 def = current.definition().overrideDefinition(def);
148 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
149 .getArgumentDefinition().isPresent()) {
150 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
152 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
156 * If the current statement definition has argument specific
157 * sub-definitions, get argument specific sub-definition based on given
158 * argument (e.g. type statement need to be specialized based on its
161 if (def.hasArgumentSpecificSubDefinitions()) {
162 def = def.getSubDefinitionSpecificForArgument(argument);
165 if (current != null) {
166 return current.createSubstatement(childId, def, ref, argument);
170 * If root is null or root version is other than default,
171 * we need to create new root.
174 root = new RootStatementContext<>(this, def, ref, argument);
175 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
176 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
177 root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
178 root.getRootIdentifier());
180 final QName rootStatement = root.definition().getStatementName();
181 final String rootArgument = root.rawArgument();
183 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
184 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
189 RootStatementContext<?, ?, ?> getRoot() {
194 * Return version of root statement context.
196 * @return version of root statement context
198 YangVersion getRootVersion() {
199 return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
202 void startPhase(final ModelProcessingPhase phase) {
203 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
204 verify(Objects.equals(previousPhase, finishedPhase),
205 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
208 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
209 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
210 previousPhase, previousModifiers, source);
212 inProgressPhase = phase;
213 LOG.debug("Source {} started phase {}", source, phase);
216 private void updateImportedNamespaces(final Class<?> type, final Object value) {
217 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
218 if (importedNamespaces.isEmpty()) {
219 importedNamespaces = new ArrayList<>(1);
222 verify(value instanceof RootStatementContext);
223 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
228 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
230 // RootStatementContext takes care of IncludedModuleContext and the rest...
231 final V ret = getRoot().putToLocalStorage(type, key, value);
232 // FIXME: what about duplicates?
233 updateImportedNamespaces(type, value);
238 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
240 // RootStatementContext takes care of IncludedModuleContext and the rest...
241 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
243 updateImportedNamespaces(type, value);
249 public StorageNodeType getStorageNodeType() {
250 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
254 public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
255 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
256 if (potentialLocal != null) {
257 return potentialLocal;
260 for (final NamespaceStorageNode importedSource : importedNamespaces) {
261 final V potential = importedSource.getFromLocalStorage(type, key);
262 if (potential != null) {
270 public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
271 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
272 if (potentialLocal != null) {
273 return potentialLocal;
276 for (final NamespaceStorageNode importedSource : importedNamespaces) {
277 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
279 if (potential != null) {
287 @SuppressWarnings("unchecked")
288 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
289 final Class<N> type) {
290 if (StatementSupportNamespace.class.equals(type)) {
291 return (NamespaceBehaviour<K, V, N>) statementSupports;
293 return globalContext.getNamespaceBehaviour(type);
297 public BuildGlobalContext getParentNamespaceStorage() {
298 return globalContext;
301 PhaseCompletionProgress tryToCompletePhase(final byte executionOrder) {
302 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(executionOrder));
303 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
305 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
306 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
307 .tryToCompletePhase(executionOrder);
309 hasProgressed |= tryToProgress(currentPhaseModifiers);
311 // TODO: use executionOrder instead?
312 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
313 finishedPhase = phase;
314 LOG.debug("Source {} finished phase {}", source, phase);
315 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
316 // We have the effective model acquired, which is the final phase of source interaction.
317 LOG.trace("Releasing source {}", source);
320 return PhaseCompletionProgress.FINISHED;
323 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
326 private boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
327 boolean hasProgressed = false;
329 // We are about to iterate over the modifiers and invoke callbacks. Those callbacks can end up circling back
330 // and modifying the same collection. This asserts that modifiers should not be modified.
331 delayedModifiers = List.of();
333 // Try making forward progress ...
334 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
335 while (modifier.hasNext()) {
336 if (modifier.next().tryApply()) {
338 hasProgressed = true;
342 // We have finished iterating, if we have any delayed modifiers, put them back. This may seem as if we want
343 // to retry the loop, but we do not have to, as we will be circling back anyway.
345 // The thing is, we are inherently single-threaded and therefore if we observe non-empty delayedModifiers, the
346 // only way that could happen is through a callback, which in turn means we have made progress.
347 if (!delayedModifiers.isEmpty()) {
348 verify(hasProgressed, "Delayed modifiers encountered without making progress in %s", this);
349 for (Entry<ModelProcessingPhase, ModifierImpl> entry : delayedModifiers) {
350 modifiers.put(entry.getKey(), entry.getValue());
353 delayedModifiers = null;
355 return hasProgressed;
358 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
359 final ModifierImpl action = new ModifierImpl();
361 if (delayedModifiers != null) {
362 if (delayedModifiers.isEmpty()) {
363 delayedModifiers = new ArrayList<>(2);
365 delayedModifiers.add(Map.entry(phase,action));
367 modifiers.put(phase, action);
374 public String toString() {
375 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
376 + finishedPhase + "]";
379 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
380 final List<SourceException> exceptions = new ArrayList<>();
381 for (final ModifierImpl mod : modifiers.get(identifier)) {
384 } catch (final SourceException e) {
389 switch (exceptions.size()) {
391 return Optional.empty();
393 return Optional.of(exceptions.get(0));
395 final String message = String.format("Yang model processing phase %s failed", identifier);
396 final InferenceException ex = new InferenceException(message, root, exceptions.get(0));
397 exceptions.listIterator(1).forEachRemaining(ex::addSuppressed);
398 return Optional.of(ex);
402 void loadStatements() {
403 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
405 switch (inProgressPhase) {
406 case SOURCE_PRE_LINKAGE:
407 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
410 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
413 case STATEMENT_DEFINITION:
414 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
415 prefixes(), getRootVersion());
417 case FULL_DECLARATION:
418 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
426 private PrefixToModule preLinkagePrefixes() {
427 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
428 final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
429 if (prefixToNamespaceMap == null) {
430 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
434 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
435 return preLinkagePrefixes;
438 private PrefixToModule prefixes() {
439 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
440 ImportPrefixToModuleCtx.class);
441 if (allImports != null) {
442 allImports.forEach((key, value) ->
443 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
446 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
447 BelongsToPrefixToModuleCtx.class);
448 if (allBelongsTo != null) {
449 allBelongsTo.forEach((key, value) ->
450 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
453 return prefixToModuleMap;
456 private QNameToStatementDefinition stmtDef() {
457 // regular YANG statements and extension supports added
458 final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
459 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
460 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
462 // No further actions needed
463 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
464 return qnameToStmtDefMap;
467 // We need to any and all extension statements which have been declared in the context
468 final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
469 StatementDefinitionNamespace.class);
470 if (extensions != null) {
471 extensions.forEach((qname, support) -> {
472 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
473 if (existing != null) {
474 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
476 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
481 return qnameToStmtDefMap;
484 Collection<SourceIdentifier> getRequiredSources() {
485 return root.getRequiredSources();
488 SourceIdentifier getRootIdentifier() {
489 return root.getRootIdentifier();