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.UnresolvedQName.Unqualified;
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.repo.api.FeatureSet;
43 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
44 import org.opendaylight.yangtools.yang.parser.spi.ParserNamespaces;
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.ParserNamespace;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
57 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
59 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles;
60 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles.ValidationBundleType;
61 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
66 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
68 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
69 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
70 ModelProcessingPhase.SOURCE_LINKAGE,
71 ModelProcessingPhase.STATEMENT_DEFINITION,
72 ModelProcessingPhase.FULL_DECLARATION,
73 ModelProcessingPhase.EFFECTIVE_MODEL
76 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
77 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
78 private final Map<ParserNamespace<?, ?>, NamespaceBehaviourWithListeners<?, ?>> supportedNamespaces =
80 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
81 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
82 private final Set<SourceSpecificContext> sources = new HashSet<>();
83 private final ImmutableSet<YangVersion> supportedVersions;
85 private Set<SourceSpecificContext> libSources = new HashSet<>();
86 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
87 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
89 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
90 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation) {
91 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
93 final var behavior = getNamespaceBehaviour(ValidationBundles.NAMESPACE);
94 for (var validationBundle : supportedValidation.entrySet()) {
95 behavior.addTo(this, validationBundle.getKey(), validationBundle.getValue());
98 supportedVersions = ImmutableSet.copyOf(
99 verifyNotNull(supports.get(ModelProcessingPhase.INIT)).getSupportedVersions());
102 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
103 return supports.get(phase);
106 void addSource(final @NonNull StatementStreamSource source) {
107 sources.add(new SourceSpecificContext(this, source));
110 void addLibSource(final @NonNull StatementStreamSource libSource) {
111 checkState(currentPhase == ModelProcessingPhase.INIT,
112 "Add library source is allowed in ModelProcessingPhase.INIT only");
113 libSources.add(new SourceSpecificContext(this, libSource));
116 void setSupportedFeatures(final Set<QName> supportedFeatures) {
117 if (supportedFeatures instanceof FeatureSet) {
118 addToNamespace(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), supportedFeatures);
120 addToNamespace(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), ImmutableSet.copyOf(supportedFeatures));
124 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
125 addToNamespace(ParserNamespaces.MODULES_DEVIATED_BY, Empty.value(),
126 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
130 public StorageNodeType getStorageNodeType() {
131 return StorageNodeType.GLOBAL;
135 public NamespaceStorageNode getParentNamespaceStorage() {
140 Registry getBehaviourRegistry() {
145 public <K, V> NamespaceBehaviourWithListeners<K, V> getNamespaceBehaviour(final ParserNamespace<K, V> type) {
146 NamespaceBehaviourWithListeners<?, ?> potential = supportedNamespaces.get(type);
147 if (potential == null) {
148 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).namespaceBehaviourOf(type);
149 if (potentialRaw != null) {
150 potential = createNamespaceContext(potentialRaw);
151 supportedNamespaces.put(type, potential);
153 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
158 Verify.verify(type.equals(potential.getIdentifier()));
160 * Safe cast, previous checkState checks equivalence of key from which
161 * type argument are derived
163 return (NamespaceBehaviourWithListeners<K, V>) potential;
166 @SuppressWarnings({ "unchecked", "rawtypes" })
167 private <K, V> NamespaceBehaviourWithListeners<K, V> createNamespaceContext(
168 final NamespaceBehaviour<K, V> potentialRaw) {
169 if (potentialRaw instanceof DerivedNamespaceBehaviour derived) {
170 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(derived);
171 getNamespaceBehaviour(derived.getDerivedFrom()).addDerivedNamespace(derivedContext);
172 return derivedContext;
174 return new SimpleNamespaceContext<>(potentialRaw);
177 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
178 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
179 if (potential == null) {
180 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getStatementDefinition(version, name);
181 if (potentialRaw != null) {
182 potential = new StatementDefinitionContext<>(potentialRaw);
183 definitions.put(version, name, potential);
189 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
190 return modelDefinedStmtDefs.get(name);
193 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
194 modelDefinedStmtDefs.put(name, def);
197 private void executePhases() throws ReactorException {
198 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
200 loadPhaseStatements();
201 completePhaseActions();
206 ReactorDeclaredModel build() throws ReactorException {
211 EffectiveSchemaContext buildEffective() throws ReactorException {
213 return transformEffective();
216 private ReactorDeclaredModel transform() {
217 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
218 final var rootStatements = new ArrayList<DeclaredStatement<?>>(sources.size());
219 for (var source : sources) {
220 rootStatements.add(source.declaredRoot());
222 return new ReactorDeclaredModel(rootStatements);
225 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
226 final RuntimeException cause) throws SomeModifiersUnresolvedException {
227 final SourceIdentifier sourceId = source.identifySource();
228 if (!(cause instanceof SourceException)) {
230 * This should not be happening as all our processing should provide SourceExceptions.
231 * We will wrap the exception to provide enough information to identify the problematic model,
232 * but also emit a warning so the offending codepath will get fixed.
234 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
238 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
241 @SuppressWarnings("checkstyle:illegalCatch")
242 private EffectiveSchemaContext transformEffective() throws ReactorException {
243 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
244 final var rootStatements = new ArrayList<DeclaredStatement<?>>(sources.size());
245 final var rootEffectiveStatements = new ArrayList<EffectiveStatement<?, ?>>(sources.size());
247 for (var source : sources) {
249 rootStatements.add(source.declaredRoot());
250 rootEffectiveStatements.add(source.effectiveRoot());
251 } catch (final RuntimeException ex) {
252 throw propagateException(source, ex);
256 sealMutableStatements();
257 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
260 private void startPhase(final ModelProcessingPhase phase) {
261 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
262 startPhaseFor(phase, sources);
263 startPhaseFor(phase, libSources);
265 currentPhase = phase;
266 LOG.debug("Global phase {} started", phase);
269 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
270 for (final SourceSpecificContext source : sources) {
271 source.startPhase(phase);
275 private void loadPhaseStatements() throws ReactorException {
276 checkState(currentPhase != null);
277 loadPhaseStatementsFor(sources);
278 loadPhaseStatementsFor(libSources);
281 @SuppressWarnings("checkstyle:illegalCatch")
282 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
283 for (final SourceSpecificContext source : srcs) {
285 source.loadStatements();
286 } catch (final RuntimeException ex) {
287 throw propagateException(source, ex);
292 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
293 boolean addedCause = false;
294 SomeModifiersUnresolvedException buildFailure = null;
295 for (final SourceSpecificContext failedSource : sourcesToProgress) {
296 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
297 if (optSourceEx.isEmpty()) {
301 final SourceException sourceEx = optSourceEx.get();
302 // Workaround for broken logging implementations which ignore
303 // suppressed exceptions
304 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
305 if (LOG.isDebugEnabled()) {
306 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
308 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
311 final Throwable[] suppressed = sourceEx.getSuppressed();
312 if (suppressed.length > 0) {
313 LOG.error("{} additional errors reported:", suppressed.length);
316 for (final Throwable t : suppressed) {
317 LOG.error("Error {}: {}", count, t.getMessage());
324 final SourceIdentifier sourceId = failedSource.identifySource();
325 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
327 buildFailure.addSuppressed(sourceEx);
333 @SuppressWarnings("checkstyle:illegalCatch")
334 private void completePhaseActions() throws ReactorException {
335 checkState(currentPhase != null);
336 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
337 if (!libSources.isEmpty()) {
338 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
339 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
340 + "but current phase was %s", currentPhase);
341 sourcesToProgress.addAll(libSources);
344 boolean progressing = true;
345 while (progressing) {
346 // We reset progressing to false.
348 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
349 while (currentSource.hasNext()) {
350 final SourceSpecificContext nextSourceCtx = currentSource.next();
352 final PhaseCompletionProgress sourceProgress =
353 nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
354 switch (sourceProgress) {
356 currentSource.remove();
357 // we were able to make progress in computation
367 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
369 } catch (final RuntimeException ex) {
370 throw propagateException(nextSourceCtx, ex);
375 if (!libSources.isEmpty()) {
376 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
377 sources.addAll(requiredLibs);
378 libSources = ImmutableSet.of();
380 * We want to report errors of relevant sources only, so any others can
383 sourcesToProgress.retainAll(sources);
386 if (!sourcesToProgress.isEmpty()) {
387 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
388 if (buildFailure != null) {
394 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
395 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
396 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
397 + " but current phase was %s", currentPhase);
398 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable =
399 TreeBasedTable.create(Unqualified::compareTo, Revision::compare);
400 for (final SourceSpecificContext libSource : libSources) {
401 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
402 libSourcesTable.put(libSourceIdentifier.name(),
403 Optional.ofNullable(libSourceIdentifier.revision()), libSource);
406 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
407 for (final SourceSpecificContext source : sources) {
408 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
409 removeConflictingLibSources(source, requiredLibs);
414 private void collectRequiredSourcesFromLib(
415 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable,
416 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
417 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
418 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
419 if (libSource != null && requiredLibs.add(libSource)) {
420 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
425 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
426 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
427 final var revision = requiredSource.revision();
428 return revision != null ? libSourcesTable.get(requiredSource.name(), Optional.of(revision))
429 : getLatestRevision(libSourcesTable.row(requiredSource.name()));
432 private static SourceSpecificContext getLatestRevision(
433 final SortedMap<Optional<Revision>, SourceSpecificContext> sourceMap) {
434 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
437 // removes required library sources which would cause namespace/name conflict with one of the main sources
438 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
439 // and the same parent module or submodule is added as one of the library sources.
440 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
441 // as its argument and the same dir is specified as one of the library dirs through -p option).
442 private static void removeConflictingLibSources(final SourceSpecificContext source,
443 final Set<SourceSpecificContext> requiredLibs) {
444 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
445 while (requiredLibsIter.hasNext()) {
446 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
447 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
448 requiredLibsIter.remove();
453 private void endPhase(final ModelProcessingPhase phase) {
454 checkState(currentPhase == phase);
455 finishedPhase = currentPhase;
456 LOG.debug("Global phase {} finished", phase);
459 Set<SourceSpecificContext> getSources() {
463 public Set<YangVersion> getSupportedVersions() {
464 return supportedVersions;
467 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
468 mutableStatementsToSeal.add(mutableStatement);
471 void sealMutableStatements() {
472 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
473 mutableStatement.seal();
475 mutableStatementsToSeal.clear();