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;
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.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
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 Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
69 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
70 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
71 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
72 private final @NonNull BuildGlobalContext globalContext;
74 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
75 private StatementStreamSource source;
78 * "imported" namespaces in this source -- this points to RootStatementContexts of
79 * - modules imported via 'import' statement
80 * - parent module, declared via 'belongs-to' statement
82 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
83 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
84 private ModelProcessingPhase inProgressPhase;
85 private RootStatementContext<?, ?, ?> root;
87 SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
88 this.globalContext = requireNonNull(globalContext);
89 this.source = requireNonNull(source);
92 @NonNull BuildGlobalContext globalContext() {
96 ModelProcessingPhase getInProgressPhase() {
97 return inProgressPhase;
100 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
101 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
102 StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
104 def = globalContext.getModelDefinedStatementDefinition(name);
106 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
107 if (extension != null) {
108 def = new StatementDefinitionContext<>(extension);
109 globalContext.putModelDefinedStatementDefinition(name, def);
112 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
114 * This code wraps statements encountered inside an extension so
115 * they do not get confused with regular statements.
117 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
118 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
122 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
123 .getArgumentDefinition().isPresent()) {
124 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
126 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
130 * If the current statement definition has argument specific
131 * sub-definitions, get argument specific sub-definition based on given
132 * argument (e.g. type statement need to be specialized based on its
135 if (def.hasArgumentSpecificSubDefinitions()) {
136 def = def.getSubDefinitionSpecificForArgument(argument);
139 if (current != null) {
140 return current.createSubstatement(childId, def, ref, argument);
144 * If root is null or root version is other than default,
145 * we need to create new root.
148 root = new RootStatementContext<>(this, def, ref, argument);
149 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
150 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
151 root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
152 root.getRootIdentifier());
154 final QName rootStatement = root.definition().getStatementName();
155 final String rootArgument = root.rawArgument();
157 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
158 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
163 RootStatementContext<?, ?, ?> getRoot() {
168 * Return version of root statement context.
170 * @return version of root statement context
172 YangVersion getRootVersion() {
173 return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
176 void startPhase(final ModelProcessingPhase phase) {
177 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
178 verify(Objects.equals(previousPhase, finishedPhase),
179 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
182 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
183 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
184 previousPhase, previousModifiers, source);
186 inProgressPhase = phase;
187 LOG.debug("Source {} started phase {}", source, phase);
190 private void updateImportedNamespaces(final Class<?> type, final Object value) {
191 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
192 if (importedNamespaces.isEmpty()) {
193 importedNamespaces = new ArrayList<>(1);
196 verify(value instanceof RootStatementContext);
197 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
202 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
204 // RootStatementContext takes care of IncludedModuleContext and the rest...
205 final V ret = getRoot().putToLocalStorage(type, key, value);
206 // FIXME: what about duplicates?
207 updateImportedNamespaces(type, value);
212 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
214 // RootStatementContext takes care of IncludedModuleContext and the rest...
215 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
217 updateImportedNamespaces(type, value);
223 public StorageNodeType getStorageNodeType() {
224 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
228 public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
229 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
230 if (potentialLocal != null) {
231 return potentialLocal;
234 for (final NamespaceStorageNode importedSource : importedNamespaces) {
235 final V potential = importedSource.getFromLocalStorage(type, key);
236 if (potential != null) {
244 public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
245 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
246 if (potentialLocal != null) {
247 return potentialLocal;
250 for (final NamespaceStorageNode importedSource : importedNamespaces) {
251 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
253 if (potential != null) {
261 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
262 final Class<N> type) {
263 return globalContext.getNamespaceBehaviour(type);
267 public BuildGlobalContext getParentNamespaceStorage() {
268 return globalContext;
271 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
272 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
274 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
275 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
276 .tryToCompletePhase(phase);
278 hasProgressed |= tryToProgress(currentPhaseModifiers);
280 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
281 finishedPhase = phase;
282 LOG.debug("Source {} finished phase {}", source, phase);
283 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
284 // We have the effective model acquired, which is the final phase of source interaction.
285 LOG.trace("Releasing source {}", source);
288 return PhaseCompletionProgress.FINISHED;
291 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
294 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
295 boolean hasProgressed = false;
297 // Try making forward progress ...
298 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
299 while (modifier.hasNext()) {
300 if (modifier.next().tryApply()) {
302 hasProgressed = true;
306 return hasProgressed;
309 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
310 final ModifierImpl action = new ModifierImpl();
311 modifiers.put(phase, action);
316 public String toString() {
317 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
318 + finishedPhase + "]";
321 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
322 final List<SourceException> exceptions = new ArrayList<>();
323 for (final ModifierImpl mod : modifiers.get(identifier)) {
326 } catch (final SourceException e) {
331 if (exceptions.isEmpty()) {
332 return Optional.empty();
335 final String message = String.format("Yang model processing phase %s failed", identifier);
336 final InferenceException e = new InferenceException(message, root, exceptions.get(0));
337 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
339 return Optional.of(e);
342 void loadStatements() {
343 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
345 switch (inProgressPhase) {
346 case SOURCE_PRE_LINKAGE:
347 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
350 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
353 case STATEMENT_DEFINITION:
354 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
355 prefixes(), getRootVersion());
357 case FULL_DECLARATION:
358 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
366 private PrefixToModule preLinkagePrefixes() {
367 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
368 final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
369 if (prefixToNamespaceMap == null) {
370 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
374 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
375 return preLinkagePrefixes;
378 private PrefixToModule prefixes() {
379 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
380 ImportPrefixToModuleCtx.class);
381 if (allImports != null) {
382 allImports.forEach((key, value) ->
383 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
386 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
387 BelongsToPrefixToModuleCtx.class);
388 if (allBelongsTo != null) {
389 allBelongsTo.forEach((key, value) ->
390 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
393 return prefixToModuleMap;
396 private QNameToStatementDefinition stmtDef() {
397 // regular YANG statements and extension supports added
398 final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
399 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
400 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
402 // No further actions needed
403 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
404 return qnameToStmtDefMap;
407 // We need to any and all extension statements which have been declared in the context
408 final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
409 StatementDefinitionNamespace.class);
410 if (extensions != null) {
411 extensions.forEach((qname, support) -> {
412 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
413 if (existing != null) {
414 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
416 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
421 return qnameToStmtDefMap;
424 Collection<SourceIdentifier> getRequiredSources() {
425 return root.getRequiredSources();
428 SourceIdentifier getRootIdentifier() {
429 return root.getRootIdentifier();