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.ImmutableMap;
15 import com.google.common.collect.Multimap;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Iterator;
20 import java.util.List;
22 import java.util.Objects;
23 import java.util.Optional;
25 import javax.annotation.Nullable;
26 import org.opendaylight.yangtools.concepts.Mutable;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.QNameModule;
29 import org.opendaylight.yangtools.yang.common.YangConstants;
30 import org.opendaylight.yangtools.yang.common.YangVersion;
31 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
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.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
46 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
51 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
52 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
53 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
54 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
64 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
65 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
66 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
67 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
68 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
74 public enum PhaseCompletionProgress {
80 @SuppressWarnings({"rawtypes", "unchecked"})
81 private final class RootContextBuilder extends ContextBuilder {
82 RootContextBuilder(final StatementDefinitionContext def, final StatementSourceReference sourceRef) {
83 super(def, sourceRef);
87 public StatementContextBase build() {
89 * If root is null or root version is other than default,
90 * we need to create new root.
93 root = new RootStatementContext(this, SourceSpecificContext.this);
94 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
95 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
96 root = new RootStatementContext(this, SourceSpecificContext.this, root.getRootVersion());
98 Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
99 "Root statement was already defined as %s.", root.getIdentifier());
106 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
107 private static final Map<String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
108 ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
109 .put(TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
110 .put(TypeUtils.UNION, new UnionSpecificationImpl.Definition())
111 .put(TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
112 .put(TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
113 .put(TypeUtils.BITS, new BitsSpecificationImpl.Definition())
114 .put(TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
115 .put(TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
117 private static final QName TYPE = YangStmtMapping.TYPE.getStatementName();
119 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
120 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
121 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
122 private final BuildGlobalContext currentContext;
123 private final StatementStreamSource source;
126 * "imported" namespaces in this source -- this points to RootStatementContexts of
127 * - modules imported via 'import' statement
128 * - parent module, declared via 'belongs-to' statement
130 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
131 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
132 private ModelProcessingPhase inProgressPhase;
133 private RootStatementContext<?, ?, ?> root;
135 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
136 this.currentContext = Preconditions.checkNotNull(currentContext);
137 this.source = Preconditions.checkNotNull(source);
140 boolean isEnabledSemanticVersioning(){
141 return currentContext.isEnabledSemanticVersioning();
144 ModelProcessingPhase getInProgressPhase() {
145 return inProgressPhase;
148 ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
149 QName name, final String argument, final StatementSourceReference ref) {
150 // FIXME: BUG-7038: Refactor/clean up this special case
151 if (TYPE.equals(name)) {
152 SourceException.throwIfNull(argument, ref, "Type statement requires an argument");
153 if (TypeUtils.isYangTypeBodyStmtString(argument)) {
154 name = QName.create(YangConstants.RFC6020_YIN_MODULE, argument);
156 name = QName.create(YangConstants.RFC6020_YIN_MODULE, TYPE.getLocalName());
160 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
163 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
164 if (extension != null) {
165 def = new StatementDefinitionContext<>(extension);
168 def = resolveTypeBodyStmts(name.getLocalName());
170 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
172 * This code wraps statements encountered inside an extension so they do not get confused with regular
175 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
176 * this work. We really should be peeking into the extension definition to find these nodes,
177 * as otherwise we are not reusing definitions nor support for these nodes.
179 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
180 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
181 new ModelDefinedStatementDefinition(qName)));
184 Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
185 final ContextBuilder<?, ?, ?> ret;
186 if (current == null) {
187 ret = new RootContextBuilder(def, ref);
189 ret = current.substatementBuilder(childId, def, ref);
192 if (argument != null) {
193 ret.setArgument(argument, ref);
199 RootStatementContext<?, ?, ?> getRoot() {
204 * Return version of root statement context.
206 * @return version of root statement context
208 YangVersion getRootVersion() {
209 return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
212 DeclaredStatement<?> buildDeclared() {
213 return root.buildDeclared();
216 EffectiveStatement<?, ?> buildEffective() {
217 return root.buildEffective();
220 void startPhase(final ModelProcessingPhase phase) {
221 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
222 Verify.verify(Objects.equals(previousPhase, finishedPhase),
223 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
226 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
227 Preconditions.checkState(previousModifiers.isEmpty(),
228 "Previous phase %s has unresolved modifiers %s in source %s",
229 previousPhase, previousModifiers, source);
231 inProgressPhase = phase;
232 LOG.debug("Source {} started phase {}", source, phase);
236 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
239 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
240 if (importedNamespaces.isEmpty()) {
241 importedNamespaces = new ArrayList<>(1);
244 Verify.verify(value instanceof RootStatementContext);
245 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
248 // RootStatementContext takes care of IncludedModuleContext and the rest...
249 getRoot().addToLocalStorage(type, key, value);
253 public StorageNodeType getStorageNodeType() {
254 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
258 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
259 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
260 if (potentialLocal != null) {
261 return potentialLocal;
264 for (final NamespaceStorageNode importedSource : importedNamespaces) {
265 final V potential = importedSource.getFromLocalStorage(type, key);
266 if (potential != null) {
275 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
276 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
277 if (potentialLocal != null) {
278 return potentialLocal;
281 for (final NamespaceStorageNode importedSource : importedNamespaces) {
282 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
284 if (potential != null) {
292 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
293 final Class<N> type) {
294 return currentContext.getNamespaceBehaviour(type);
298 public NamespaceStorageNode getParentNamespaceStorage() {
299 return currentContext;
302 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
303 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
305 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
307 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
308 final boolean phaseCompleted = root.tryToCompletePhase(phase);
310 hasProgressed |= tryToProgress(currentPhaseModifiers);
312 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
313 finishedPhase = phase;
314 LOG.debug("Source {} finished phase {}", source, phase);
315 return PhaseCompletionProgress.FINISHED;
319 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
322 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
323 boolean hasProgressed = false;
325 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
326 while (modifier.hasNext()) {
327 if (modifier.next().tryApply()) {
329 hasProgressed = true;
333 return hasProgressed;
336 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
337 final ModifierImpl action = new ModifierImpl(phase);
338 modifiers.put(phase, action);
343 public String toString() {
344 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
345 + finishedPhase + "]";
348 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
349 final List<SourceException> exceptions = new ArrayList<>();
350 for (final ModifierImpl mod : modifiers.get(identifier)) {
353 } catch (final SourceException e) {
358 if (exceptions.isEmpty()) {
359 return Optional.empty();
362 final String message = String.format("Yang model processing phase %s failed", identifier);
363 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
365 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
367 return Optional.of(e);
370 void loadStatements() throws SourceException {
371 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
373 switch (inProgressPhase) {
374 case SOURCE_PRE_LINKAGE:
375 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
378 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
380 case STATEMENT_DEFINITION:
381 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
383 case FULL_DECLARATION:
384 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
391 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
392 final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
393 return support == null ? null : new StatementDefinitionContext<>(support);
396 private PrefixToModule preLinkagePrefixes() {
397 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
398 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
399 if (prefixToNamespaceMap == null) {
400 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
404 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
405 return preLinkagePrefixes;
408 private PrefixToModule prefixes() {
409 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
411 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
412 (BelongsToPrefixToModuleIdentifier.class);
413 if (belongsToPrefixes != null) {
414 allPrefixes.putAll(belongsToPrefixes);
417 allPrefixes.forEach((key, value) ->
418 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.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();