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;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.Objects;
25 import java.util.Optional;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.opendaylight.yangtools.concepts.Mutable;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.QNameModule;
31 import org.opendaylight.yangtools.yang.common.YangVersion;
32 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
35 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
49 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
55 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
56 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
57 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
58 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
67 public enum PhaseCompletionProgress {
73 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
75 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
76 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
77 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
78 private final BuildGlobalContext currentContext;
79 private final StatementStreamSource source;
82 * "imported" namespaces in this source -- this points to RootStatementContexts of
83 * - modules imported via 'import' statement
84 * - parent module, declared via 'belongs-to' statement
86 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
87 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
88 private ModelProcessingPhase inProgressPhase;
89 private RootStatementContext<?, ?, ?> root;
91 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
92 this.currentContext = requireNonNull(currentContext);
93 this.source = requireNonNull(source);
96 boolean isEnabledSemanticVersioning() {
97 return currentContext.isEnabledSemanticVersioning();
100 ModelProcessingPhase getInProgressPhase() {
101 return inProgressPhase;
104 Optional<StatementContextBase<?, ?, ?>> lookupDeclaredChild(final StatementContextBase<?, ?, ?> current,
106 if (current == null) {
107 return Optional.empty();
110 // Fast path: we are entering a statement which was emitted in previous phase
111 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
112 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
113 existing = existing.lookupSubstatement(childId);
116 return Optional.ofNullable(existing);
119 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
120 final QName name, final String argument, final StatementSourceReference ref) {
121 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
123 def = currentContext.getModelDefinedStatementDefinition(name);
125 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
126 if (extension != null) {
127 def = new StatementDefinitionContext<>(extension);
128 currentContext.putModelDefinedStatementDefinition(name, def);
131 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
133 * This code wraps statements encountered inside an extension so
134 * they do not get confused with regular statements.
136 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
137 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
141 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
143 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
145 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
149 * If the current statement definition has argument specific
150 * sub-definitions, get argument specific sub-definition based on given
151 * argument (e.g. type statement need to be specialized based on its
154 if (def.hasArgumentSpecificSubDefinitions()) {
155 def = def.getSubDefinitionSpecificForArgument(argument);
158 if (current != null) {
159 return current.createSubstatement(childId, def, ref, argument);
163 * If root is null or root version is other than default,
164 * we need to create new root.
167 root = new RootStatementContext<>(this, def, ref, argument);
168 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
169 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
170 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
171 root.getRootIdentifier());
173 final QName rootStatement = root.definition().getStatementName();
174 final String rootArgument = root.rawStatementArgument();
176 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
177 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
182 RootStatementContext<?, ?, ?> getRoot() {
187 * Return version of root statement context.
189 * @return version of root statement context
191 YangVersion getRootVersion() {
192 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
195 DeclaredStatement<?> buildDeclared() {
196 return root.buildDeclared();
199 EffectiveStatement<?, ?> buildEffective() {
200 return root.buildEffective();
203 void startPhase(final ModelProcessingPhase phase) {
204 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
205 verify(Objects.equals(previousPhase, finishedPhase),
206 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
209 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
210 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
211 previousPhase, previousModifiers, source);
213 inProgressPhase = phase;
214 LOG.debug("Source {} started phase {}", source, phase);
217 private void updateImportedNamespaces(final Class<?> type, final Object value) {
218 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
219 if (importedNamespaces.isEmpty()) {
220 importedNamespaces = new ArrayList<>(1);
223 verify(value instanceof RootStatementContext);
224 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
229 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
231 // RootStatementContext takes care of IncludedModuleContext and the rest...
232 final V ret = getRoot().putToLocalStorage(type, key, value);
233 // FIXME: what about duplicates?
234 updateImportedNamespaces(type, value);
239 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
241 // RootStatementContext takes care of IncludedModuleContext and the rest...
242 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
244 updateImportedNamespaces(type, value);
250 public StorageNodeType getStorageNodeType() {
251 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
255 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
256 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
257 if (potentialLocal != null) {
258 return potentialLocal;
261 for (final NamespaceStorageNode importedSource : importedNamespaces) {
262 final V potential = importedSource.getFromLocalStorage(type, key);
263 if (potential != null) {
271 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
272 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
273 if (potentialLocal != null) {
274 return potentialLocal;
277 for (final NamespaceStorageNode importedSource : importedNamespaces) {
278 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
280 if (potential != null) {
288 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
289 final Class<N> type) {
290 return currentContext.getNamespaceBehaviour(type);
294 public NamespaceStorageNode getParentNamespaceStorage() {
295 return currentContext;
298 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
299 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
301 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
303 checkNotNull(this.root, "Malformed source. Valid root element is missing.");
304 final boolean phaseCompleted = root.tryToCompletePhase(phase);
306 hasProgressed |= tryToProgress(currentPhaseModifiers);
308 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
309 finishedPhase = phase;
310 LOG.debug("Source {} finished phase {}", source, phase);
311 return PhaseCompletionProgress.FINISHED;
315 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
318 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
319 boolean hasProgressed = false;
321 // Try making forward progress ...
322 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
323 while (modifier.hasNext()) {
324 if (modifier.next().tryApply()) {
326 hasProgressed = true;
330 return hasProgressed;
333 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
334 final ModifierImpl action = new ModifierImpl();
335 modifiers.put(phase, action);
340 public String toString() {
341 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
342 + finishedPhase + "]";
345 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
346 final List<SourceException> exceptions = new ArrayList<>();
347 for (final ModifierImpl mod : modifiers.get(identifier)) {
350 } catch (final SourceException e) {
355 if (exceptions.isEmpty()) {
356 return Optional.empty();
359 final String message = String.format("Yang model processing phase %s failed", identifier);
360 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
362 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
364 return Optional.of(e);
367 void loadStatements() {
368 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
370 switch (inProgressPhase) {
371 case SOURCE_PRE_LINKAGE:
372 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
375 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
378 case STATEMENT_DEFINITION:
379 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
380 prefixes(), getRootVersion());
382 case FULL_DECLARATION:
383 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
391 private PrefixToModule preLinkagePrefixes() {
392 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
393 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
394 if (prefixToNamespaceMap == null) {
395 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
399 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
400 return preLinkagePrefixes;
403 private PrefixToModule prefixes() {
404 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
405 ImportPrefixToModuleCtx.class);
406 if (allImports != null) {
407 allImports.forEach((key, value) ->
408 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
411 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
412 BelongsToPrefixToModuleCtx.class);
413 if (allBelongsTo != null) {
414 allBelongsTo.forEach((key, value) ->
415 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
418 return prefixToModuleMap;
421 private QNameToStatementDefinition stmtDef() {
422 // regular YANG statements and extension supports added
423 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
424 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
425 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
427 // No further actions needed
428 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
429 return qnameToStmtDefMap;
432 // We need to any and all extension statements which have been declared in the context
433 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
434 StatementDefinitionNamespace.class);
435 if (extensions != null) {
436 extensions.forEach((qname, support) -> {
437 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
438 if (existing != null) {
439 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
441 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
446 return qnameToStmtDefMap;
449 public Set<YangVersion> getSupportedVersions() {
450 return currentContext.getSupportedVersions();
453 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
454 currentContext.addMutableStmtToSeal(mutableStatement);
457 Collection<SourceIdentifier> getRequiredSources() {
458 return root.getRequiredSources();
461 SourceIdentifier getRootIdentifier() {
462 return root.getRootIdentifier();