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.collect.HashMultimap;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Multimap;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Iterator;
18 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.Objects;
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import org.opendaylight.yangtools.concepts.Mutable;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
28 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
32 import org.opendaylight.yangtools.yang.model.api.stmt.ExtensionStatement;
33 import org.opendaylight.yangtools.yang.parser.spi.ExtensionNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ImportedNamespaceContext;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
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.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
48 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
49 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
50 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
51 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
52 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
53 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
54 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
55 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
64 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
65 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
67 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
69 public enum PhaseCompletionProgress {
75 private final StatementStreamSource source;
76 private final BuildGlobalContext currentContext;
77 private final Collection<NamespaceStorageNode> importedNamespaces = new ArrayList<>();
78 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
80 private RootStatementContext<?, ?, ?> root;
82 private ModelProcessingPhase inProgressPhase;
83 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
84 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
85 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
88 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
90 this.currentContext = currentContext;
93 public boolean isEnabledSemanticVersioning(){
94 return currentContext.isEnabledSemanticVersioning();
97 ModelProcessingPhase getInProgressPhase() {
98 return inProgressPhase;
101 StatementDefinitionContext<?, ?, ?> getDefinition(final QName name) {
102 return currentContext.getStatementDefinition(name);
105 ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
106 final StatementSourceReference ref) {
107 StatementDefinitionContext<?, ?, ?> def = getDefinition(name);
110 // unknown-stmts (from import, include or local-scope)
111 if (qNameToStmtDefMap.get(name) != null) {
112 final StatementDefinition extension = currentContext.getFromNamespace(
113 StatementDefinitionNamespace.class, name);
114 SourceException.throwIfNull(extension, current.getStatementSourceReference(), "Extension %s not found",
117 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(extension));
120 def = resolveTypeBodyStmts(name.getLocalName());
122 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
123 // FIXME: What's going on here?
124 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
126 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
127 new ModelDefinedStatementDefinition(qName)));
130 Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
131 if (current == null) {
132 return createDeclaredRoot(def, ref);
134 return current.substatementBuilder(def, ref);
137 @SuppressWarnings({"rawtypes", "unchecked"})
138 private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
139 final StatementSourceReference ref) {
140 return new ContextBuilder(def, ref) {
143 public StatementContextBase build() {
145 root = new RootStatementContext(this, SourceSpecificContext.this);
147 Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
148 "Root statement was already defined as %s.", root.getIdentifier());
157 RootStatementContext<?, ?, ?> getRoot() {
161 DeclaredStatement<?> buildDeclared() {
162 return root.buildDeclared();
165 EffectiveStatement<?, ?> buildEffective() {
166 return root.buildEffective();
169 void startPhase(final ModelProcessingPhase phase) {
171 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
172 Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
173 Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
174 inProgressPhase = phase;
178 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
180 if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
181 importedNamespaces.add((NamespaceStorageNode) value);
183 getRoot().addToLocalStorage(type, key, value);
187 public StorageNodeType getStorageNodeType() {
188 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
192 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
193 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
194 if (potentialLocal != null) {
195 return potentialLocal;
197 for (final NamespaceStorageNode importedSource : importedNamespaces) {
198 final V potential = importedSource.getFromLocalStorage(type, key);
199 if (potential != null) {
208 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
209 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
211 if (potentialLocal != null) {
212 return potentialLocal;
215 for (final NamespaceStorageNode importedSource : importedNamespaces) {
216 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
218 if (potential != null) {
226 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
227 final Class<N> type) {
228 return currentContext.getNamespaceBehaviour(type);
232 public NamespaceStorageNode getParentNamespaceStorage() {
233 return currentContext;
236 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
237 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
239 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
241 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
242 final boolean phaseCompleted = root.tryToCompletePhase(phase);
244 hasProgressed = (tryToProgress(currentPhaseModifiers) | hasProgressed);
246 if (phaseCompleted && (currentPhaseModifiers.isEmpty())) {
247 finishedPhase = phase;
248 return PhaseCompletionProgress.FINISHED;
252 return PhaseCompletionProgress.PROGRESS;
254 return PhaseCompletionProgress.NO_PROGRESS;
258 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
259 boolean hasProgressed = false;
261 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
262 while (modifier.hasNext()) {
263 if (modifier.next().tryApply()) {
265 hasProgressed = true;
269 return hasProgressed;
273 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
274 final ModifierImpl action = new ModifierImpl(phase);
275 modifiers.put(phase, action);
280 public String toString() {
281 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
282 + finishedPhase + "]";
285 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
286 final List<SourceException> exceptions = new ArrayList<>();
287 for (final ModifierImpl mod : modifiers.get(identifier)) {
290 } catch (final SourceException e) {
295 if (exceptions.isEmpty()) {
296 return Optional.empty();
299 final String message = String.format("Yang model processing phase %s failed", identifier);
300 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
302 final Iterator<SourceException> it = exceptions.listIterator(1);
303 while (it.hasNext()) {
304 e.addSuppressed(it.next());
307 return Optional.of(e);
310 void loadStatements() throws SourceException {
311 switch (inProgressPhase) {
312 case SOURCE_PRE_LINKAGE:
313 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
316 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
318 case STATEMENT_DEFINITION:
319 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
321 case FULL_DECLARATION:
322 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
329 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
330 switch (typeArgument) {
331 case TypeUtils.DECIMAL64:
332 return new StatementDefinitionContext<>(new Decimal64SpecificationImpl.Definition());
333 case TypeUtils.UNION:
334 return new StatementDefinitionContext<>(new UnionSpecificationImpl.Definition());
335 case TypeUtils.ENUMERATION:
336 return new StatementDefinitionContext<>(new EnumSpecificationImpl.Definition());
337 case TypeUtils.LEAF_REF:
338 return new StatementDefinitionContext<>(new LeafrefSpecificationImpl.Definition());
340 return new StatementDefinitionContext<>(new BitsSpecificationImpl.Definition());
341 case TypeUtils.IDENTITY_REF:
342 return new StatementDefinitionContext<>(new IdentityRefSpecificationImpl.Definition());
343 case TypeUtils.INSTANCE_IDENTIFIER:
344 return new StatementDefinitionContext<>(new InstanceIdentifierSpecificationImpl.Definition());
350 private PrefixToModule preLinkagePrefixes() {
351 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
352 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
353 if (prefixToNamespaceMap == null) {
354 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
357 for (final Entry<String, URI> prefixToNamespace : prefixToNamespaceMap.entrySet()) {
358 preLinkagePrefixes.put(prefixToNamespace.getKey(), QNameModule.create(prefixToNamespace.getValue(), null));
361 return preLinkagePrefixes;
364 private PrefixToModule prefixes() {
365 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
367 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
368 (BelongsToPrefixToModuleIdentifier.class);
369 if (belongsToPrefixes != null) {
370 allPrefixes.putAll(belongsToPrefixes);
373 for (final Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
374 final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
375 stringModuleIdentifierEntry.getValue());
376 prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
378 return prefixToModuleMap;
381 private QNameToStatementDefinition stmtDef() {
382 // regular YANG statements and extension supports added
383 final ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
384 inProgressPhase).getDefinitions();
385 for (final Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
386 qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
390 if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
391 final Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions =
392 currentContext.getAllFromNamespace(ExtensionNamespace.class);
393 if (extensions != null) {
394 for (final Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension :
395 extensions.entrySet()) {
396 if(qNameToStmtDefMap.get(extension.getKey()) == null) {
397 qNameToStmtDefMap.put((extension.getKey()),
398 (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension.getValue()).definition()
405 return qNameToStmtDefMap;