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 javax.annotation.Nullable;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.yangtools.concepts.Mutable;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.common.YangVersion;
33 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
36 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
37 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
50 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
51 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
56 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
57 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
58 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
59 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
62 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
68 public enum PhaseCompletionProgress {
74 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
76 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
77 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
78 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
79 private final BuildGlobalContext currentContext;
80 private final StatementStreamSource source;
83 * "imported" namespaces in this source -- this points to RootStatementContexts of
84 * - modules imported via 'import' statement
85 * - parent module, declared via 'belongs-to' statement
87 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
88 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
89 private ModelProcessingPhase inProgressPhase;
90 private RootStatementContext<?, ?, ?> root;
92 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
93 this.currentContext = requireNonNull(currentContext);
94 this.source = requireNonNull(source);
97 boolean isEnabledSemanticVersioning() {
98 return currentContext.isEnabledSemanticVersioning();
101 ModelProcessingPhase getInProgressPhase() {
102 return inProgressPhase;
105 Optional<StatementContextBase<?, ?, ?>> lookupDeclaredChild(final StatementContextBase<?, ?, ?> current,
107 if (current == null) {
108 return Optional.empty();
111 // Fast path: we are entering a statement which was emitted in previous phase
112 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
113 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
114 existing = existing.lookupSubstatement(childId);
117 return Optional.ofNullable(existing);
120 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
121 final QName name, final String argument, final StatementSourceReference ref) {
122 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
124 def = currentContext.getModelDefinedStatementDefinition(name);
126 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
127 if (extension != null) {
128 def = new StatementDefinitionContext<>(extension);
129 currentContext.putModelDefinedStatementDefinition(name, def);
132 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
134 * This code wraps statements encountered inside an extension so
135 * they do not get confused with regular statements.
137 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
138 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
142 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
143 if (def.hasArgument()) {
144 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
146 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
150 * If the current statement definition has argument specific
151 * sub-definitions, get argument specific sub-definition based on given
152 * argument (e.g. type statement need to be specialized based on its
155 if (def.hasArgumentSpecificSubDefinitions()) {
156 def = def.getSubDefinitionSpecificForArgument(argument);
159 if (current != null) {
160 return current.createSubstatement(childId, def, ref, argument);
164 * If root is null or root version is other than default,
165 * we need to create new root.
168 root = new RootStatementContext<>(this, def, ref, argument);
169 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
170 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
171 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
172 root.getRootIdentifier());
174 final QName rootStatement = root.definition().getStatementName();
175 final String rootArgument = root.rawStatementArgument();
177 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
178 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
183 RootStatementContext<?, ?, ?> getRoot() {
188 * Return version of root statement context.
190 * @return version of root statement context
192 YangVersion getRootVersion() {
193 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
196 DeclaredStatement<?> buildDeclared() {
197 return root.buildDeclared();
200 EffectiveStatement<?, ?> buildEffective() {
201 return root.buildEffective();
204 void startPhase(final ModelProcessingPhase phase) {
205 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
206 verify(Objects.equals(previousPhase, finishedPhase),
207 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
210 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
211 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
212 previousPhase, previousModifiers, source);
214 inProgressPhase = phase;
215 LOG.debug("Source {} started phase {}", source, phase);
218 private void updateImportedNamespaces(final Class<?> type, final Object value) {
219 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
220 if (importedNamespaces.isEmpty()) {
221 importedNamespaces = new ArrayList<>(1);
224 verify(value instanceof RootStatementContext);
225 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
230 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
232 // RootStatementContext takes care of IncludedModuleContext and the rest...
233 final V ret = getRoot().putToLocalStorage(type, key, value);
234 // FIXME: what about duplicates?
235 updateImportedNamespaces(type, value);
240 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
242 // RootStatementContext takes care of IncludedModuleContext and the rest...
243 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
245 updateImportedNamespaces(type, value);
251 public StorageNodeType getStorageNodeType() {
252 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
256 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
257 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
258 if (potentialLocal != null) {
259 return potentialLocal;
262 for (final NamespaceStorageNode importedSource : importedNamespaces) {
263 final V potential = importedSource.getFromLocalStorage(type, key);
264 if (potential != null) {
273 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
274 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
275 if (potentialLocal != null) {
276 return potentialLocal;
279 for (final NamespaceStorageNode importedSource : importedNamespaces) {
280 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
282 if (potential != null) {
290 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
291 final Class<N> type) {
292 return currentContext.getNamespaceBehaviour(type);
296 public NamespaceStorageNode getParentNamespaceStorage() {
297 return currentContext;
300 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
301 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
303 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
305 checkNotNull(this.root, "Malformed source. Valid root element is missing.");
306 final boolean phaseCompleted = root.tryToCompletePhase(phase);
308 hasProgressed |= tryToProgress(currentPhaseModifiers);
310 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
311 finishedPhase = phase;
312 LOG.debug("Source {} finished phase {}", source, phase);
313 return PhaseCompletionProgress.FINISHED;
317 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
320 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
321 boolean hasProgressed = false;
323 // Try making forward progress ...
324 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
325 while (modifier.hasNext()) {
326 if (modifier.next().tryApply()) {
328 hasProgressed = true;
332 return hasProgressed;
335 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
336 final ModifierImpl action = new ModifierImpl();
337 modifiers.put(phase, action);
342 public String toString() {
343 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
344 + finishedPhase + "]";
347 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
348 final List<SourceException> exceptions = new ArrayList<>();
349 for (final ModifierImpl mod : modifiers.get(identifier)) {
352 } catch (final SourceException e) {
357 if (exceptions.isEmpty()) {
358 return Optional.empty();
361 final String message = String.format("Yang model processing phase %s failed", identifier);
362 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
364 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
366 return Optional.of(e);
369 void loadStatements() {
370 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
372 switch (inProgressPhase) {
373 case SOURCE_PRE_LINKAGE:
374 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
377 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
380 case STATEMENT_DEFINITION:
381 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
382 prefixes(), getRootVersion());
384 case FULL_DECLARATION:
385 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
393 private PrefixToModule preLinkagePrefixes() {
394 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
395 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
396 if (prefixToNamespaceMap == null) {
397 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
401 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
402 return preLinkagePrefixes;
405 private PrefixToModule prefixes() {
406 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
407 ImportPrefixToModuleCtx.class);
408 if (allImports != null) {
409 allImports.forEach((key, value) ->
410 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
413 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
414 BelongsToPrefixToModuleCtx.class);
415 if (allBelongsTo != null) {
416 allBelongsTo.forEach((key, value) ->
417 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
420 return prefixToModuleMap;
423 private QNameToStatementDefinition stmtDef() {
424 // regular YANG statements and extension supports added
425 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
426 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
427 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
429 // No further actions needed
430 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
431 return qnameToStmtDefMap;
434 // We need to any and all extension statements which have been declared in the context
435 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
436 StatementDefinitionNamespace.class);
437 if (extensions != null) {
438 extensions.forEach((qname, support) -> {
439 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
440 if (existing != null) {
441 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
443 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
448 return qnameToStmtDefMap;
451 public Set<YangVersion> getSupportedVersions() {
452 return currentContext.getSupportedVersions();
455 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
456 currentContext.addMutableStmtToSeal(mutableStatement);
459 Collection<SourceIdentifier> getRequiredSources() {
460 return root.getRequiredSources();
463 SourceIdentifier getRootIdentifier() {
464 return root.getRootIdentifier();