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.parser.spi.meta.InferenceException;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
44 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
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.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
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);
72 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
73 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
74 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
75 private final BuildGlobalContext currentContext;
76 private final StatementStreamSource source;
79 * "imported" namespaces in this source -- this points to RootStatementContexts of
80 * - modules imported via 'import' statement
81 * - parent module, declared via 'belongs-to' statement
83 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
84 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
85 private ModelProcessingPhase inProgressPhase;
86 private RootStatementContext<?, ?, ?> root;
88 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
89 this.currentContext = Preconditions.checkNotNull(currentContext);
90 this.source = Preconditions.checkNotNull(source);
93 boolean isEnabledOpenconfigVersioning(){
94 return currentContext.isEnabledOpenconfigVersioning();
97 ModelProcessingPhase getInProgressPhase() {
98 return inProgressPhase;
101 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
102 final QName name, final String argument, final StatementSourceReference ref) {
103 if (current != null) {
104 // Fast path: we are entering a statement which was emitted in previous phase
105 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
106 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
107 existing = existing.lookupSubstatement(childId);
109 if (existing != null) {
114 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
116 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
117 if (extension != null) {
118 def = new StatementDefinitionContext<>(extension);
120 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
122 * This code wraps statements encountered inside an extension so they do not get confused with regular
125 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
126 * this work. We really should be peeking into the extension definition to find these nodes,
127 * as otherwise we are not reusing definitions nor support for these nodes.
129 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
130 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
131 new ModelDefinedStatementDefinition(qName, argument != null)));
134 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
135 if (def.hasArgument()) {
136 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
138 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
142 * If the current statement definition has argument specific
143 * sub-definitions, get argument specific sub-definition based on given
144 * argument (e.g. type statement need to be specialized based on its
147 if (def.hasArgumentSpecificSubDefinitions()) {
148 def = def.getSubDefinitionSpecificForArgument(argument);
151 if (current != null) {
152 return current.createSubstatement(childId, def, ref, argument);
156 * If root is null or root version is other than default,
157 * we need to create new root.
160 root = new RootStatementContext<>(this, def, ref, argument);
161 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
162 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
163 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(), root.getRootIdentifier());
165 final QName rootStatement = root.definition().getStatementName();
166 final String rootArgument = root.rawStatementArgument();
168 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
169 && Objects.equals(argument, rootArgument),
170 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
175 RootStatementContext<?, ?, ?> getRoot() {
180 * Return version of root statement context.
182 * @return version of root statement context
184 YangVersion getRootVersion() {
185 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
188 DeclaredStatement<?> buildDeclared() {
189 return root.buildDeclared();
192 EffectiveStatement<?, ?> buildEffective() {
193 return root.buildEffective();
196 void startPhase(final ModelProcessingPhase phase) {
197 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
198 Verify.verify(Objects.equals(previousPhase, finishedPhase),
199 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
202 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
203 Preconditions.checkState(previousModifiers.isEmpty(),
204 "Previous phase %s has unresolved modifiers %s in source %s",
205 previousPhase, previousModifiers, source);
207 inProgressPhase = phase;
208 LOG.debug("Source {} started phase {}", source, phase);
211 private void updateImportedNamespaces(final Class<?> type, final Object value) {
212 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
213 if (importedNamespaces.isEmpty()) {
214 importedNamespaces = new ArrayList<>(1);
217 Verify.verify(value instanceof RootStatementContext);
218 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
223 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
225 // RootStatementContext takes care of IncludedModuleContext and the rest...
226 final V ret = getRoot().putToLocalStorage(type, key, value);
227 // FIXME: what about duplicates?
228 updateImportedNamespaces(type, value);
233 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
235 // RootStatementContext takes care of IncludedModuleContext and the rest...
236 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
238 updateImportedNamespaces(type, value);
244 public StorageNodeType getStorageNodeType() {
245 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
249 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
250 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
251 if (potentialLocal != null) {
252 return potentialLocal;
255 for (final NamespaceStorageNode importedSource : importedNamespaces) {
256 final V potential = importedSource.getFromLocalStorage(type, key);
257 if (potential != null) {
266 public <K, V, N extends IdentifierNamespace<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 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
284 final Class<N> type) {
285 return currentContext.getNamespaceBehaviour(type);
289 public NamespaceStorageNode getParentNamespaceStorage() {
290 return currentContext;
293 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
294 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
296 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
298 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
299 final boolean phaseCompleted = root.tryToCompletePhase(phase);
301 hasProgressed |= tryToProgress(currentPhaseModifiers);
303 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
304 finishedPhase = phase;
305 LOG.debug("Source {} finished phase {}", source, phase);
306 return PhaseCompletionProgress.FINISHED;
310 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
313 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
314 boolean hasProgressed = false;
316 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
317 while (modifier.hasNext()) {
318 if (modifier.next().tryApply()) {
320 hasProgressed = true;
324 return hasProgressed;
327 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
328 final ModifierImpl action = new ModifierImpl(phase);
329 modifiers.put(phase, action);
334 public String toString() {
335 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
336 + finishedPhase + "]";
339 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
340 final List<SourceException> exceptions = new ArrayList<>();
341 for (final ModifierImpl mod : modifiers.get(identifier)) {
344 } catch (final SourceException e) {
349 if (exceptions.isEmpty()) {
350 return Optional.empty();
353 final String message = String.format("Yang model processing phase %s failed", identifier);
354 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
356 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
358 return Optional.of(e);
361 void loadStatements() throws SourceException {
362 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
364 switch (inProgressPhase) {
365 case SOURCE_PRE_LINKAGE:
366 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
369 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(), getRootVersion());
371 case STATEMENT_DEFINITION:
372 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
374 case FULL_DECLARATION:
375 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
382 private PrefixToModule preLinkagePrefixes() {
383 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
384 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
385 if (prefixToNamespaceMap == null) {
386 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
390 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
391 return preLinkagePrefixes;
394 private PrefixToModule prefixes() {
395 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
397 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
398 (BelongsToPrefixToModuleIdentifier.class);
399 if (belongsToPrefixes != null) {
400 allPrefixes.putAll(belongsToPrefixes);
403 allPrefixes.forEach((key, value) ->
404 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
406 return prefixToModuleMap;
409 private QNameToStatementDefinition stmtDef() {
410 // regular YANG statements and extension supports added
411 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
412 qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
413 qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
415 // No further actions needed
416 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
417 return qNameToStmtDefMap;
420 // We need to any and all extension statements which have been declared in the context
421 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
422 StatementDefinitionNamespace.class);
423 if (extensions != null) {
424 extensions.forEach((qname, support) -> {
425 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
426 if (existing != null) {
427 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
429 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
434 return qNameToStmtDefMap;
437 public Set<YangVersion> getSupportedVersions() {
438 return currentContext.getSupportedVersions();
441 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
442 currentContext.addMutableStmtToSeal(mutableStatement);
445 Collection<ModuleIdentifier> getRequiredModules() {
446 return root.getRequiredModules();
449 ModuleIdentifier getRootIdentifier() {
450 return root.getRootIdentifier();