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.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.parser.spi.meta.ImportedNamespaceContext;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
41 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
42 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
44 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
45 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
46 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
47 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
50 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
51 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
52 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
53 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
54 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
55 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
67 public enum PhaseCompletionProgress {
73 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
74 private static final Map<String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
75 ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
76 .put(TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
77 .put(TypeUtils.UNION, new UnionSpecificationImpl.Definition())
78 .put(TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
79 .put(TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
80 .put(TypeUtils.BITS, new BitsSpecificationImpl.Definition())
81 .put(TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
82 .put(TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
85 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
86 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
87 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
88 private final BuildGlobalContext currentContext;
89 private final StatementStreamSource source;
91 private Collection<NamespaceStorageNode> importedNamespaces = ImmutableList.of();
92 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
93 private ModelProcessingPhase inProgressPhase;
94 private RootStatementContext<?, ?, ?> root;
96 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
97 this.currentContext = Preconditions.checkNotNull(currentContext);
98 this.source = Preconditions.checkNotNull(source);
101 boolean isEnabledSemanticVersioning(){
102 return currentContext.isEnabledSemanticVersioning();
105 ModelProcessingPhase getInProgressPhase() {
106 return inProgressPhase;
109 ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
110 final StatementSourceReference ref) {
111 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(name);
114 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
115 if (extension != null) {
116 def = new StatementDefinitionContext<>(extension);
119 def = resolveTypeBodyStmts(name.getLocalName());
121 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
123 * This code wraps statements encountered inside an extension so they do not get confused with regular
126 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
127 * this work. We really should be peeking into the extension definition to find these nodes,
128 * as otherwise we are not reusing definitions nor support for these nodes.
130 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
131 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
132 new ModelDefinedStatementDefinition(qName)));
135 Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
136 if (current == null) {
137 return createDeclaredRoot(def, ref);
139 return current.substatementBuilder(def, ref);
142 @SuppressWarnings({"rawtypes", "unchecked"})
143 private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
144 final StatementSourceReference ref) {
145 return new ContextBuilder(def, ref) {
148 public StatementContextBase build() {
150 root = new RootStatementContext(this, SourceSpecificContext.this);
152 Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
153 "Root statement was already defined as %s.", root.getIdentifier());
162 RootStatementContext<?, ?, ?> getRoot() {
166 DeclaredStatement<?> buildDeclared() {
167 return root.buildDeclared();
170 EffectiveStatement<?, ?> buildEffective() {
171 return root.buildEffective();
174 void startPhase(final ModelProcessingPhase phase) {
175 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
176 Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
177 Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
178 inProgressPhase = phase;
179 LOG.debug("Source {} started phase {}", source, phase);
183 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
185 if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
186 if (importedNamespaces.isEmpty()) {
187 importedNamespaces = new ArrayList<>(1);
189 importedNamespaces.add((NamespaceStorageNode) value);
191 getRoot().addToLocalStorage(type, key, value);
195 public StorageNodeType getStorageNodeType() {
196 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
200 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
201 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
202 if (potentialLocal != null) {
203 return potentialLocal;
206 for (final NamespaceStorageNode importedSource : importedNamespaces) {
207 final V potential = importedSource.getFromLocalStorage(type, key);
208 if (potential != null) {
217 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
218 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
219 if (potentialLocal != null) {
220 return potentialLocal;
223 for (final NamespaceStorageNode importedSource : importedNamespaces) {
224 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
226 if (potential != null) {
234 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
235 final Class<N> type) {
236 return currentContext.getNamespaceBehaviour(type);
240 public NamespaceStorageNode getParentNamespaceStorage() {
241 return currentContext;
244 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
245 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
247 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
249 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
250 final boolean phaseCompleted = root.tryToCompletePhase(phase);
252 hasProgressed |= tryToProgress(currentPhaseModifiers);
254 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
255 finishedPhase = phase;
256 LOG.debug("Source {} finished phase {}", source, phase);
257 return PhaseCompletionProgress.FINISHED;
261 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
264 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
265 boolean hasProgressed = false;
267 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
268 while (modifier.hasNext()) {
269 if (modifier.next().tryApply()) {
271 hasProgressed = true;
275 return hasProgressed;
278 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
279 final ModifierImpl action = new ModifierImpl(phase);
280 modifiers.put(phase, action);
285 public String toString() {
286 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
287 + finishedPhase + "]";
290 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
291 final List<SourceException> exceptions = new ArrayList<>();
292 for (final ModifierImpl mod : modifiers.get(identifier)) {
295 } catch (final SourceException e) {
300 if (exceptions.isEmpty()) {
301 return Optional.empty();
304 final String message = String.format("Yang model processing phase %s failed", identifier);
305 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
307 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
309 return Optional.of(e);
312 void loadStatements() throws SourceException {
313 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
315 switch (inProgressPhase) {
316 case SOURCE_PRE_LINKAGE:
317 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
320 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
322 case STATEMENT_DEFINITION:
323 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
325 case FULL_DECLARATION:
326 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
333 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
334 final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
335 return support == null ? null : new StatementDefinitionContext<>(support);
338 private PrefixToModule preLinkagePrefixes() {
339 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
340 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
341 if (prefixToNamespaceMap == null) {
342 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
346 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
347 return preLinkagePrefixes;
350 private PrefixToModule prefixes() {
351 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
353 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
354 (BelongsToPrefixToModuleIdentifier.class);
355 if (belongsToPrefixes != null) {
356 allPrefixes.putAll(belongsToPrefixes);
359 allPrefixes.forEach((key, value) ->
360 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
362 return prefixToModuleMap;
365 private QNameToStatementDefinition stmtDef() {
366 // regular YANG statements and extension supports added
367 qNameToStmtDefMap.putAll(currentContext.getSupportsForPhase(inProgressPhase).getDefinitions());
369 // No further actions needed
370 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
371 return qNameToStmtDefMap;
374 // We need to any and all extension statements which have been declared in the context
375 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
376 StatementDefinitionNamespace.class);
377 if (extensions != null) {
378 extensions.forEach((qname, support) -> {
379 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
380 if (existing != null) {
381 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
383 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
388 return qNameToStmtDefMap;