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.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.Multimap;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Objects;
23 import java.util.Optional;
24 import javax.annotation.Nullable;
25 import org.opendaylight.yangtools.concepts.Mutable;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
33 import org.opendaylight.yangtools.yang.model.api.stmt.ExtensionStatement;
34 import org.opendaylight.yangtools.yang.parser.spi.ExtensionNamespace;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ImportedNamespaceContext;
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.StmtContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
49 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
50 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
51 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
52 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
53 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
54 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
55 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
64 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
65 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
66 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
72 public enum PhaseCompletionProgress {
78 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
79 private static final Map<String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
80 ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
81 .put(TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
82 .put(TypeUtils.UNION, new UnionSpecificationImpl.Definition())
83 .put(TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
84 .put(TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
85 .put(TypeUtils.BITS, new BitsSpecificationImpl.Definition())
86 .put(TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
87 .put(TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
90 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
91 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
92 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
93 private final BuildGlobalContext currentContext;
94 private final StatementStreamSource source;
96 private Collection<NamespaceStorageNode> importedNamespaces = ImmutableList.of();
97 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
98 private ModelProcessingPhase inProgressPhase;
99 private RootStatementContext<?, ?, ?> root;
101 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
102 this.currentContext = Preconditions.checkNotNull(currentContext);
103 this.source = Preconditions.checkNotNull(source);
106 public boolean isEnabledSemanticVersioning(){
107 return currentContext.isEnabledSemanticVersioning();
110 ModelProcessingPhase getInProgressPhase() {
111 return inProgressPhase;
114 StatementDefinitionContext<?, ?, ?> getDefinition(final QName name) {
115 return currentContext.getStatementDefinition(name);
118 ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
119 final StatementSourceReference ref) {
120 StatementDefinitionContext<?, ?, ?> def = getDefinition(name);
123 // unknown-stmts (from import, include or local-scope)
124 if (qNameToStmtDefMap.get(name) != null) {
125 final StatementDefinition extension = currentContext.getFromNamespace(
126 StatementDefinitionNamespace.class, name);
127 SourceException.throwIfNull(extension, current.getStatementSourceReference(), "Extension %s not found",
130 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(extension));
133 def = resolveTypeBodyStmts(name.getLocalName());
135 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
136 // FIXME: What's going on here?
137 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
139 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
140 new ModelDefinedStatementDefinition(qName)));
143 Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
144 if (current == null) {
145 return createDeclaredRoot(def, ref);
147 return current.substatementBuilder(def, ref);
150 @SuppressWarnings({"rawtypes", "unchecked"})
151 private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
152 final StatementSourceReference ref) {
153 return new ContextBuilder(def, ref) {
156 public StatementContextBase build() {
158 root = new RootStatementContext(this, SourceSpecificContext.this);
160 Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
161 "Root statement was already defined as %s.", root.getIdentifier());
170 RootStatementContext<?, ?, ?> getRoot() {
174 DeclaredStatement<?> buildDeclared() {
175 return root.buildDeclared();
178 EffectiveStatement<?, ?> buildEffective() {
179 return root.buildEffective();
182 void startPhase(final ModelProcessingPhase phase) {
183 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
184 Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
185 Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
186 inProgressPhase = phase;
187 LOG.debug("Source {} started phase {}", source, phase);
191 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
193 if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
194 if (importedNamespaces.isEmpty()) {
195 importedNamespaces = new ArrayList<>(1);
197 importedNamespaces.add((NamespaceStorageNode) value);
199 getRoot().addToLocalStorage(type, key, value);
203 public StorageNodeType getStorageNodeType() {
204 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
208 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
209 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
210 if (potentialLocal != null) {
211 return potentialLocal;
213 for (final NamespaceStorageNode importedSource : importedNamespaces) {
214 final V potential = importedSource.getFromLocalStorage(type, key);
215 if (potential != null) {
224 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
225 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
227 if (potentialLocal != null) {
228 return potentialLocal;
231 for (final NamespaceStorageNode importedSource : importedNamespaces) {
232 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
234 if (potential != null) {
242 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
243 final Class<N> type) {
244 return currentContext.getNamespaceBehaviour(type);
248 public NamespaceStorageNode getParentNamespaceStorage() {
249 return currentContext;
252 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
253 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
255 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
257 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
258 final boolean phaseCompleted = root.tryToCompletePhase(phase);
260 hasProgressed |= tryToProgress(currentPhaseModifiers);
262 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
263 finishedPhase = phase;
264 LOG.debug("Source {} finished phase {}", source, phase);
265 return PhaseCompletionProgress.FINISHED;
269 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
273 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
274 boolean hasProgressed = false;
276 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
277 while (modifier.hasNext()) {
278 if (modifier.next().tryApply()) {
280 hasProgressed = true;
284 return hasProgressed;
288 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
289 final ModifierImpl action = new ModifierImpl(phase);
290 modifiers.put(phase, action);
295 public String toString() {
296 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
297 + finishedPhase + "]";
300 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
301 final List<SourceException> exceptions = new ArrayList<>();
302 for (final ModifierImpl mod : modifiers.get(identifier)) {
305 } catch (final SourceException e) {
310 if (exceptions.isEmpty()) {
311 return Optional.empty();
314 final String message = String.format("Yang model processing phase %s failed", identifier);
315 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
317 final Iterator<SourceException> it = exceptions.listIterator(1);
318 while (it.hasNext()) {
319 e.addSuppressed(it.next());
322 return Optional.of(e);
325 void loadStatements() throws SourceException {
326 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
328 switch (inProgressPhase) {
329 case SOURCE_PRE_LINKAGE:
330 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
333 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
335 case STATEMENT_DEFINITION:
336 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
338 case FULL_DECLARATION:
339 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
346 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
347 final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
348 return support == null ? null : new StatementDefinitionContext<>(support);
351 private PrefixToModule preLinkagePrefixes() {
352 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
353 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
354 if (prefixToNamespaceMap == null) {
355 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
358 for (final Entry<String, URI> prefixToNamespace : prefixToNamespaceMap.entrySet()) {
359 preLinkagePrefixes.put(prefixToNamespace.getKey(), QNameModule.create(prefixToNamespace.getValue(), null));
362 return preLinkagePrefixes;
365 private PrefixToModule prefixes() {
366 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
368 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
369 (BelongsToPrefixToModuleIdentifier.class);
370 if (belongsToPrefixes != null) {
371 allPrefixes.putAll(belongsToPrefixes);
374 for (final Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
375 final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
376 stringModuleIdentifierEntry.getValue());
377 prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
379 return prefixToModuleMap;
382 private QNameToStatementDefinition stmtDef() {
383 // regular YANG statements and extension supports added
384 final ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
385 inProgressPhase).getDefinitions();
386 for (final Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
387 qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
391 if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
392 final Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions =
393 currentContext.getAllFromNamespace(ExtensionNamespace.class);
394 if (extensions != null) {
395 for (final Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension :
396 extensions.entrySet()) {
397 if(qNameToStmtDefMap.get(extension.getKey()) == null) {
398 qNameToStmtDefMap.put((extension.getKey()),
399 (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension.getValue()).definition()
406 return qNameToStmtDefMap;