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.model.api.meta.StatementSource;
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.source.BelongsToModuleContext;
49 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
55 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
56 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
57 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
58 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
59 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
64 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
65 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
66 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
67 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
68 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
69 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
70 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
71 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
72 import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.IdentityrefSpecificationRfc7950Support;
73 import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.LeafrefSpecificationRfc7950Support;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
77 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
79 public enum PhaseCompletionProgress {
85 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
86 private static final Table<YangVersion, String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
87 ImmutableTable.<YangVersion, String, StatementSupport<?, ?, ?>>builder()
88 .put(YangVersion.VERSION_1, TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
89 .put(YangVersion.VERSION_1, TypeUtils.UNION, new UnionSpecificationImpl.Definition())
90 .put(YangVersion.VERSION_1, TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
91 .put(YangVersion.VERSION_1, TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
92 .put(YangVersion.VERSION_1_1, TypeUtils.LEAF_REF, new LeafrefSpecificationRfc7950Support())
93 .put(YangVersion.VERSION_1, TypeUtils.BITS, new BitsSpecificationImpl.Definition())
94 .put(YangVersion.VERSION_1, TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
95 .put(YangVersion.VERSION_1_1, TypeUtils.IDENTITY_REF, new IdentityrefSpecificationRfc7950Support())
96 .put(YangVersion.VERSION_1, TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
99 private static final QName TYPE = YangStmtMapping.TYPE.getStatementName();
101 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
102 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
103 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
104 private final BuildGlobalContext currentContext;
105 private final StatementStreamSource source;
108 * "imported" namespaces in this source -- this points to RootStatementContexts of
109 * - modules imported via 'import' statement
110 * - parent module, declared via 'belongs-to' statement
112 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
113 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
114 private ModelProcessingPhase inProgressPhase;
115 private RootStatementContext<?, ?, ?> root;
117 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
118 this.currentContext = Preconditions.checkNotNull(currentContext);
119 this.source = Preconditions.checkNotNull(source);
122 boolean isEnabledSemanticVersioning(){
123 return currentContext.isEnabledSemanticVersioning();
126 ModelProcessingPhase getInProgressPhase() {
127 return inProgressPhase;
130 StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
131 QName name, final String argument, final StatementSourceReference ref) {
132 if (current != null) {
133 // Fast path: we are entering a statement which was emitted in previous phase
134 StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
135 while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
136 existing = existing.lookupSubstatement(childId);
138 if (existing != null) {
143 // FIXME: BUG-7038: Refactor/clean up this special case
144 if (TYPE.equals(name)) {
145 SourceException.throwIfNull(argument, ref, "Type statement requires an argument");
146 if (TypeUtils.isYangTypeBodyStmtString(argument)) {
147 name = QName.create(YangConstants.RFC6020_YIN_MODULE, argument);
149 name = QName.create(YangConstants.RFC6020_YIN_MODULE, TYPE.getLocalName());
153 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
155 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
156 if (extension != null) {
157 def = new StatementDefinitionContext<>(extension);
160 def = resolveTypeBodyStmts(name.getLocalName(), getRootVersion());
162 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
164 * This code wraps statements encountered inside an extension so they do not get confused with regular
167 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
168 * this work. We really should be peeking into the extension definition to find these nodes,
169 * as otherwise we are not reusing definitions nor support for these nodes.
171 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
172 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
173 new ModelDefinedStatementDefinition(qName, argument != null)));
176 InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
177 if (def.hasArgument()) {
178 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
180 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
183 if (current != null) {
184 return current.createSubstatement(childId, def, ref, argument);
188 * If root is null or root version is other than default,
189 * we need to create new root.
192 root = new RootStatementContext<>(this, def, ref, argument);
193 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
194 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
195 root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(), root.getRootIdentifier());
197 final QName rootStatement = root.definition().getStatementName();
198 final String rootArgument = root.rawStatementArgument();
200 Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
201 && Objects.equals(argument, rootArgument),
202 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
207 RootStatementContext<?, ?, ?> getRoot() {
212 * Return version of root statement context.
214 * @return version of root statement context
216 YangVersion getRootVersion() {
217 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
220 DeclaredStatement<?> buildDeclared() {
221 return root.buildDeclared();
224 EffectiveStatement<?, ?> buildEffective() {
225 return root.buildEffective();
228 void startPhase(final ModelProcessingPhase phase) {
229 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
230 Verify.verify(Objects.equals(previousPhase, finishedPhase),
231 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
234 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
235 Preconditions.checkState(previousModifiers.isEmpty(),
236 "Previous phase %s has unresolved modifiers %s in source %s",
237 previousPhase, previousModifiers, source);
239 inProgressPhase = phase;
240 LOG.debug("Source {} started phase {}", source, phase);
243 private void updateImportedNamespaces(final Class<?> type, final Object value) {
244 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
245 if (importedNamespaces.isEmpty()) {
246 importedNamespaces = new ArrayList<>(1);
249 Verify.verify(value instanceof RootStatementContext);
250 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
255 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
257 // RootStatementContext takes care of IncludedModuleContext and the rest...
258 final V ret = getRoot().putToLocalStorage(type, key, value);
259 // FIXME: what about duplicates?
260 updateImportedNamespaces(type, value);
265 public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
267 // RootStatementContext takes care of IncludedModuleContext and the rest...
268 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
270 updateImportedNamespaces(type, value);
276 public StorageNodeType getStorageNodeType() {
277 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
281 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
282 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
283 if (potentialLocal != null) {
284 return potentialLocal;
287 for (final NamespaceStorageNode importedSource : importedNamespaces) {
288 final V potential = importedSource.getFromLocalStorage(type, key);
289 if (potential != null) {
298 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
299 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
300 if (potentialLocal != null) {
301 return potentialLocal;
304 for (final NamespaceStorageNode importedSource : importedNamespaces) {
305 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
307 if (potential != null) {
315 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
316 final Class<N> type) {
317 return currentContext.getNamespaceBehaviour(type);
321 public NamespaceStorageNode getParentNamespaceStorage() {
322 return currentContext;
325 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
326 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
328 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
330 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
331 final boolean phaseCompleted = root.tryToCompletePhase(phase);
333 hasProgressed |= tryToProgress(currentPhaseModifiers);
335 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
336 finishedPhase = phase;
337 LOG.debug("Source {} finished phase {}", source, phase);
338 return PhaseCompletionProgress.FINISHED;
342 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
345 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
346 boolean hasProgressed = false;
348 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
349 while (modifier.hasNext()) {
350 if (modifier.next().tryApply()) {
352 hasProgressed = true;
356 return hasProgressed;
359 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
360 final ModifierImpl action = new ModifierImpl(phase);
361 modifiers.put(phase, action);
366 public String toString() {
367 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
368 + finishedPhase + "]";
371 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
372 final List<SourceException> exceptions = new ArrayList<>();
373 for (final ModifierImpl mod : modifiers.get(identifier)) {
376 } catch (final SourceException e) {
381 if (exceptions.isEmpty()) {
382 return Optional.empty();
385 final String message = String.format("Yang model processing phase %s failed", identifier);
386 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
388 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
390 return Optional.of(e);
393 void loadStatements() throws SourceException {
394 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
396 switch (inProgressPhase) {
397 case SOURCE_PRE_LINKAGE:
398 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
401 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(), getRootVersion());
403 case STATEMENT_DEFINITION:
404 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
406 case FULL_DECLARATION:
407 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
414 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument,
415 final YangVersion version) {
416 StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(version, typeArgument);
418 if (support == null) {
419 support = BUILTIN_TYPE_SUPPORTS.get(YangVersion.VERSION_1, typeArgument);
422 return support == null ? null : new StatementDefinitionContext<>(support);
425 private PrefixToModule preLinkagePrefixes() {
426 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
427 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
428 if (prefixToNamespaceMap == null) {
429 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
433 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
434 return preLinkagePrefixes;
437 private PrefixToModule prefixes() {
438 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
440 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
441 (BelongsToPrefixToModuleIdentifier.class);
442 if (belongsToPrefixes != null) {
443 allPrefixes.putAll(belongsToPrefixes);
446 allPrefixes.forEach((key, value) ->
447 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
449 return prefixToModuleMap;
452 private QNameToStatementDefinition stmtDef() {
453 // regular YANG statements and extension supports added
454 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
455 qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
456 qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
458 // No further actions needed
459 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
460 return qNameToStmtDefMap;
463 // We need to any and all extension statements which have been declared in the context
464 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
465 StatementDefinitionNamespace.class);
466 if (extensions != null) {
467 extensions.forEach((qname, support) -> {
468 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
469 if (existing != null) {
470 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
472 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
477 return qNameToStmtDefMap;
480 public Set<YangVersion> getSupportedVersions() {
481 return currentContext.getSupportedVersions();
484 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
485 currentContext.addMutableStmtToSeal(mutableStatement);
488 Collection<ModuleIdentifier> getRequiredModules() {
489 return root.getRequiredModules();
492 ModuleIdentifier getRootIdentifier() {
493 return root.getRootIdentifier();