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.Objects;
24 import java.util.Optional;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.yangtools.concepts.Mutable;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.QNameModule;
29 import org.opendaylight.yangtools.yang.common.XMLNamespace;
30 import org.opendaylight.yangtools.yang.common.YangVersion;
31 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
50 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
51 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
52 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
53 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
56 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
61 enum PhaseCompletionProgress {
67 private static final class SupportedStatements
68 extends NamespaceBehaviour<QName, StatementSupport<?, ?, ?>, StatementSupportNamespace> {
69 private final QNameToStatementDefinitionMap statementDefinitions;
71 SupportedStatements(final QNameToStatementDefinitionMap statementDefinitions) {
72 super(StatementSupportNamespace.class);
73 this.statementDefinitions = requireNonNull(statementDefinitions);
77 public StatementSupport<?, ?, ?> getFrom(final NamespaceStorageNode storage, final QName key) {
78 return statementDefinitions.get(key);
82 public Map<QName, StatementSupport<?, ?, ?>> getAllFrom(final NamespaceStorageNode storage) {
83 throw new UnsupportedOperationException("StatementSupportNamespace is immutable");
87 public void addTo(final NamespaceStorageNode storage, final QName key, final StatementSupport<?, ?, ?> value) {
88 throw new UnsupportedOperationException("StatementSupportNamespace is immutable");
92 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
94 // TODO: consider keying by Byte equivalent of ExecutionOrder
95 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
96 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
97 private final SupportedStatements statementSupports = new SupportedStatements(qnameToStmtDefMap);
98 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
99 private final @NonNull BuildGlobalContext globalContext;
101 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
102 private StatementStreamSource source;
105 * "imported" namespaces in this source -- this points to RootStatementContexts of
106 * - modules imported via 'import' statement
107 * - parent module, declared via 'belongs-to' statement
109 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
110 private RootStatementContext<?, ?, ?> root;
111 // TODO: consider using ExecutionOrder byte for these two
112 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
113 private ModelProcessingPhase inProgressPhase;
115 SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
116 this.globalContext = requireNonNull(globalContext);
117 this.source = requireNonNull(source);
120 @NonNull BuildGlobalContext globalContext() {
121 return globalContext;
124 ModelProcessingPhase getInProgressPhase() {
125 return inProgressPhase;
128 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
129 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
130 StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
132 def = globalContext.getModelDefinedStatementDefinition(name);
134 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
135 if (extension != null) {
136 def = new StatementDefinitionContext<>(extension);
137 globalContext.putModelDefinedStatementDefinition(name, def);
140 } else if (current != null) {
141 def = current.definition().overrideDefinition(def);
144 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
145 .getArgumentDefinition().isPresent()) {
146 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
148 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
152 * If the current statement definition has argument specific
153 * sub-definitions, get argument specific sub-definition based on given
154 * argument (e.g. type statement need to be specialized based on its
157 if (def.hasArgumentSpecificSubDefinitions()) {
158 def = def.getSubDefinitionSpecificForArgument(argument);
161 if (current != null) {
162 return current.createSubstatement(childId, def, ref, argument);
166 * If root is null or root version is other than default,
167 * we need to create new root.
170 root = new RootStatementContext<>(this, def, ref, argument);
171 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
172 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
173 root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
174 root.getRootIdentifier());
176 final QName rootStatement = root.definition().getStatementName();
177 final String rootArgument = root.rawArgument();
179 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
180 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
185 RootStatementContext<?, ?, ?> getRoot() {
190 * Return version of root statement context.
192 * @return version of root statement context
194 YangVersion getRootVersion() {
195 return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
198 void startPhase(final ModelProcessingPhase phase) {
199 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
200 verify(Objects.equals(previousPhase, finishedPhase),
201 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
204 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
205 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
206 previousPhase, previousModifiers, source);
208 inProgressPhase = phase;
209 LOG.debug("Source {} started phase {}", source, phase);
212 private void updateImportedNamespaces(final Class<?> type, final Object value) {
213 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
214 if (importedNamespaces.isEmpty()) {
215 importedNamespaces = new ArrayList<>(1);
218 verify(value instanceof RootStatementContext);
219 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
224 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
226 // RootStatementContext takes care of IncludedModuleContext and the rest...
227 final V ret = getRoot().putToLocalStorage(type, key, value);
228 // FIXME: what about duplicates?
229 updateImportedNamespaces(type, value);
234 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
236 // RootStatementContext takes care of IncludedModuleContext and the rest...
237 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
239 updateImportedNamespaces(type, value);
245 public StorageNodeType getStorageNodeType() {
246 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
250 public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
251 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
252 if (potentialLocal != null) {
253 return potentialLocal;
256 for (final NamespaceStorageNode importedSource : importedNamespaces) {
257 final V potential = importedSource.getFromLocalStorage(type, key);
258 if (potential != null) {
266 public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
267 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
268 if (potentialLocal != null) {
269 return potentialLocal;
272 for (final NamespaceStorageNode importedSource : importedNamespaces) {
273 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
275 if (potential != null) {
283 @SuppressWarnings("unchecked")
284 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
285 final Class<N> type) {
286 if (StatementSupportNamespace.class.equals(type)) {
287 return (NamespaceBehaviour<K, V, N>) statementSupports;
289 return globalContext.getNamespaceBehaviour(type);
293 public BuildGlobalContext getParentNamespaceStorage() {
294 return globalContext;
297 PhaseCompletionProgress tryToCompletePhase(final byte executionOrder) {
298 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(executionOrder));
299 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
301 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
302 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
303 .tryToCompletePhase(executionOrder);
305 hasProgressed |= tryToProgress(currentPhaseModifiers);
307 // TODO: use executionOrder instead?
308 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
309 finishedPhase = phase;
310 LOG.debug("Source {} finished phase {}", source, phase);
311 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
312 // We have the effective model acquired, which is the final phase of source interaction.
313 LOG.trace("Releasing source {}", source);
316 return PhaseCompletionProgress.FINISHED;
319 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
322 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
323 boolean hasProgressed = false;
325 // Try making forward progress ...
326 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
327 while (modifier.hasNext()) {
328 if (modifier.next().tryApply()) {
330 hasProgressed = true;
334 return hasProgressed;
337 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
338 final ModifierImpl action = new ModifierImpl();
339 modifiers.put(phase, action);
344 public String toString() {
345 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
346 + finishedPhase + "]";
349 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
350 final List<SourceException> exceptions = new ArrayList<>();
351 for (final ModifierImpl mod : modifiers.get(identifier)) {
354 } catch (final SourceException e) {
359 if (exceptions.isEmpty()) {
360 return Optional.empty();
363 final String message = String.format("Yang model processing phase %s failed", identifier);
364 final InferenceException e = new InferenceException(message, root, exceptions.get(0));
365 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
367 return Optional.of(e);
370 void loadStatements() {
371 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
373 switch (inProgressPhase) {
374 case SOURCE_PRE_LINKAGE:
375 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
378 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
381 case STATEMENT_DEFINITION:
382 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
383 prefixes(), getRootVersion());
385 case FULL_DECLARATION:
386 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
394 private PrefixToModule preLinkagePrefixes() {
395 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
396 final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
397 if (prefixToNamespaceMap == null) {
398 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
402 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
403 return preLinkagePrefixes;
406 private PrefixToModule prefixes() {
407 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
408 ImportPrefixToModuleCtx.class);
409 if (allImports != null) {
410 allImports.forEach((key, value) ->
411 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
414 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
415 BelongsToPrefixToModuleCtx.class);
416 if (allBelongsTo != null) {
417 allBelongsTo.forEach((key, value) ->
418 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
421 return prefixToModuleMap;
424 private QNameToStatementDefinition stmtDef() {
425 // regular YANG statements and extension supports added
426 final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
427 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
428 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
430 // No further actions needed
431 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
432 return qnameToStmtDefMap;
435 // We need to any and all extension statements which have been declared in the context
436 final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
437 StatementDefinitionNamespace.class);
438 if (extensions != null) {
439 extensions.forEach((qname, support) -> {
440 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
441 if (existing != null) {
442 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
444 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
449 return qnameToStmtDefMap;
452 Collection<SourceIdentifier> getRequiredSources() {
453 return root.getRequiredSources();
456 SourceIdentifier getRootIdentifier() {
457 return root.getRootIdentifier();