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.ImmutableTable;
15 import com.google.common.collect.Multimap;
16 import com.google.common.collect.Table;
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;
26 import javax.annotation.Nullable;
27 import org.opendaylight.yangtools.concepts.Mutable;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.YangConstants;
31 import org.opendaylight.yangtools.yang.common.YangVersion;
32 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
34 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
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.NamespaceBehaviour;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
46 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
47 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
52 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
53 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
54 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
55 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
56 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
64 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
65 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
66 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
67 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
68 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
69 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
70 import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.LeafrefSpecificationRfc7950Support;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
74 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
76 public enum PhaseCompletionProgress {
82 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
83 private static final Table<YangVersion, String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
84 ImmutableTable.<YangVersion, String, StatementSupport<?, ?, ?>>builder()
85 .put(YangVersion.VERSION_1, TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
86 .put(YangVersion.VERSION_1, TypeUtils.UNION, new UnionSpecificationImpl.Definition())
87 .put(YangVersion.VERSION_1, TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
88 .put(YangVersion.VERSION_1, TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
89 .put(YangVersion.VERSION_1_1, TypeUtils.LEAF_REF, new LeafrefSpecificationRfc7950Support())
90 .put(YangVersion.VERSION_1, TypeUtils.BITS, new BitsSpecificationImpl.Definition())
91 .put(YangVersion.VERSION_1, TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
92 .put(YangVersion.VERSION_1, TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
95 private static final QName TYPE = YangStmtMapping.TYPE.getStatementName();
97 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
98 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
99 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
100 private final BuildGlobalContext currentContext;
101 private final StatementStreamSource source;
104 * "imported" namespaces in this source -- this points to RootStatementContexts of
105 * - modules imported via 'import' statement
106 * - parent module, declared via 'belongs-to' statement
108 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
109 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
110 private ModelProcessingPhase inProgressPhase;
111 private RootStatementContext<?, ?, ?> root;
113 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
114 this.currentContext = Preconditions.checkNotNull(currentContext);
115 this.source = Preconditions.checkNotNull(source);
118 boolean isEnabledSemanticVersioning(){
119 return currentContext.isEnabledSemanticVersioning();
122 ModelProcessingPhase getInProgressPhase() {
123 return inProgressPhase;
126 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
127 QName name, final String argument, final StatementSourceReference ref) {
128 if (current != null) {
129 // Fast path: we are entering a statement which was emitted in previous phase
130 final StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
131 if (existing != null) {
136 // FIXME: BUG-7038: Refactor/clean up this special case
137 if (TYPE.equals(name)) {
138 SourceException.throwIfNull(argument, ref, "Type statement requires an argument");
139 if (TypeUtils.isYangTypeBodyStmtString(argument)) {
140 name = QName.create(YangConstants.RFC6020_YIN_MODULE, argument);
142 name = QName.create(YangConstants.RFC6020_YIN_MODULE, TYPE.getLocalName());
146 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
148 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
149 if (extension != null) {
150 def = new StatementDefinitionContext<>(extension);
153 def = resolveTypeBodyStmts(name.getLocalName(), getRootVersion());
155 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
157 * This code wraps statements encountered inside an extension so they do not get confused with regular
160 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
161 * this work. We really should be peeking into the extension definition to find these nodes,
162 * as otherwise we are not reusing definitions nor support for these nodes.
164 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
165 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
166 new ModelDefinedStatementDefinition(qName, argument != null)));
169 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
170 if (def.hasArgument()) {
171 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
173 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
176 if (current != null) {
177 return current.createSubstatement(childId, def, ref, argument);
181 * If root is null or root version is other than default,
182 * we need to create new root.
185 root = new RootStatementContext<>(this, def, ref, argument);
186 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
187 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
188 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion());
190 final QName rootStatement = root.definition().getStatementName();
191 final String rootArgument = root.rawStatementArgument();
193 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
194 && Objects.equals(argument, rootArgument),
195 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
200 RootStatementContext<?, ?, ?> getRoot() {
205 * Return version of root statement context.
207 * @return version of root statement context
209 YangVersion getRootVersion() {
210 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
213 DeclaredStatement<?> buildDeclared() {
214 return root.buildDeclared();
217 EffectiveStatement<?, ?> buildEffective() {
218 return root.buildEffective();
221 void startPhase(final ModelProcessingPhase phase) {
222 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
223 Verify.verify(Objects.equals(previousPhase, finishedPhase),
224 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
227 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
228 Preconditions.checkState(previousModifiers.isEmpty(),
229 "Previous phase %s has unresolved modifiers %s in source %s",
230 previousPhase, previousModifiers, source);
232 inProgressPhase = phase;
233 LOG.debug("Source {} started phase {}", source, phase);
237 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
240 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
241 if (importedNamespaces.isEmpty()) {
242 importedNamespaces = new ArrayList<>(1);
245 Verify.verify(value instanceof RootStatementContext);
246 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
249 // RootStatementContext takes care of IncludedModuleContext and the rest...
250 getRoot().addToLocalStorage(type, key, value);
254 public StorageNodeType getStorageNodeType() {
255 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
259 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
260 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
261 if (potentialLocal != null) {
262 return potentialLocal;
265 for (final NamespaceStorageNode importedSource : importedNamespaces) {
266 final V potential = importedSource.getFromLocalStorage(type, key);
267 if (potential != null) {
276 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
277 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
278 if (potentialLocal != null) {
279 return potentialLocal;
282 for (final NamespaceStorageNode importedSource : importedNamespaces) {
283 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
285 if (potential != null) {
293 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
294 final Class<N> type) {
295 return currentContext.getNamespaceBehaviour(type);
299 public NamespaceStorageNode getParentNamespaceStorage() {
300 return currentContext;
303 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
304 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
306 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
308 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
309 final boolean phaseCompleted = root.tryToCompletePhase(phase);
311 hasProgressed |= tryToProgress(currentPhaseModifiers);
313 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
314 finishedPhase = phase;
315 LOG.debug("Source {} finished phase {}", source, phase);
316 return PhaseCompletionProgress.FINISHED;
320 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
323 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
324 boolean hasProgressed = false;
326 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
327 while (modifier.hasNext()) {
328 if (modifier.next().tryApply()) {
330 hasProgressed = true;
334 return hasProgressed;
337 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
338 final ModifierImpl action = new ModifierImpl(phase);
339 modifiers.put(phase, action);
344 public String toString() {
345 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
346 + finishedPhase + "]";
349 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
350 final List<SourceException> exceptions = new ArrayList<>();
351 for (final ModifierImpl mod : modifiers.get(identifier)) {
354 } catch (final SourceException e) {
359 if (exceptions.isEmpty()) {
360 return Optional.empty();
363 final String message = String.format("Yang model processing phase %s failed", identifier);
364 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
366 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
368 return Optional.of(e);
371 void loadStatements() throws SourceException {
372 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
374 switch (inProgressPhase) {
375 case SOURCE_PRE_LINKAGE:
376 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
379 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
381 case STATEMENT_DEFINITION:
382 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
384 case FULL_DECLARATION:
385 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
392 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument,
393 final YangVersion version) {
394 StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(version, typeArgument);
396 if (support == null) {
397 support = BUILTIN_TYPE_SUPPORTS.get(YangVersion.VERSION_1, typeArgument);
400 return support == null ? null : new StatementDefinitionContext<>(support);
403 private PrefixToModule preLinkagePrefixes() {
404 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
405 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
406 if (prefixToNamespaceMap == null) {
407 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
411 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
412 return preLinkagePrefixes;
415 private PrefixToModule prefixes() {
416 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
418 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
419 (BelongsToPrefixToModuleIdentifier.class);
420 if (belongsToPrefixes != null) {
421 allPrefixes.putAll(belongsToPrefixes);
424 allPrefixes.forEach((key, value) ->
425 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
427 return prefixToModuleMap;
430 private QNameToStatementDefinition stmtDef() {
431 // regular YANG statements and extension supports added
432 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
433 qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
434 qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
436 // No further actions needed
437 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
438 return qNameToStmtDefMap;
441 // We need to any and all extension statements which have been declared in the context
442 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
443 StatementDefinitionNamespace.class);
444 if (extensions != null) {
445 extensions.forEach((qname, support) -> {
446 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
447 if (existing != null) {
448 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
450 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
455 return qNameToStmtDefMap;
458 public Set<YangVersion> getSupportedVersions() {
459 return currentContext.getSupportedVersions();