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.checkState;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.Verify;
14 import com.google.common.collect.HashBasedTable;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.ImmutableSetMultimap;
18 import com.google.common.collect.SetMultimap;
19 import com.google.common.collect.Table;
20 import com.google.common.collect.TreeBasedTable;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.Objects;
29 import java.util.Optional;
31 import java.util.SortedMap;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.common.Revision;
36 import org.opendaylight.yangtools.yang.common.YangVersion;
37 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
38 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
57 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
59 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
62 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
64 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
65 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
66 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
71 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
73 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
74 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
75 ModelProcessingPhase.SOURCE_LINKAGE,
76 ModelProcessingPhase.STATEMENT_DEFINITION,
77 ModelProcessingPhase.FULL_DECLARATION,
78 ModelProcessingPhase.EFFECTIVE_MODEL
81 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
82 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
83 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
84 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
85 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
86 private final Set<SourceSpecificContext> sources = new HashSet<>();
87 private final ImmutableSet<YangVersion> supportedVersions;
88 private final boolean enabledSemanticVersions;
90 private Set<SourceSpecificContext> libSources = new HashSet<>();
91 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
92 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
94 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
95 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation,
96 final StatementParserMode statementParserMode) {
97 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
99 switch (statementParserMode) {
101 enabledSemanticVersions = false;
104 enabledSemanticVersions = true;
107 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
110 addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
112 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
115 boolean isEnabledSemanticVersioning() {
116 return enabledSemanticVersions;
119 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
120 return supports.get(phase);
123 void addSource(final @NonNull StatementStreamSource source) {
124 sources.add(new SourceSpecificContext(this, source));
127 void addLibSource(final @NonNull StatementStreamSource libSource) {
128 checkState(!isEnabledSemanticVersioning(),
129 "Library sources are not supported in semantic version mode currently.");
130 checkState(currentPhase == ModelProcessingPhase.INIT,
131 "Add library source is allowed in ModelProcessingPhase.INIT only");
132 libSources.add(new SourceSpecificContext(this, libSource));
135 void setSupportedFeatures(final Set<QName> supportedFeatures) {
136 addToNamespace(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
137 ImmutableSet.copyOf(supportedFeatures));
140 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
141 addToNamespace(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
142 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
146 public StorageNodeType getStorageNodeType() {
147 return StorageNodeType.GLOBAL;
151 public NamespaceStorageNode getParentNamespaceStorage() {
156 public NamespaceBehaviour.Registry getBehaviourRegistry() {
161 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
162 final Class<N> type) {
163 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
164 if (potential == null) {
165 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
166 if (potentialRaw != null) {
167 potential = createNamespaceContext(potentialRaw);
168 supportedNamespaces.put(type, potential);
170 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
175 Verify.verify(type.equals(potential.getIdentifier()));
177 * Safe cast, previous checkState checks equivalence of key from which
178 * type argument are derived
180 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
183 @SuppressWarnings({ "unchecked", "rawtypes" })
184 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
185 final NamespaceBehaviour<K, V, N> potentialRaw) {
186 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
187 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
188 (DerivedNamespaceBehaviour) potentialRaw);
189 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
191 return derivedContext;
193 return new SimpleNamespaceContext<>(potentialRaw);
196 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
197 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
198 if (potential == null) {
199 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
201 if (potentialRaw != null) {
202 potential = new StatementDefinitionContext<>(potentialRaw);
203 definitions.put(version, name, potential);
209 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
210 return modelDefinedStmtDefs.get(name);
213 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
214 modelDefinedStmtDefs.put(name, def);
217 private void executePhases() throws ReactorException {
218 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
220 loadPhaseStatements();
221 completePhaseActions();
226 ReactorDeclaredModel build() throws ReactorException {
231 EffectiveSchemaContext buildEffective() throws ReactorException {
233 return transformEffective();
236 private ReactorDeclaredModel transform() {
237 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
238 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
239 for (final SourceSpecificContext source : sources) {
240 rootStatements.add(source.getRoot().declared());
242 return new ReactorDeclaredModel(rootStatements);
245 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
246 final RuntimeException cause) throws SomeModifiersUnresolvedException {
247 final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
248 if (!(cause instanceof SourceException)) {
250 * This should not be happening as all our processing should provide SourceExceptions.
251 * We will wrap the exception to provide enough information to identify the problematic model,
252 * but also emit a warning so the offending codepath will get fixed.
254 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
258 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
261 private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
262 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
263 final String arg = root.getRawArgument();
264 if (qNameModule != null) {
265 // creates SourceIdentifier for a module
266 return RevisionSourceIdentifier.create(arg, qNameModule.getRevision());
269 // creates SourceIdentifier for a submodule
270 return RevisionSourceIdentifier.create(arg, StmtContextUtils.getLatestRevision(root.declaredSubstatements()));
273 @SuppressWarnings("checkstyle:illegalCatch")
274 private EffectiveSchemaContext transformEffective() throws ReactorException {
275 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
276 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
277 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
279 for (final SourceSpecificContext source : sources) {
280 final RootStatementContext<?, ?, ?> root = source.getRoot();
282 rootStatements.add(root.declared());
283 rootEffectiveStatements.add(root.buildEffective());
284 } catch (final RuntimeException ex) {
285 throw propagateException(source, ex);
289 sealMutableStatements();
290 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
293 private void startPhase(final ModelProcessingPhase phase) {
294 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
295 startPhaseFor(phase, sources);
296 startPhaseFor(phase, libSources);
298 currentPhase = phase;
299 LOG.debug("Global phase {} started", phase);
302 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
303 for (final SourceSpecificContext source : sources) {
304 source.startPhase(phase);
308 private void loadPhaseStatements() throws ReactorException {
309 checkState(currentPhase != null);
310 loadPhaseStatementsFor(sources);
311 loadPhaseStatementsFor(libSources);
314 @SuppressWarnings("checkstyle:illegalCatch")
315 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
316 for (final SourceSpecificContext source : srcs) {
318 source.loadStatements();
319 } catch (final RuntimeException ex) {
320 throw propagateException(source, ex);
325 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
326 boolean addedCause = false;
327 SomeModifiersUnresolvedException buildFailure = null;
328 for (final SourceSpecificContext failedSource : sourcesToProgress) {
329 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
330 if (optSourceEx.isEmpty()) {
334 final SourceException sourceEx = optSourceEx.get();
335 // Workaround for broken logging implementations which ignore
336 // suppressed exceptions
337 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
338 if (LOG.isDebugEnabled()) {
339 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
341 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
344 final Throwable[] suppressed = sourceEx.getSuppressed();
345 if (suppressed.length > 0) {
346 LOG.error("{} additional errors reported:", suppressed.length);
349 for (final Throwable t : suppressed) {
350 LOG.error("Error {}: {}", count, t.getMessage());
357 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
358 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
360 buildFailure.addSuppressed(sourceEx);
366 @SuppressWarnings("checkstyle:illegalCatch")
367 private void completePhaseActions() throws ReactorException {
368 checkState(currentPhase != null);
369 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
370 if (!libSources.isEmpty()) {
371 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
372 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
373 + "but current phase was %s", currentPhase);
374 sourcesToProgress.addAll(libSources);
377 boolean progressing = true;
378 while (progressing) {
379 // We reset progressing to false.
381 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
382 while (currentSource.hasNext()) {
383 final SourceSpecificContext nextSourceCtx = currentSource.next();
385 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
386 switch (sourceProgress) {
388 currentSource.remove();
389 // we were able to make progress in computation
399 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
401 } catch (final RuntimeException ex) {
402 throw propagateException(nextSourceCtx, ex);
407 if (!libSources.isEmpty()) {
408 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
409 sources.addAll(requiredLibs);
410 libSources = ImmutableSet.of();
412 * We want to report errors of relevant sources only, so any others can
415 sourcesToProgress.retainAll(sources);
418 if (!sourcesToProgress.isEmpty()) {
419 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
420 if (buildFailure != null) {
426 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
427 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
428 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
429 + " but current phase was %s", currentPhase);
430 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
431 String::compareTo, Revision::compare);
432 for (final SourceSpecificContext libSource : libSources) {
433 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
434 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
437 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
438 for (final SourceSpecificContext source : sources) {
439 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
440 removeConflictingLibSources(source, requiredLibs);
445 private void collectRequiredSourcesFromLib(
446 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
447 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
448 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
449 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
450 if (libSource != null && requiredLibs.add(libSource)) {
451 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
456 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
457 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
458 return requiredSource.getRevision().isPresent()
459 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
460 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
463 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
464 SourceSpecificContext> sourceMap) {
465 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
468 // removes required library sources which would cause namespace/name conflict with one of the main sources
469 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
470 // and the same parent module or submodule is added as one of the library sources.
471 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
472 // as its argument and the same dir is specified as one of the library dirs through -p option).
473 private static void removeConflictingLibSources(final SourceSpecificContext source,
474 final Set<SourceSpecificContext> requiredLibs) {
475 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
476 while (requiredLibsIter.hasNext()) {
477 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
478 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
479 requiredLibsIter.remove();
484 private void endPhase(final ModelProcessingPhase phase) {
485 checkState(currentPhase == phase);
486 finishedPhase = currentPhase;
487 LOG.debug("Global phase {} finished", phase);
490 Set<SourceSpecificContext> getSources() {
494 public Set<YangVersion> getSupportedVersions() {
495 return supportedVersions;
498 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
499 mutableStatementsToSeal.add(mutableStatement);
502 void sealMutableStatements() {
503 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
504 mutableStatement.seal();
506 mutableStatementsToSeal.clear();