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;
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.common.YangConstants;
29 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
31 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
42 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
43 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
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;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
71 public enum PhaseCompletionProgress {
77 @SuppressWarnings({"rawtypes", "unchecked"})
78 private final class RootContextBuilder extends ContextBuilder {
79 RootContextBuilder(final StatementDefinitionContext def, final StatementSourceReference sourceRef) {
80 super(def, sourceRef);
84 public StatementContextBase build() {
86 root = new RootStatementContext(this, SourceSpecificContext.this);
88 Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
89 "Root statement was already defined as %s.", root.getIdentifier());
96 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
97 private static final Map<String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
98 ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
99 .put(TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
100 .put(TypeUtils.UNION, new UnionSpecificationImpl.Definition())
101 .put(TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
102 .put(TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
103 .put(TypeUtils.BITS, new BitsSpecificationImpl.Definition())
104 .put(TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
105 .put(TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
107 private static final QName TYPE = Rfc6020Mapping.TYPE.getStatementName();
109 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
110 private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
111 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
112 private final BuildGlobalContext currentContext;
113 private final StatementStreamSource source;
116 * "imported" namespaces in this source -- this points to RootStatementContexts of
117 * - modules imported via 'import' statement
118 * - parent module, declared via 'belongs-to' statement
120 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
121 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
122 private ModelProcessingPhase inProgressPhase;
123 private RootStatementContext<?, ?, ?> root;
125 SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
126 this.currentContext = Preconditions.checkNotNull(currentContext);
127 this.source = Preconditions.checkNotNull(source);
130 boolean isEnabledSemanticVersioning(){
131 return currentContext.isEnabledSemanticVersioning();
134 ModelProcessingPhase getInProgressPhase() {
135 return inProgressPhase;
138 ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, QName name,
139 final String argument, final StatementSourceReference ref) {
140 // FIXME: BUG-7038: Refactor/clean up this special case
141 if (TYPE.equals(name)) {
142 SourceException.throwIfNull(argument, ref, "Type statement requires an argument");
143 if (TypeUtils.isYangTypeBodyStmtString(argument)) {
144 name = QName.create(YangConstants.RFC6020_YIN_MODULE, argument);
146 name = QName.create(YangConstants.RFC6020_YIN_MODULE, TYPE.getLocalName());
150 StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(name);
153 final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
154 if (extension != null) {
155 def = new StatementDefinitionContext<>(extension);
158 def = resolveTypeBodyStmts(name.getLocalName());
160 } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
162 * This code wraps statements encountered inside an extension so they do not get confused with regular
165 * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
166 * this work. We really should be peeking into the extension definition to find these nodes,
167 * as otherwise we are not reusing definitions nor support for these nodes.
169 final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
170 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
171 new ModelDefinedStatementDefinition(qName)));
174 Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
175 final ContextBuilder<?, ?, ?> ret;
176 if (current == null) {
177 ret = new RootContextBuilder(def, ref);
179 ret = current.substatementBuilder(def, ref);
182 if (argument != null) {
183 ret.setArgument(argument, ref);
189 RootStatementContext<?, ?, ?> getRoot() {
193 DeclaredStatement<?> buildDeclared() {
194 return root.buildDeclared();
197 EffectiveStatement<?, ?> buildEffective() {
198 return root.buildEffective();
201 void startPhase(final ModelProcessingPhase phase) {
202 @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
203 Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
204 Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
205 inProgressPhase = phase;
206 LOG.debug("Source {} started phase {}", source, phase);
210 public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
213 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
214 if (importedNamespaces.isEmpty()) {
215 importedNamespaces = new ArrayList<>(1);
218 Verify.verify(value instanceof RootStatementContext);
219 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
222 // RootStatementContext takes care of IncludedModuleContext and the rest...
223 getRoot().addToLocalStorage(type, key, value);
227 public StorageNodeType getStorageNodeType() {
228 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
232 public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
233 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
234 if (potentialLocal != null) {
235 return potentialLocal;
238 for (final NamespaceStorageNode importedSource : importedNamespaces) {
239 final V potential = importedSource.getFromLocalStorage(type, key);
240 if (potential != null) {
249 public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
250 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
251 if (potentialLocal != null) {
252 return potentialLocal;
255 for (final NamespaceStorageNode importedSource : importedNamespaces) {
256 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
258 if (potential != null) {
266 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
267 final Class<N> type) {
268 return currentContext.getNamespaceBehaviour(type);
272 public NamespaceStorageNode getParentNamespaceStorage() {
273 return currentContext;
276 PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
277 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
279 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
281 Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
282 final boolean phaseCompleted = root.tryToCompletePhase(phase);
284 hasProgressed |= tryToProgress(currentPhaseModifiers);
286 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
287 finishedPhase = phase;
288 LOG.debug("Source {} finished phase {}", source, phase);
289 return PhaseCompletionProgress.FINISHED;
293 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
296 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
297 boolean hasProgressed = false;
299 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
300 while (modifier.hasNext()) {
301 if (modifier.next().tryApply()) {
303 hasProgressed = true;
307 return hasProgressed;
310 ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
311 final ModifierImpl action = new ModifierImpl(phase);
312 modifiers.put(phase, action);
317 public String toString() {
318 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
319 + finishedPhase + "]";
322 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
323 final List<SourceException> exceptions = new ArrayList<>();
324 for (final ModifierImpl mod : modifiers.get(identifier)) {
327 } catch (final SourceException e) {
332 if (exceptions.isEmpty()) {
333 return Optional.empty();
336 final String message = String.format("Yang model processing phase %s failed", identifier);
337 final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
339 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
341 return Optional.of(e);
344 void loadStatements() throws SourceException {
345 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
347 switch (inProgressPhase) {
348 case SOURCE_PRE_LINKAGE:
349 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
352 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
354 case STATEMENT_DEFINITION:
355 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
357 case FULL_DECLARATION:
358 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
365 private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
366 final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
367 return support == null ? null : new StatementDefinitionContext<>(support);
370 private PrefixToModule preLinkagePrefixes() {
371 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
372 final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
373 if (prefixToNamespaceMap == null) {
374 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
378 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
379 return preLinkagePrefixes;
382 private PrefixToModule prefixes() {
383 final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
385 final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
386 (BelongsToPrefixToModuleIdentifier.class);
387 if (belongsToPrefixes != null) {
388 allPrefixes.putAll(belongsToPrefixes);
391 allPrefixes.forEach((key, value) ->
392 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
394 return prefixToModuleMap;
397 private QNameToStatementDefinition stmtDef() {
398 // regular YANG statements and extension supports added
399 qNameToStmtDefMap.putAll(currentContext.getSupportsForPhase(inProgressPhase).getDefinitions());
401 // No further actions needed
402 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
403 return qNameToStmtDefMap;
406 // We need to any and all extension statements which have been declared in the context
407 final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
408 StatementDefinitionNamespace.class);
409 if (extensions != null) {
410 extensions.forEach((qname, support) -> {
411 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
412 if (existing != null) {
413 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
415 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
420 return qNameToStmtDefMap;