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.ImmutableMap.Builder;
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;
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.parser.spi.meta.ImportedNamespaceContext;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
42 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
45 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
46 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
47 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
48 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
50 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
51 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
52 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
53 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
54 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
55 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
68 public enum PhaseCompletionProgress {
74 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
75 private static final Map<String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
76 ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
77 .put(TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
78 .put(TypeUtils.UNION, new UnionSpecificationImpl.Definition())
79 .put(TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
80 .put(TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
81 .put(TypeUtils.BITS, new BitsSpecificationImpl.Definition())
82 .put(TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
83 .put(TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
86 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
87 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
88 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
89 private final BuildGlobalContext currentContext;
90 private final StatementStreamSource source;
92 private Map<QName, StatementSupport<?, ?, ?>> definedExtensions = ImmutableMap.of();
93 private Collection<NamespaceStorageNode> importedNamespaces = ImmutableList.of();
94 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
95 private ModelProcessingPhase inProgressPhase;
96 private RootStatementContext<?, ?, ?> root;
98 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
99 this.currentContext = Preconditions.checkNotNull(currentContext);
100 this.source = Preconditions.checkNotNull(source);
103 boolean isEnabledSemanticVersioning(){
104 return currentContext.isEnabledSemanticVersioning();
107 ModelProcessingPhase getInProgressPhase() {
108 return inProgressPhase;
111 ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
112 final StatementSourceReference ref) {
113 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(name);
116 final StatementSupport<?, ?, ?> extension = definedExtensions.get(name);
117 if (extension != null) {
118 def = new StatementDefinitionContext<>(extension);
121 def = resolveTypeBodyStmts(name.getLocalName());
123 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
125 * This code wraps statements encountered inside an extension so they do not get confused with regular
128 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
129 * this work. We really should be peeking into the extension definition to find these nodes,
130 * as otherwise we are not reusing definitions nor support for these nodes.
132 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
133 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
134 new ModelDefinedStatementDefinition(qName)));
137 Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
138 if (current == null) {
139 return createDeclaredRoot(def, ref);
141 return current.substatementBuilder(def, ref);
144 @SuppressWarnings({"rawtypes", "unchecked"})
145 private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
146 final StatementSourceReference ref) {
147 return new ContextBuilder(def, ref) {
150 public StatementContextBase build() {
152 root = new RootStatementContext(this, SourceSpecificContext.this);
154 Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
155 "Root statement was already defined as %s.", root.getIdentifier());
164 RootStatementContext<?, ?, ?> getRoot() {
168 DeclaredStatement<?> buildDeclared() {
169 return root.buildDeclared();
172 EffectiveStatement<?, ?> buildEffective() {
173 return root.buildEffective();
176 void startPhase(final ModelProcessingPhase phase) {
177 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
178 Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
179 Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
180 inProgressPhase = phase;
181 LOG.debug("Source {} started phase {}", source, phase);
185 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
187 if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
188 if (importedNamespaces.isEmpty()) {
189 importedNamespaces = new ArrayList<>(1);
191 importedNamespaces.add((NamespaceStorageNode) value);
193 getRoot().addToLocalStorage(type, key, value);
197 public StorageNodeType getStorageNodeType() {
198 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
202 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
203 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
204 if (potentialLocal != null) {
205 return potentialLocal;
208 for (final NamespaceStorageNode importedSource : importedNamespaces) {
209 final V potential = importedSource.getFromLocalStorage(type, key);
210 if (potential != null) {
219 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
220 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
221 if (potentialLocal != null) {
222 return potentialLocal;
225 for (final NamespaceStorageNode importedSource : importedNamespaces) {
226 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
228 if (potential != null) {
236 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
237 final Class<N> type) {
238 return currentContext.getNamespaceBehaviour(type);
242 public NamespaceStorageNode getParentNamespaceStorage() {
243 return currentContext;
246 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
247 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
249 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
251 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
252 final boolean phaseCompleted = root.tryToCompletePhase(phase);
254 hasProgressed |= tryToProgress(currentPhaseModifiers);
256 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
257 finishedPhase = phase;
258 LOG.debug("Source {} finished phase {}", source, phase);
259 return PhaseCompletionProgress.FINISHED;
263 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
266 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
267 boolean hasProgressed = false;
269 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
270 while (modifier.hasNext()) {
271 if (modifier.next().tryApply()) {
273 hasProgressed = true;
277 return hasProgressed;
280 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
281 final ModifierImpl action = new ModifierImpl(phase);
282 modifiers.put(phase, action);
287 public String toString() {
288 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
289 + finishedPhase + "]";
292 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
293 final List<SourceException> exceptions = new ArrayList<>();
294 for (final ModifierImpl mod : modifiers.get(identifier)) {
297 } catch (final SourceException e) {
302 if (exceptions.isEmpty()) {
303 return Optional.empty();
306 final String message = String.format("Yang model processing phase %s failed", identifier);
307 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
309 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
311 return Optional.of(e);
314 void loadStatements() throws SourceException {
315 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
317 switch (inProgressPhase) {
318 case SOURCE_PRE_LINKAGE:
319 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
322 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
324 case STATEMENT_DEFINITION:
325 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
327 case FULL_DECLARATION:
328 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
335 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
336 final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
337 return support == null ? null : new StatementDefinitionContext<>(support);
340 private PrefixToModule preLinkagePrefixes() {
341 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
342 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
343 if (prefixToNamespaceMap == null) {
344 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
348 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
349 return preLinkagePrefixes;
352 private PrefixToModule prefixes() {
353 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
355 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
356 (BelongsToPrefixToModuleIdentifier.class);
357 if (belongsToPrefixes != null) {
358 allPrefixes.putAll(belongsToPrefixes);
361 allPrefixes.forEach((key, value) ->
362 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
364 return prefixToModuleMap;
367 private static <K, V> void addSupports(final Builder<K, V> builder, @Nullable final Map<K, V> supports) {
368 if (supports != null) {
369 builder.putAll(supports);
373 private QNameToStatementDefinition stmtDef() {
374 // regular YANG statements and extension supports added
375 qNameToStmtDefMap.putAll(currentContext.getSupportsForPhase(inProgressPhase).getDefinitions());
377 // We need to any and all extension statements which have been declared in the context
378 if (inProgressPhase == ModelProcessingPhase.FULL_DECLARATION) {
379 // We maintain this map for createDeclaredChild(), which calls out to global context first,
380 // hence there is no point in performing double lookups.
381 final Builder<QName, StatementSupport<?, ?, ?>> b = ImmutableMap.builder();
382 addSupports(b, getRoot().getAllFromLocalStorage(StatementDefinitionNamespace.class));
383 for (NamespaceStorageNode namespace : importedNamespaces) {
384 addSupports(b, namespace.getAllFromLocalStorage(StatementDefinitionNamespace.class));
387 definedExtensions = b.build();
388 definedExtensions.forEach((qname, support) -> {
389 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
390 if (existing != null) {
391 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
393 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
398 return qNameToStmtDefMap;