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 com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.base.Verify;
15 import com.google.common.collect.HashBasedTable;
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.Objects;
30 import java.util.Optional;
32 import java.util.SortedMap;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.yangtools.yang.common.Empty;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.common.Revision;
38 import org.opendaylight.yangtools.yang.common.YangVersion;
39 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
40 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
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.SourceException;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
61 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
62 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
63 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
64 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
69 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
71 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
72 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
73 ModelProcessingPhase.SOURCE_LINKAGE,
74 ModelProcessingPhase.STATEMENT_DEFINITION,
75 ModelProcessingPhase.FULL_DECLARATION,
76 ModelProcessingPhase.EFFECTIVE_MODEL
79 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
80 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
81 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
82 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
83 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
84 private final Set<SourceSpecificContext> sources = new HashSet<>();
85 private final ImmutableSet<YangVersion> supportedVersions;
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 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
95 addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
97 supportedVersions = ImmutableSet.copyOf(
98 verifyNotNull(supports.get(ModelProcessingPhase.INIT)).getSupportedVersions());
101 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
102 return supports.get(phase);
105 void addSource(final @NonNull StatementStreamSource source) {
106 sources.add(new SourceSpecificContext(this, source));
109 void addLibSource(final @NonNull StatementStreamSource libSource) {
110 checkState(currentPhase == ModelProcessingPhase.INIT,
111 "Add library source is allowed in ModelProcessingPhase.INIT only");
112 libSources.add(new SourceSpecificContext(this, libSource));
115 void setSupportedFeatures(final Set<QName> supportedFeatures) {
116 addToNamespace(SupportedFeaturesNamespace.class, Empty.value(), ImmutableSet.copyOf(supportedFeatures));
119 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
120 addToNamespace(ModulesDeviatedByModules.class, Empty.value(),
121 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
125 public StorageNodeType getStorageNodeType() {
126 return StorageNodeType.GLOBAL;
130 public NamespaceStorageNode getParentNamespaceStorage() {
135 public NamespaceBehaviour.Registry getBehaviourRegistry() {
140 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
141 final Class<N> type) {
142 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
143 if (potential == null) {
144 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getNamespaceBehaviour(type);
145 if (potentialRaw != null) {
146 potential = createNamespaceContext(potentialRaw);
147 supportedNamespaces.put(type, potential);
149 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
154 Verify.verify(type.equals(potential.getIdentifier()));
156 * Safe cast, previous checkState checks equivalence of key from which
157 * type argument are derived
159 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
162 @SuppressWarnings({ "unchecked", "rawtypes" })
163 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
164 final NamespaceBehaviour<K, V, N> potentialRaw) {
165 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
166 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
167 (DerivedNamespaceBehaviour) potentialRaw);
168 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
170 return derivedContext;
172 return new SimpleNamespaceContext<>(potentialRaw);
175 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
176 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
177 if (potential == null) {
178 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getStatementDefinition(version, name);
179 if (potentialRaw != null) {
180 potential = new StatementDefinitionContext<>(potentialRaw);
181 definitions.put(version, name, potential);
187 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
188 return modelDefinedStmtDefs.get(name);
191 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
192 modelDefinedStmtDefs.put(name, def);
195 private void executePhases() throws ReactorException {
196 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
198 loadPhaseStatements();
199 completePhaseActions();
204 ReactorDeclaredModel build() throws ReactorException {
209 EffectiveSchemaContext buildEffective() throws ReactorException {
211 return transformEffective();
214 private ReactorDeclaredModel transform() {
215 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
216 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
217 for (final SourceSpecificContext source : sources) {
218 rootStatements.add(source.getRoot().declared());
220 return new ReactorDeclaredModel(rootStatements);
223 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
224 final RuntimeException cause) throws SomeModifiersUnresolvedException {
225 final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
226 if (!(cause instanceof SourceException)) {
228 * This should not be happening as all our processing should provide SourceExceptions.
229 * We will wrap the exception to provide enough information to identify the problematic model,
230 * but also emit a warning so the offending codepath will get fixed.
232 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
236 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
239 private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
240 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
241 final String arg = root.getRawArgument();
242 if (qNameModule != null) {
243 // creates SourceIdentifier for a module
244 return RevisionSourceIdentifier.create(arg, qNameModule.getRevision());
247 // creates SourceIdentifier for a submodule
248 return RevisionSourceIdentifier.create(arg, StmtContextUtils.getLatestRevision(root.declaredSubstatements()));
251 @SuppressWarnings("checkstyle:illegalCatch")
252 private EffectiveSchemaContext transformEffective() throws ReactorException {
253 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
254 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
255 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
257 for (final SourceSpecificContext source : sources) {
258 final RootStatementContext<?, ?, ?> root = source.getRoot();
260 rootStatements.add(root.declared());
261 rootEffectiveStatements.add(root.buildEffective());
262 } catch (final RuntimeException ex) {
263 throw propagateException(source, ex);
267 sealMutableStatements();
268 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
271 private void startPhase(final ModelProcessingPhase phase) {
272 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
273 startPhaseFor(phase, sources);
274 startPhaseFor(phase, libSources);
276 currentPhase = phase;
277 LOG.debug("Global phase {} started", phase);
280 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
281 for (final SourceSpecificContext source : sources) {
282 source.startPhase(phase);
286 private void loadPhaseStatements() throws ReactorException {
287 checkState(currentPhase != null);
288 loadPhaseStatementsFor(sources);
289 loadPhaseStatementsFor(libSources);
292 @SuppressWarnings("checkstyle:illegalCatch")
293 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
294 for (final SourceSpecificContext source : srcs) {
296 source.loadStatements();
297 } catch (final RuntimeException ex) {
298 throw propagateException(source, ex);
303 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
304 boolean addedCause = false;
305 SomeModifiersUnresolvedException buildFailure = null;
306 for (final SourceSpecificContext failedSource : sourcesToProgress) {
307 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
308 if (optSourceEx.isEmpty()) {
312 final SourceException sourceEx = optSourceEx.get();
313 // Workaround for broken logging implementations which ignore
314 // suppressed exceptions
315 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
316 if (LOG.isDebugEnabled()) {
317 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
319 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
322 final Throwable[] suppressed = sourceEx.getSuppressed();
323 if (suppressed.length > 0) {
324 LOG.error("{} additional errors reported:", suppressed.length);
327 for (final Throwable t : suppressed) {
328 LOG.error("Error {}: {}", count, t.getMessage());
335 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
336 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
338 buildFailure.addSuppressed(sourceEx);
344 @SuppressWarnings("checkstyle:illegalCatch")
345 private void completePhaseActions() throws ReactorException {
346 checkState(currentPhase != null);
347 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
348 if (!libSources.isEmpty()) {
349 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
350 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
351 + "but current phase was %s", currentPhase);
352 sourcesToProgress.addAll(libSources);
355 boolean progressing = true;
356 while (progressing) {
357 // We reset progressing to false.
359 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
360 while (currentSource.hasNext()) {
361 final SourceSpecificContext nextSourceCtx = currentSource.next();
363 final PhaseCompletionProgress sourceProgress =
364 nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
365 switch (sourceProgress) {
367 currentSource.remove();
368 // we were able to make progress in computation
378 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
380 } catch (final RuntimeException ex) {
381 throw propagateException(nextSourceCtx, ex);
386 if (!libSources.isEmpty()) {
387 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
388 sources.addAll(requiredLibs);
389 libSources = ImmutableSet.of();
391 * We want to report errors of relevant sources only, so any others can
394 sourcesToProgress.retainAll(sources);
397 if (!sourcesToProgress.isEmpty()) {
398 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
399 if (buildFailure != null) {
405 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
406 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
407 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
408 + " but current phase was %s", currentPhase);
409 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
410 String::compareTo, Revision::compare);
411 for (final SourceSpecificContext libSource : libSources) {
412 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
413 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
416 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
417 for (final SourceSpecificContext source : sources) {
418 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
419 removeConflictingLibSources(source, requiredLibs);
424 private void collectRequiredSourcesFromLib(
425 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
426 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
427 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
428 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
429 if (libSource != null && requiredLibs.add(libSource)) {
430 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
435 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
436 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
437 return requiredSource.getRevision().isPresent()
438 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
439 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
442 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
443 SourceSpecificContext> sourceMap) {
444 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
447 // removes required library sources which would cause namespace/name conflict with one of the main sources
448 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
449 // and the same parent module or submodule is added as one of the library sources.
450 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
451 // as its argument and the same dir is specified as one of the library dirs through -p option).
452 private static void removeConflictingLibSources(final SourceSpecificContext source,
453 final Set<SourceSpecificContext> requiredLibs) {
454 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
455 while (requiredLibsIter.hasNext()) {
456 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
457 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
458 requiredLibsIter.remove();
463 private void endPhase(final ModelProcessingPhase phase) {
464 checkState(currentPhase == phase);
465 finishedPhase = currentPhase;
466 LOG.debug("Global phase {} finished", phase);
469 Set<SourceSpecificContext> getSources() {
473 public Set<YangVersion> getSupportedVersions() {
474 return supportedVersions;
477 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
478 mutableStatementsToSeal.add(mutableStatement);
481 void sealMutableStatements() {
482 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
483 mutableStatement.seal();
485 mutableStatementsToSeal.clear();