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 static com.google.common.base.Preconditions.checkNotNull;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
16 import com.google.common.collect.HashMultimap;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.Multimap;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.Objects;
25 import java.util.Optional;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.yangtools.concepts.Mutable;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.XMLNamespace;
31 import org.opendaylight.yangtools.yang.common.YangVersion;
32 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
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.ParserNamespace;
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.meta.StatementSupportBundle;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
46 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
51 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
52 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
53 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
54 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
62 enum PhaseCompletionProgress {
68 private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
70 // TODO: consider keying by Byte equivalent of ExecutionOrder
71 private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
72 private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
73 private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
74 private final @NonNull BuildGlobalContext globalContext;
76 // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
77 private StatementStreamSource source;
80 * "imported" namespaces in this source -- this points to RootStatementContexts of
81 * - modules imported via 'import' statement
82 * - parent module, declared via 'belongs-to' statement
84 private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
85 private RootStatementContext<?, ?, ?> root;
86 // TODO: consider using ExecutionOrder byte for these two
87 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
88 private ModelProcessingPhase inProgressPhase;
90 SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
91 this.globalContext = requireNonNull(globalContext);
92 this.source = requireNonNull(source);
95 @NonNull BuildGlobalContext globalContext() {
99 ModelProcessingPhase getInProgressPhase() {
100 return inProgressPhase;
103 AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
104 final int childId, final QName name, final String argument, final StatementSourceReference ref) {
105 StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
107 def = globalContext.getModelDefinedStatementDefinition(name);
109 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
110 if (extension != null) {
111 def = new StatementDefinitionContext<>(extension);
112 globalContext.putModelDefinedStatementDefinition(name, def);
115 } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
117 * This code wraps statements encountered inside an extension so
118 * they do not get confused with regular statements.
120 def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
121 "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
125 if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
126 .getArgumentDefinition().isPresent()) {
127 SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
129 SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
133 * If the current statement definition has argument specific
134 * sub-definitions, get argument specific sub-definition based on given
135 * argument (e.g. type statement need to be specialized based on its
138 if (def.hasArgumentSpecificSubDefinitions()) {
139 def = def.getSubDefinitionSpecificForArgument(argument);
142 if (current != null) {
143 return current.createSubstatement(childId, def, ref, argument);
147 * If root is null or root version is other than default,
148 * we need to create new root.
151 root = new RootStatementContext<>(this, def, ref, argument);
152 } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
153 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
154 root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
155 root.getRootIdentifier());
157 final QName rootStatement = root.definition().getStatementName();
158 final String rootArgument = root.rawArgument();
160 checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
161 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
166 RootStatementContext<?, ?, ?> getRoot() {
171 * Return version of root statement context.
173 * @return version of root statement context
175 YangVersion getRootVersion() {
176 return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
179 void startPhase(final ModelProcessingPhase phase) {
180 final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
181 verify(Objects.equals(previousPhase, finishedPhase),
182 "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
185 final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
186 checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
187 previousPhase, previousModifiers, source);
189 inProgressPhase = phase;
190 LOG.debug("Source {} started phase {}", source, phase);
193 private void updateImportedNamespaces(final Class<?> type, final Object value) {
194 if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
195 if (importedNamespaces.isEmpty()) {
196 importedNamespaces = new ArrayList<>(1);
199 verify(value instanceof RootStatementContext);
200 importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
205 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
207 // RootStatementContext takes care of IncludedModuleContext and the rest...
208 final V ret = getRoot().putToLocalStorage(type, key, value);
209 // FIXME: what about duplicates?
210 updateImportedNamespaces(type, value);
215 public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
217 // RootStatementContext takes care of IncludedModuleContext and the rest...
218 final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
220 updateImportedNamespaces(type, value);
226 public StorageNodeType getStorageNodeType() {
227 return StorageNodeType.SOURCE_LOCAL_SPECIAL;
231 public <K, V, N extends ParserNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
232 final V potentialLocal = getRoot().getFromLocalStorage(type, key);
233 if (potentialLocal != null) {
234 return potentialLocal;
237 for (final NamespaceStorageNode importedSource : importedNamespaces) {
238 final V potential = importedSource.getFromLocalStorage(type, key);
239 if (potential != null) {
247 public <K, V, N extends ParserNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
248 final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
249 if (potentialLocal != null) {
250 return potentialLocal;
253 for (final NamespaceStorageNode importedSource : importedNamespaces) {
254 final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
256 if (potential != null) {
264 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
265 final Class<N> type) {
266 return globalContext.getNamespaceBehaviour(type);
270 public BuildGlobalContext getParentNamespaceStorage() {
271 return globalContext;
274 PhaseCompletionProgress tryToCompletePhase(final byte executionOrder) {
275 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(executionOrder));
276 final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
278 boolean hasProgressed = tryToProgress(currentPhaseModifiers);
279 final boolean phaseCompleted = requireNonNull(root, "Malformed source. Valid root element is missing.")
280 .tryToCompletePhase(executionOrder);
282 hasProgressed |= tryToProgress(currentPhaseModifiers);
284 // TODO: use executionOrder instead?
285 if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
286 finishedPhase = phase;
287 LOG.debug("Source {} finished phase {}", source, phase);
288 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
289 // We have the effective model acquired, which is the final phase of source interaction.
290 LOG.trace("Releasing source {}", source);
293 return PhaseCompletionProgress.FINISHED;
296 return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
299 private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
300 boolean hasProgressed = false;
302 // Try making forward progress ...
303 final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
304 while (modifier.hasNext()) {
305 if (modifier.next().tryApply()) {
307 hasProgressed = true;
311 return hasProgressed;
314 @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
315 final ModifierImpl action = new ModifierImpl();
316 modifiers.put(phase, action);
321 public String toString() {
322 return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
323 + finishedPhase + "]";
326 Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
327 final List<SourceException> exceptions = new ArrayList<>();
328 for (final ModifierImpl mod : modifiers.get(identifier)) {
331 } catch (final SourceException e) {
336 if (exceptions.isEmpty()) {
337 return Optional.empty();
340 final String message = String.format("Yang model processing phase %s failed", identifier);
341 final InferenceException e = new InferenceException(message, root, exceptions.get(0));
342 exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
344 return Optional.of(e);
347 void loadStatements() {
348 LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
350 switch (inProgressPhase) {
351 case SOURCE_PRE_LINKAGE:
352 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
355 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
358 case STATEMENT_DEFINITION:
359 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
360 prefixes(), getRootVersion());
362 case FULL_DECLARATION:
363 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
371 private PrefixToModule preLinkagePrefixes() {
372 final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap();
373 final Map<String, XMLNamespace> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
374 if (prefixToNamespaceMap == null) {
375 //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
379 prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
380 return preLinkagePrefixes;
383 private PrefixToModule prefixes() {
384 final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
385 ImportPrefixToModuleCtx.class);
386 if (allImports != null) {
387 allImports.forEach((key, value) ->
388 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
391 final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
392 BelongsToPrefixToModuleCtx.class);
393 if (allBelongsTo != null) {
394 allBelongsTo.forEach((key, value) ->
395 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
398 return prefixToModuleMap;
401 private QNameToStatementDefinition stmtDef() {
402 // regular YANG statements and extension supports added
403 final StatementSupportBundle supportsForPhase = globalContext.getSupportsForPhase(inProgressPhase);
404 qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
405 qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
407 // No further actions needed
408 if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
409 return qnameToStmtDefMap;
412 // We need to any and all extension statements which have been declared in the context
413 final Map<QName, StatementSupport<?, ?, ?>> extensions = globalContext.getNamespace(
414 StatementDefinitionNamespace.class);
415 if (extensions != null) {
416 extensions.forEach((qname, support) -> {
417 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
418 if (existing != null) {
419 LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
421 LOG.debug("Source {} defined statement {} as {}", source, qname, support);
426 return qnameToStmtDefMap;
429 Collection<SourceIdentifier> getRequiredSources() {
430 return root.getRequiredSources();
433 SourceIdentifier getRootIdentifier() {
434 return root.getRootIdentifier();