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.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSetMultimap;
19 import com.google.common.collect.SetMultimap;
20 import com.google.common.collect.Table;
21 import com.google.common.collect.TreeBasedTable;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Objects;
31 import java.util.Optional;
33 import java.util.SortedMap;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.yangtools.util.RecursiveObjectLeaker;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.common.Revision;
39 import org.opendaylight.yangtools.yang.common.YangVersion;
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
43 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
44 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
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 class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
71 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
73 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER =
74 ImmutableList.<ModelProcessingPhase>builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
75 .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
76 .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
78 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
79 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
80 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
81 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
82 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
83 private final Set<SourceSpecificContext> sources = new HashSet<>();
84 private final ImmutableSet<YangVersion> supportedVersions;
85 private final boolean enabledSemanticVersions;
87 private Set<SourceSpecificContext> libSources = new HashSet<>();
88 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
89 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
91 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
92 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation,
93 final StatementParserMode statementParserMode) {
94 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
96 switch (statementParserMode) {
98 enabledSemanticVersions = false;
101 enabledSemanticVersions = true;
104 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
107 for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
108 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
111 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
114 boolean isEnabledSemanticVersioning() {
115 return enabledSemanticVersions;
118 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
119 return supports.get(phase);
122 void addSource(final @NonNull StatementStreamSource source) {
123 sources.add(new SourceSpecificContext(this, source));
126 void addLibSource(final @NonNull StatementStreamSource libSource) {
127 checkState(!isEnabledSemanticVersioning(),
128 "Library sources are not supported in semantic version mode currently.");
129 checkState(currentPhase == ModelProcessingPhase.INIT,
130 "Add library source is allowed in ModelProcessingPhase.INIT only");
131 libSources.add(new SourceSpecificContext(this, libSource));
134 void setSupportedFeatures(final Set<QName> supportedFeatures) {
135 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
136 ImmutableSet.copyOf(supportedFeatures));
139 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
140 addToNs(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
141 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
145 public StorageNodeType getStorageNodeType() {
146 return StorageNodeType.GLOBAL;
150 public NamespaceStorageNode getParentNamespaceStorage() {
155 public NamespaceBehaviour.Registry getBehaviourRegistry() {
160 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
161 final Class<N> type) {
162 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
163 if (potential == null) {
164 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
165 if (potentialRaw != null) {
166 potential = createNamespaceContext(potentialRaw);
167 supportedNamespaces.put(type, potential);
169 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
174 Verify.verify(type.equals(potential.getIdentifier()));
176 * Safe cast, previous checkState checks equivalence of key from which
177 * type argument are derived
179 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
182 @SuppressWarnings({ "unchecked", "rawtypes" })
183 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
184 final NamespaceBehaviour<K, V, N> potentialRaw) {
185 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
186 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
187 (DerivedNamespaceBehaviour) potentialRaw);
188 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
190 return derivedContext;
192 return new SimpleNamespaceContext<>(potentialRaw);
195 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
196 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
197 if (potential == null) {
198 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
200 if (potentialRaw != null) {
201 potential = new StatementDefinitionContext<>(potentialRaw);
202 definitions.put(version, name, potential);
208 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
209 return modelDefinedStmtDefs.get(name);
212 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
213 modelDefinedStmtDefs.put(name, def);
216 private void executePhases() throws ReactorException {
217 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
219 loadPhaseStatements();
220 completePhaseActions();
225 ReactorDeclaredModel build() throws ReactorException {
230 EffectiveSchemaContext buildEffective() throws ReactorException {
232 return transformEffective();
235 private ReactorDeclaredModel transform() {
236 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
237 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
238 for (final SourceSpecificContext source : sources) {
239 rootStatements.add(source.getRoot().buildDeclared());
241 return new ReactorDeclaredModel(rootStatements);
244 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
245 final RuntimeException cause) throws SomeModifiersUnresolvedException {
246 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(source.getRoot());
247 if (!(cause instanceof SourceException)) {
249 * This should not be happening as all our processing should provide SourceExceptions.
250 * We will wrap the exception to provide enough information to identify the problematic model,
251 * but also emit a warning so the offending codepath will get fixed.
253 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
257 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
260 @SuppressWarnings("checkstyle:illegalCatch")
261 private EffectiveSchemaContext transformEffective() throws ReactorException {
262 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
263 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
264 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
267 for (final SourceSpecificContext source : sources) {
268 final RootStatementContext<?, ?, ?> root = source.getRoot();
270 rootStatements.add(root.buildDeclared());
271 rootEffectiveStatements.add(root.buildEffective());
272 } catch (final RuntimeException ex) {
273 throw propagateException(source, ex);
277 RecursiveObjectLeaker.cleanup();
280 sealMutableStatements();
281 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
284 private void startPhase(final ModelProcessingPhase phase) {
285 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
286 startPhaseFor(phase, sources);
287 startPhaseFor(phase, libSources);
289 currentPhase = phase;
290 LOG.debug("Global phase {} started", phase);
293 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
294 for (final SourceSpecificContext source : sources) {
295 source.startPhase(phase);
299 private void loadPhaseStatements() throws ReactorException {
300 checkState(currentPhase != null);
301 loadPhaseStatementsFor(sources);
302 loadPhaseStatementsFor(libSources);
305 @SuppressWarnings("checkstyle:illegalCatch")
306 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
307 for (final SourceSpecificContext source : srcs) {
309 source.loadStatements();
310 } catch (final RuntimeException ex) {
311 throw propagateException(source, ex);
316 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
317 boolean addedCause = false;
318 SomeModifiersUnresolvedException buildFailure = null;
319 for (final SourceSpecificContext failedSource : sourcesToProgress) {
320 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
321 if (optSourceEx.isEmpty()) {
325 final SourceException sourceEx = optSourceEx.get();
326 // Workaround for broken logging implementations which ignore
327 // suppressed exceptions
328 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
329 if (LOG.isDebugEnabled()) {
330 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
332 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
335 final Throwable[] suppressed = sourceEx.getSuppressed();
336 if (suppressed.length > 0) {
337 LOG.error("{} additional errors reported:", suppressed.length);
340 for (final Throwable t : suppressed) {
341 LOG.error("Error {}: {}", count, t.getMessage());
348 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(failedSource.getRoot());
349 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
351 buildFailure.addSuppressed(sourceEx);
357 @SuppressWarnings("checkstyle:illegalCatch")
358 private void completePhaseActions() throws ReactorException {
359 checkState(currentPhase != null);
360 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
361 if (!libSources.isEmpty()) {
362 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
363 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
364 + "but current phase was %s", currentPhase);
365 sourcesToProgress.addAll(libSources);
368 boolean progressing = true;
369 while (progressing) {
370 // We reset progressing to false.
372 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
373 while (currentSource.hasNext()) {
374 final SourceSpecificContext nextSourceCtx = currentSource.next();
376 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
377 switch (sourceProgress) {
379 currentSource.remove();
380 // we were able to make progress in computation
390 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
392 } catch (final RuntimeException ex) {
393 throw propagateException(nextSourceCtx, ex);
398 if (!libSources.isEmpty()) {
399 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
400 sources.addAll(requiredLibs);
401 libSources = ImmutableSet.of();
403 * We want to report errors of relevant sources only, so any others can
406 sourcesToProgress.retainAll(sources);
409 if (!sourcesToProgress.isEmpty()) {
410 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
411 if (buildFailure != null) {
417 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
418 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
419 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
420 + " but current phase was %s", currentPhase);
421 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
422 String::compareTo, Revision::compare);
423 for (final SourceSpecificContext libSource : libSources) {
424 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
425 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
428 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
429 for (final SourceSpecificContext source : sources) {
430 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
431 removeConflictingLibSources(source, requiredLibs);
436 private void collectRequiredSourcesFromLib(
437 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
438 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
439 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
440 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
441 if (libSource != null && requiredLibs.add(libSource)) {
442 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
447 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
448 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
449 return requiredSource.getRevision().isPresent()
450 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
451 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
454 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
455 SourceSpecificContext> sourceMap) {
456 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
459 // removes required library sources which would cause namespace/name conflict with one of the main sources
460 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
461 // and the same parent module or submodule is added as one of the library sources.
462 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
463 // as its argument and the same dir is specified as one of the library dirs through -p option).
464 private static void removeConflictingLibSources(final SourceSpecificContext source,
465 final Set<SourceSpecificContext> requiredLibs) {
466 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
467 while (requiredLibsIter.hasNext()) {
468 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
469 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
470 requiredLibsIter.remove();
475 private void endPhase(final ModelProcessingPhase phase) {
476 checkState(currentPhase == phase);
477 finishedPhase = currentPhase;
478 LOG.debug("Global phase {} finished", phase);
481 Set<SourceSpecificContext> getSources() {
485 public Set<YangVersion> getSupportedVersions() {
486 return supportedVersions;
489 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
490 mutableStatementsToSeal.add(mutableStatement);
493 void sealMutableStatements() {
494 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
495 mutableStatement.seal();
497 mutableStatementsToSeal.clear();