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.Rfc6020Mapping;
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 = Rfc6020Mapping.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 Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
223 Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
224 inProgressPhase = phase;
225 LOG.debug("Source {} started phase {}", source, phase);
229 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
232 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
233 if (importedNamespaces.isEmpty()) {
234 importedNamespaces = new ArrayList<>(1);
237 Verify.verify(value instanceof RootStatementContext);
238 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
241 // RootStatementContext takes care of IncludedModuleContext and the rest...
242 getRoot().addToLocalStorage(type, key, value);
246 public StorageNodeType getStorageNodeType() {
247 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
251 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
252 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
253 if (potentialLocal != null) {
254 return potentialLocal;
257 for (final NamespaceStorageNode importedSource : importedNamespaces) {
258 final V potential = importedSource.getFromLocalStorage(type, key);
259 if (potential != null) {
268 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
269 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
270 if (potentialLocal != null) {
271 return potentialLocal;
274 for (final NamespaceStorageNode importedSource : importedNamespaces) {
275 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
277 if (potential != null) {
285 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
286 final Class<N> type) {
287 return currentContext.getNamespaceBehaviour(type);
291 public NamespaceStorageNode getParentNamespaceStorage() {
292 return currentContext;
295 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
296 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
298 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
300 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
301 final boolean phaseCompleted = root.tryToCompletePhase(phase);
303 hasProgressed |= tryToProgress(currentPhaseModifiers);
305 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
306 finishedPhase = phase;
307 LOG.debug("Source {} finished phase {}", source, phase);
308 return PhaseCompletionProgress.FINISHED;
312 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
315 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
316 boolean hasProgressed = false;
318 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
319 while (modifier.hasNext()) {
320 if (modifier.next().tryApply()) {
322 hasProgressed = true;
326 return hasProgressed;
329 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
330 final ModifierImpl action = new ModifierImpl(phase);
331 modifiers.put(phase, action);
336 public String toString() {
337 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
338 + finishedPhase + "]";
341 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
342 final List<SourceException> exceptions = new ArrayList<>();
343 for (final ModifierImpl mod : modifiers.get(identifier)) {
346 } catch (final SourceException e) {
351 if (exceptions.isEmpty()) {
352 return Optional.empty();
355 final String message = String.format("Yang model processing phase %s failed", identifier);
356 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
358 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
360 return Optional.of(e);
363 void loadStatements() throws SourceException {
364 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
366 switch (inProgressPhase) {
367 case SOURCE_PRE_LINKAGE:
368 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
371 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
373 case STATEMENT_DEFINITION:
374 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
376 case FULL_DECLARATION:
377 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
384 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
385 final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
386 return support == null ? null : new StatementDefinitionContext<>(support);
389 private PrefixToModule preLinkagePrefixes() {
390 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
391 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
392 if (prefixToNamespaceMap == null) {
393 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
397 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
398 return preLinkagePrefixes;
401 private PrefixToModule prefixes() {
402 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
404 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
405 (BelongsToPrefixToModuleIdentifier.class);
406 if (belongsToPrefixes != null) {
407 allPrefixes.putAll(belongsToPrefixes);
410 allPrefixes.forEach((key, value) ->
411 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
413 return prefixToModuleMap;
416 private QNameToStatementDefinition stmtDef() {
417 // regular YANG statements and extension supports added
418 final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
419 qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
420 qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
422 // No further actions needed
423 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
424 return qNameToStmtDefMap;
427 // We need to any and all extension statements which have been declared in the context
428 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
429 StatementDefinitionNamespace.class);
430 if (extensions != null) {
431 extensions.forEach((qname, support) -> {
432 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
433 if (existing != null) {
434 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
436 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
441 return qNameToStmtDefMap;
444 public Set<YangVersion> getSupportedVersions() {
445 return currentContext.getSupportedVersions();