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.getSupport(key);
83 public Map<QName, StatementSupport<?, ?, ?>> getAllFrom(final NamespaceStorageNode storage) {
88 public void addTo(final NamespaceStorageNode storage, final QName key, final StatementSupport<?, ?, ?> value) {
92 private static UnsupportedOperationException uoe() {
93 return new UnsupportedOperationException("StatementSupportNamespace is immutable");
97 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
99 // TODO: consider keying by Byte equivalent of ExecutionOrder
100 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
101 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
102 private final SupportedStatements statementSupports = new SupportedStatements(qnameToStmtDefMap);
103 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
104 private final @NonNull BuildGlobalContext globalContext;
106 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
107 private StatementStreamSource source;
110 * "imported" namespaces in this source -- this points to RootStatementContexts of
111 * - modules imported via 'import' statement
112 * - parent module, declared via 'belongs-to' statement
114 private List<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
115 private RootStatementContext<?, ?, ?> root;
116 // TODO: consider using ExecutionOrder byte for these two
117 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
118 private ModelProcessingPhase inProgressPhase;
120 // If not null, do not add anything to modifiers, but record it here.
121 private List<Entry<ModelProcessingPhase, ModifierImpl>> delayedModifiers;
123 SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
124 this.globalContext = requireNonNull(globalContext);
125 this.source = requireNonNull(source);
128 @NonNull BuildGlobalContext globalContext() {
129 return globalContext;
132 ModelProcessingPhase getInProgressPhase() {
133 return inProgressPhase;
136 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
137 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
138 StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
140 def = globalContext.getModelDefinedStatementDefinition(name);
142 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.getSupport(name);
143 if (extension != null) {
144 def = new StatementDefinitionContext<>(extension);
145 globalContext.putModelDefinedStatementDefinition(name, def);
148 } else if (current != null) {
149 def = current.definition().overrideDefinition(def);
152 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
153 .getArgumentDefinition().isPresent()) {
154 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
156 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
160 * If the current statement definition has argument specific
161 * sub-definitions, get argument specific sub-definition based on given
162 * argument (e.g. type statement need to be specialized based on its
165 if (def.hasArgumentSpecificSubDefinitions()) {
166 def = def.getSubDefinitionSpecificForArgument(argument);
169 if (current != null) {
170 return current.createSubstatement(childId, def, ref, argument);
174 * If root is null or root version is other than default,
175 * we need to create new root.
178 root = new RootStatementContext<>(this, def, ref, argument);
179 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
180 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
181 root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
182 root.getRootIdentifier());
184 final QName rootStatement = root.definition().getStatementName();
185 final String rootArgument = root.rawArgument();
187 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
188 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
193 RootStatementContext<?, ?, ?> getRoot() {
198 * Return version of root statement context.
200 * @return version of root statement context
202 YangVersion getRootVersion() {
203 return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
206 void startPhase(final ModelProcessingPhase phase) {
207 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
208 verify(Objects.equals(previousPhase, finishedPhase),
209 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
212 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
213 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
214 previousPhase, previousModifiers, source);
216 inProgressPhase = phase;
217 LOG.debug("Source {} started phase {}", source, phase);
220 private void updateImportedNamespaces(final Class<?> type, final Object value) {
221 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
222 verify(value instanceof RootStatementContext, "Unexpected imported value %s", value);
224 if (importedNamespaces.isEmpty()) {
225 importedNamespaces = new ArrayList<>(1);
227 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
232 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
234 // RootStatementContext takes care of IncludedModuleContext and the rest...
235 final V ret = getRoot().putToLocalStorage(type, key, value);
236 // FIXME: what about duplicates?
237 updateImportedNamespaces(type, value);
242 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
244 // RootStatementContext takes care of IncludedModuleContext and the rest...
245 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
247 updateImportedNamespaces(type, value);
253 public StorageNodeType getStorageNodeType() {
254 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
258 public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
259 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
260 if (potentialLocal != null) {
261 return potentialLocal;
264 for (final NamespaceStorageNode importedSource : importedNamespaces) {
265 final V potential = importedSource.getFromLocalStorage(type, key);
266 if (potential != null) {
274 public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
275 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
276 if (potentialLocal != null) {
277 return potentialLocal;
280 for (final NamespaceStorageNode importedSource : importedNamespaces) {
281 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
283 if (potential != null) {
291 @SuppressWarnings("unchecked")
292 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
293 final Class<N> type) {
294 if (StatementSupportNamespace.class.equals(type)) {
295 return (NamespaceBehaviour<K, V, N>) statementSupports;
297 return globalContext.getNamespaceBehaviour(type);
301 public BuildGlobalContext getParentNamespaceStorage() {
302 return globalContext;
305 PhaseCompletionProgress tryToCompletePhase(final byte executionOrder) {
306 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(executionOrder));
307 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
309 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
310 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
311 .tryToCompletePhase(executionOrder);
313 hasProgressed |= tryToProgress(currentPhaseModifiers);
315 // TODO: use executionOrder instead?
316 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
317 finishedPhase = phase;
318 LOG.debug("Source {} finished phase {}", source, phase);
319 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
320 // We have the effective model acquired, which is the final phase of source interaction.
321 LOG.trace("Releasing source {}", source);
324 return PhaseCompletionProgress.FINISHED;
327 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
330 private boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
331 boolean hasProgressed = false;
333 // We are about to iterate over the modifiers and invoke callbacks. Those callbacks can end up circling back
334 // and modifying the same collection. This asserts that modifiers should not be modified.
335 delayedModifiers = List.of();
337 // Try making forward progress ...
338 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
339 while (modifier.hasNext()) {
340 if (modifier.next().tryApply()) {
342 hasProgressed = true;
346 // We have finished iterating, if we have any delayed modifiers, put them back. This may seem as if we want
347 // to retry the loop, but we do not have to, as we will be circling back anyway.
349 // The thing is, we are inherently single-threaded and therefore if we observe non-empty delayedModifiers, the
350 // only way that could happen is through a callback, which in turn means we have made progress.
351 if (!delayedModifiers.isEmpty()) {
352 verify(hasProgressed, "Delayed modifiers encountered without making progress in %s", this);
353 for (Entry<ModelProcessingPhase, ModifierImpl> entry : delayedModifiers) {
354 modifiers.put(entry.getKey(), entry.getValue());
357 delayedModifiers = null;
359 return hasProgressed;
362 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
363 final ModifierImpl action = new ModifierImpl();
365 if (delayedModifiers != null) {
366 if (delayedModifiers.isEmpty()) {
367 delayedModifiers = new ArrayList<>(2);
369 delayedModifiers.add(Map.entry(phase,action));
371 modifiers.put(phase, action);
378 public String toString() {
379 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
380 + finishedPhase + "]";
383 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
384 final List<SourceException> exceptions = new ArrayList<>();
385 for (final ModifierImpl mod : modifiers.get(identifier)) {
388 } catch (final SourceException e) {
393 return switch (exceptions.size()) {
394 case 0 -> Optional.empty();
395 case 1 -> Optional.of(exceptions.get(0));
397 final String message = String.format("Yang model processing phase %s failed", identifier);
398 final InferenceException ex = new InferenceException(message, root, exceptions.get(0));
399 exceptions.listIterator(1).forEachRemaining(ex::addSuppressed);
400 yield Optional.of(ex);
405 void loadStatements() {
406 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
408 switch (inProgressPhase) {
409 case SOURCE_PRE_LINKAGE:
410 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
413 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
416 case STATEMENT_DEFINITION:
417 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
418 prefixes(), getRootVersion());
420 case FULL_DECLARATION:
421 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
429 private PrefixToModule preLinkagePrefixes() {
430 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
431 final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
432 if (prefixToNamespaceMap == null) {
433 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
437 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
438 return preLinkagePrefixes;
441 private PrefixToModule prefixes() {
442 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
443 ImportPrefixToModuleCtx.class);
444 if (allImports != null) {
445 allImports.forEach((key, value) ->
446 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
449 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
450 BelongsToPrefixToModuleCtx.class);
451 if (allBelongsTo != null) {
452 allBelongsTo.forEach((key, value) ->
453 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
456 return prefixToModuleMap;
459 private QNameToStatementDefinition stmtDef() {
460 // regular YANG statements and extension supports added
461 final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
462 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
463 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
465 // No further actions needed
466 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
467 return qnameToStmtDefMap;
470 // We need to any and all extension statements which have been declared in the context
471 final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
472 StatementDefinitionNamespace.class);
473 if (extensions != null) {
474 extensions.forEach((qname, support) -> {
475 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
476 if (existing != null) {
477 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
479 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
484 return qnameToStmtDefMap;
487 Collection<SourceIdentifier> getRequiredSources() {
488 return root.getRequiredSources();
491 SourceIdentifier getRootIdentifier() {
492 return root.getRootIdentifier();