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 com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.HashMultimap;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Multimap;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Objects;
22 import java.util.Optional;
24 import javax.annotation.Nullable;
25 import org.opendaylight.yangtools.concepts.Mutable;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.common.YangVersion;
29 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
47 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
48 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
53 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
54 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
55 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
56 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
57 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
59 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
65 public enum PhaseCompletionProgress {
71 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
73 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
74 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
75 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
76 private final BuildGlobalContext currentContext;
77 private final StatementStreamSource source;
80 * "imported" namespaces in this source -- this points to RootStatementContexts of
81 * - modules imported via 'import' statement
82 * - parent module, declared via 'belongs-to' statement
84 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
85 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
86 private ModelProcessingPhase inProgressPhase;
87 private RootStatementContext<?, ?, ?> root;
89 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
90 this.currentContext = Preconditions.checkNotNull(currentContext);
91 this.source = Preconditions.checkNotNull(source);
94 boolean isEnabledSemanticVersioning() {
95 return currentContext.isEnabledSemanticVersioning();
98 ModelProcessingPhase getInProgressPhase() {
99 return inProgressPhase;
102 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
103 final QName name, final String argument, final StatementSourceReference ref) {
104 if (current != null) {
105 // Fast path: we are entering a statement which was emitted in previous phase
106 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
107 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
108 existing = existing.lookupSubstatement(childId);
110 if (existing != null) {
115 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
117 def = currentContext.getModelDefinedStatementDefinition(name);
119 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
120 if (extension != null) {
121 def = new StatementDefinitionContext<>(extension);
122 currentContext.putModelDefinedStatementDefinition(name, def);
125 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
127 * This code wraps statements encountered inside an extension so
128 * they do not get confused with regular statements.
130 def = Preconditions.checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
131 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
135 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
136 if (def.hasArgument()) {
137 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
139 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
143 * If the current statement definition has argument specific
144 * sub-definitions, get argument specific sub-definition based on given
145 * argument (e.g. type statement need to be specialized based on its
148 if (def.hasArgumentSpecificSubDefinitions()) {
149 def = def.getSubDefinitionSpecificForArgument(argument);
152 if (current != null) {
153 return current.createSubstatement(childId, def, ref, argument);
157 * If root is null or root version is other than default,
158 * we need to create new root.
161 root = new RootStatementContext<>(this, def, ref, argument);
162 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
163 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
164 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
165 root.getRootIdentifier());
167 final QName rootStatement = root.definition().getStatementName();
168 final String rootArgument = root.rawStatementArgument();
170 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
171 && Objects.equals(argument, rootArgument), "Root statement was already defined as '%s %s'.",
172 rootStatement, rootArgument);
177 RootStatementContext<?, ?, ?> getRoot() {
182 * Return version of root statement context.
184 * @return version of root statement context
186 YangVersion getRootVersion() {
187 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
190 DeclaredStatement<?> buildDeclared() {
191 return root.buildDeclared();
194 EffectiveStatement<?, ?> buildEffective() {
195 return root.buildEffective();
198 void startPhase(final ModelProcessingPhase phase) {
199 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
200 Verify.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 Preconditions.checkState(previousModifiers.isEmpty(),
206 "Previous phase %s has unresolved modifiers %s in source %s", 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.verify(value instanceof RootStatementContext);
219 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
224 public <K, V, N extends IdentifierNamespace<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 IdentifierNamespace<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 IdentifierNamespace<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) {
267 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
268 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
269 if (potentialLocal != null) {
270 return potentialLocal;
273 for (final NamespaceStorageNode importedSource : importedNamespaces) {
274 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
276 if (potential != null) {
284 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
285 final Class<N> type) {
286 return currentContext.getNamespaceBehaviour(type);
290 public NamespaceStorageNode getParentNamespaceStorage() {
291 return currentContext;
294 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
295 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
297 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
299 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
300 final boolean phaseCompleted = root.tryToCompletePhase(phase);
302 hasProgressed |= tryToProgress(currentPhaseModifiers);
304 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
305 finishedPhase = phase;
306 LOG.debug("Source {} finished phase {}", source, phase);
307 return PhaseCompletionProgress.FINISHED;
311 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
314 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
315 boolean hasProgressed = false;
317 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
318 while (modifier.hasNext()) {
319 if (modifier.next().tryApply()) {
321 hasProgressed = true;
325 return hasProgressed;
328 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
329 final ModifierImpl action = new ModifierImpl();
330 modifiers.put(phase, action);
335 public String toString() {
336 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
337 + finishedPhase + "]";
340 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
341 final List<SourceException> exceptions = new ArrayList<>();
342 for (final ModifierImpl mod : modifiers.get(identifier)) {
345 } catch (final SourceException e) {
350 if (exceptions.isEmpty()) {
351 return Optional.empty();
354 final String message = String.format("Yang model processing phase %s failed", identifier);
355 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
357 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
359 return Optional.of(e);
362 void loadStatements() throws SourceException {
363 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
365 switch (inProgressPhase) {
366 case SOURCE_PRE_LINKAGE:
367 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
370 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
373 case STATEMENT_DEFINITION:
374 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
375 prefixes(), getRootVersion());
377 case FULL_DECLARATION:
378 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
386 private PrefixToModule preLinkagePrefixes() {
387 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
388 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
389 if (prefixToNamespaceMap == null) {
390 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
394 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
395 return preLinkagePrefixes;
398 private PrefixToModule prefixes() {
399 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
400 ImportPrefixToModuleCtx.class);
401 if (allImports != null) {
402 allImports.forEach((key, value) ->
403 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
406 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
407 BelongsToPrefixToModuleCtx.class);
408 if (allBelongsTo != null) {
409 allBelongsTo.forEach((key, value) ->
410 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
413 return prefixToModuleMap;
416 private QNameToStatementDefinition stmtDef() {
417 // regular YANG statements and extension supports added
418 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
419 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
420 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
422 // No further actions needed
423 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
424 return qnameToStmtDefMap;
427 // We need to any and all extension statements which have been declared in the context
428 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
429 StatementDefinitionNamespace.class);
430 if (extensions != null) {
431 extensions.forEach((qname, support) -> {
432 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
433 if (existing != null) {
434 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
436 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
441 return qnameToStmtDefMap;
444 public Set<YangVersion> getSupportedVersions() {
445 return currentContext.getSupportedVersions();
448 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
449 currentContext.addMutableStmtToSeal(mutableStatement);
452 Collection<SourceIdentifier> getRequiredSources() {
453 return root.getRequiredSources();
456 ModuleIdentifier getRootIdentifier() {
457 return root.getRootIdentifier();