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.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.base.Verify;
16 import com.google.common.collect.HashBasedTable;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.ImmutableSetMultimap;
20 import com.google.common.collect.SetMultimap;
21 import com.google.common.collect.Table;
22 import com.google.common.collect.TreeBasedTable;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.List;
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.yang.common.Empty;
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.UnresolvedQName.Unqualified;
40 import org.opendaylight.yangtools.yang.common.YangVersion;
41 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
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.meta.StmtContext;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
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.validation.ValidationBundles;
62 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles.ValidationBundleType;
63 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
68 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
70 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
71 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
72 ModelProcessingPhase.SOURCE_LINKAGE,
73 ModelProcessingPhase.STATEMENT_DEFINITION,
74 ModelProcessingPhase.FULL_DECLARATION,
75 ModelProcessingPhase.EFFECTIVE_MODEL
78 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
79 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
80 private final Map<ParserNamespace<?, ?>, NamespaceBehaviourWithListeners<?, ?>> supportedNamespaces =
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(ValidationBundles.NAMESPACE, 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(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), ImmutableSet.copyOf(supportedFeatures));
119 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
120 addToNamespace(ParserNamespaces.MODULES_DEVIATED_BY, 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> NamespaceBehaviourWithListeners<K, V> getNamespaceBehaviour(final ParserNamespace<K, V> type) {
141 NamespaceBehaviourWithListeners<?, ?> potential = supportedNamespaces.get(type);
142 if (potential == null) {
143 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getNamespaceBehaviour(type);
144 if (potentialRaw != null) {
145 potential = createNamespaceContext(potentialRaw);
146 supportedNamespaces.put(type, potential);
148 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
153 Verify.verify(type.equals(potential.getIdentifier()));
155 * Safe cast, previous checkState checks equivalence of key from which
156 * type argument are derived
158 return (NamespaceBehaviourWithListeners<K, V>) potential;
161 @SuppressWarnings({ "unchecked", "rawtypes" })
162 private <K, V> NamespaceBehaviourWithListeners<K, V> createNamespaceContext(
163 final NamespaceBehaviour<K, V> potentialRaw) {
164 if (potentialRaw instanceof DerivedNamespaceBehaviour derived) {
165 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(derived);
166 getNamespaceBehaviour(derived.getDerivedFrom()).addDerivedNamespace(derivedContext);
167 return derivedContext;
169 return new SimpleNamespaceContext<>(potentialRaw);
172 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
173 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
174 if (potential == null) {
175 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getStatementDefinition(version, name);
176 if (potentialRaw != null) {
177 potential = new StatementDefinitionContext<>(potentialRaw);
178 definitions.put(version, name, potential);
184 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
185 return modelDefinedStmtDefs.get(name);
188 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
189 modelDefinedStmtDefs.put(name, def);
192 private void executePhases() throws ReactorException {
193 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
195 loadPhaseStatements();
196 completePhaseActions();
201 ReactorDeclaredModel build() throws ReactorException {
206 EffectiveSchemaContext buildEffective() throws ReactorException {
208 return transformEffective();
211 private ReactorDeclaredModel transform() {
212 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
213 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
214 for (final SourceSpecificContext source : sources) {
215 rootStatements.add(source.getRoot().declared());
217 return new ReactorDeclaredModel(rootStatements);
220 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
221 final RuntimeException cause) throws SomeModifiersUnresolvedException {
222 final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
223 if (!(cause instanceof SourceException)) {
225 * This should not be happening as all our processing should provide SourceExceptions.
226 * We will wrap the exception to provide enough information to identify the problematic model,
227 * but also emit a warning so the offending codepath will get fixed.
229 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
233 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
236 private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
237 final QNameModule qNameModule = root.getFromNamespace(ParserNamespaces.MODULECTX_TO_QNAME, root);
238 final Object arg = root.getArgument();
239 verify(arg instanceof Unqualified, "Unexpected argument %s", arg);
241 if (qNameModule != null) {
242 // creates SourceIdentifier for a module
243 return new SourceIdentifier((Unqualified) arg, qNameModule.getRevision().orElse(null));
246 // creates SourceIdentifier for a submodule
247 return new SourceIdentifier((Unqualified) arg,
248 StmtContextUtils.getLatestRevision(root.declaredSubstatements()).orElse(null));
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<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable =
410 TreeBasedTable.create(Unqualified::compareTo, Revision::compare);
411 for (final SourceSpecificContext libSource : libSources) {
412 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
413 libSourcesTable.put(libSourceIdentifier.name(),
414 Optional.ofNullable(libSourceIdentifier.revision()), libSource);
417 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
418 for (final SourceSpecificContext source : sources) {
419 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
420 removeConflictingLibSources(source, requiredLibs);
425 private void collectRequiredSourcesFromLib(
426 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable,
427 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
428 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
429 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
430 if (libSource != null && requiredLibs.add(libSource)) {
431 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
436 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
437 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
438 final var revision = requiredSource.revision();
439 return revision != null ? libSourcesTable.get(requiredSource.name(), Optional.of(revision))
440 : getLatestRevision(libSourcesTable.row(requiredSource.name()));
443 private static SourceSpecificContext getLatestRevision(
444 final SortedMap<Optional<Revision>, SourceSpecificContext> sourceMap) {
445 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
448 // removes required library sources which would cause namespace/name conflict with one of the main sources
449 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
450 // and the same parent module or submodule is added as one of the library sources.
451 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
452 // as its argument and the same dir is specified as one of the library dirs through -p option).
453 private static void removeConflictingLibSources(final SourceSpecificContext source,
454 final Set<SourceSpecificContext> requiredLibs) {
455 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
456 while (requiredLibsIter.hasNext()) {
457 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
458 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
459 requiredLibsIter.remove();
464 private void endPhase(final ModelProcessingPhase phase) {
465 checkState(currentPhase == phase);
466 finishedPhase = currentPhase;
467 LOG.debug("Global phase {} finished", phase);
470 Set<SourceSpecificContext> getSources() {
474 public Set<YangVersion> getSupportedVersions() {
475 return supportedVersions;
478 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
479 mutableStatementsToSeal.add(mutableStatement);
482 void sealMutableStatements() {
483 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
484 mutableStatement.seal();
486 mutableStatementsToSeal.clear();