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.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.opendaylight.yangtools.yang.common.Empty;
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.UnresolvedQName.Unqualified;
37 import org.opendaylight.yangtools.yang.common.YangVersion;
38 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
39 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.api.stmt.FeatureSet;
42 import org.opendaylight.yangtools.yang.parser.spi.ParserNamespaces;
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.NamespaceNotAvailableException;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceStorage.GlobalStorage;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
52 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
53 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles;
54 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles.ValidationBundleType;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 final class BuildGlobalContext extends AbstractNamespaceStorage implements GlobalStorage {
60 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
62 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
63 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
64 ModelProcessingPhase.SOURCE_LINKAGE,
65 ModelProcessingPhase.STATEMENT_DEFINITION,
66 ModelProcessingPhase.FULL_DECLARATION,
67 ModelProcessingPhase.EFFECTIVE_MODEL
70 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
71 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
72 private final Map<ParserNamespace<?, ?>, BehaviourNamespaceAccess<?, ?>> supportedNamespaces = new HashMap<>();
73 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
74 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
75 private final Set<SourceSpecificContext> sources = new HashSet<>();
76 private final ImmutableSet<YangVersion> supportedVersions;
78 private Set<SourceSpecificContext> libSources = new HashSet<>();
79 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
80 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
82 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
83 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation) {
84 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
86 final var access = accessNamespace(ValidationBundles.NAMESPACE);
87 for (var validationBundle : supportedValidation.entrySet()) {
88 access.valueTo(this, validationBundle.getKey(), validationBundle.getValue());
91 supportedVersions = ImmutableSet.copyOf(
92 verifyNotNull(supports.get(ModelProcessingPhase.INIT)).getSupportedVersions());
95 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
96 return supports.get(phase);
99 void addSource(final StatementStreamSource source) {
100 sources.add(new SourceSpecificContext(this, source));
103 void addLibSource(final StatementStreamSource libSource) {
104 checkState(currentPhase == ModelProcessingPhase.INIT,
105 "Add library source is allowed in ModelProcessingPhase.INIT only");
106 libSources.add(new SourceSpecificContext(this, libSource));
109 void setSupportedFeatures(final FeatureSet supportedFeatures) {
110 addToNamespace(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), requireNonNull(supportedFeatures));
113 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
114 addToNamespace(ParserNamespaces.MODULES_DEVIATED_BY, Empty.value(),
115 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
119 <K, V> BehaviourNamespaceAccess<K, V> accessNamespace(final ParserNamespace<K, V> namespace) {
120 @SuppressWarnings("unchecked")
121 final var existing = (BehaviourNamespaceAccess<K, V>) supportedNamespaces.get(namespace);
122 if (existing != null) {
126 final var behaviour = verifyNotNull(supports.get(currentPhase), "No support for phase %s", currentPhase)
127 .namespaceBehaviourOf(namespace);
128 if (behaviour == null) {
129 throw new NamespaceNotAvailableException(
130 "Namespace " + namespace + " is not available in phase " + currentPhase);
133 final var created = new BehaviourNamespaceAccess<>(this, behaviour);
134 supportedNamespaces.put(namespace, created);
138 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
139 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
140 if (potential == null) {
141 final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getStatementDefinition(version, name);
142 if (potentialRaw != null) {
143 potential = new StatementDefinitionContext<>(potentialRaw);
144 definitions.put(version, name, potential);
150 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
151 return modelDefinedStmtDefs.get(name);
154 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
155 modelDefinedStmtDefs.put(name, def);
158 private void executePhases() throws ReactorException {
159 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
161 loadPhaseStatements();
162 completePhaseActions();
167 ReactorDeclaredModel build() throws ReactorException {
172 EffectiveSchemaContext buildEffective() throws ReactorException {
174 return transformEffective();
177 private ReactorDeclaredModel transform() {
178 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
179 final var rootStatements = new ArrayList<DeclaredStatement<?>>(sources.size());
180 for (var source : sources) {
181 rootStatements.add(source.declaredRoot());
183 return new ReactorDeclaredModel(rootStatements);
186 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
187 final RuntimeException cause) throws SomeModifiersUnresolvedException {
188 final SourceIdentifier sourceId = source.identifySource();
189 if (!(cause instanceof SourceException)) {
191 * This should not be happening as all our processing should provide SourceExceptions.
192 * We will wrap the exception to provide enough information to identify the problematic model,
193 * but also emit a warning so the offending codepath will get fixed.
195 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
199 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
202 @SuppressWarnings("checkstyle:illegalCatch")
203 private EffectiveSchemaContext transformEffective() throws ReactorException {
204 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
205 final var rootStatements = new ArrayList<DeclaredStatement<?>>(sources.size());
206 final var rootEffectiveStatements = new ArrayList<EffectiveStatement<?, ?>>(sources.size());
208 for (var source : sources) {
210 rootStatements.add(source.declaredRoot());
211 rootEffectiveStatements.add(source.effectiveRoot());
212 } catch (final RuntimeException ex) {
213 throw propagateException(source, ex);
217 sealMutableStatements();
218 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
221 private void startPhase(final ModelProcessingPhase phase) {
222 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
223 startPhaseFor(phase, sources);
224 startPhaseFor(phase, libSources);
226 currentPhase = phase;
227 LOG.debug("Global phase {} started", phase);
230 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
231 for (final SourceSpecificContext source : sources) {
232 source.startPhase(phase);
236 private void loadPhaseStatements() throws ReactorException {
237 checkState(currentPhase != null);
238 loadPhaseStatementsFor(sources);
239 loadPhaseStatementsFor(libSources);
242 @SuppressWarnings("checkstyle:illegalCatch")
243 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
244 for (final SourceSpecificContext source : srcs) {
246 source.loadStatements();
247 } catch (final RuntimeException ex) {
248 throw propagateException(source, ex);
253 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
254 boolean addedCause = false;
255 SomeModifiersUnresolvedException buildFailure = null;
256 for (final SourceSpecificContext failedSource : sourcesToProgress) {
257 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
258 if (optSourceEx.isEmpty()) {
262 final SourceException sourceEx = optSourceEx.orElseThrow();
263 // Workaround for broken logging implementations which ignore
264 // suppressed exceptions
265 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
266 if (LOG.isDebugEnabled()) {
267 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
269 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
272 final Throwable[] suppressed = sourceEx.getSuppressed();
273 if (suppressed.length > 0) {
274 LOG.error("{} additional errors reported:", suppressed.length);
277 for (final Throwable t : suppressed) {
278 LOG.error("Error {}: {}", count, t.getMessage());
285 final SourceIdentifier sourceId = failedSource.identifySource();
286 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
288 buildFailure.addSuppressed(sourceEx);
294 @SuppressWarnings("checkstyle:illegalCatch")
295 private void completePhaseActions() throws ReactorException {
296 checkState(currentPhase != null);
297 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
298 if (!libSources.isEmpty()) {
299 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
300 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
301 + "but current phase was %s", currentPhase);
302 sourcesToProgress.addAll(libSources);
305 boolean progressing = true;
306 while (progressing) {
307 // We reset progressing to false.
309 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
310 while (currentSource.hasNext()) {
311 final SourceSpecificContext nextSourceCtx = currentSource.next();
313 final PhaseCompletionProgress sourceProgress =
314 nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
315 switch (sourceProgress) {
317 currentSource.remove();
318 // we were able to make progress in computation
328 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
330 } catch (final RuntimeException ex) {
331 throw propagateException(nextSourceCtx, ex);
336 if (!libSources.isEmpty()) {
337 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
338 sources.addAll(requiredLibs);
339 libSources = ImmutableSet.of();
341 * We want to report errors of relevant sources only, so any others can
344 sourcesToProgress.retainAll(sources);
347 if (!sourcesToProgress.isEmpty()) {
348 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
349 if (buildFailure != null) {
355 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
356 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
357 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
358 + " but current phase was %s", currentPhase);
359 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable =
360 TreeBasedTable.create(Unqualified::compareTo, Revision::compare);
361 for (final SourceSpecificContext libSource : libSources) {
362 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
363 libSourcesTable.put(libSourceIdentifier.name(),
364 Optional.ofNullable(libSourceIdentifier.revision()), libSource);
367 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
368 for (final SourceSpecificContext source : sources) {
369 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
370 removeConflictingLibSources(source, requiredLibs);
375 private void collectRequiredSourcesFromLib(
376 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable,
377 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
378 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
379 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
380 if (libSource != null && requiredLibs.add(libSource)) {
381 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
386 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
387 final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
388 final var revision = requiredSource.revision();
389 return revision != null ? libSourcesTable.get(requiredSource.name(), Optional.of(revision))
390 : getLatestRevision(libSourcesTable.row(requiredSource.name()));
393 private static SourceSpecificContext getLatestRevision(
394 final SortedMap<Optional<Revision>, SourceSpecificContext> sourceMap) {
395 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
398 // removes required library sources which would cause namespace/name conflict with one of the main sources
399 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
400 // and the same parent module or submodule is added as one of the library sources.
401 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
402 // as its argument and the same dir is specified as one of the library dirs through -p option).
403 private static void removeConflictingLibSources(final SourceSpecificContext source,
404 final Set<SourceSpecificContext> requiredLibs) {
405 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
406 while (requiredLibsIter.hasNext()) {
407 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
408 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
409 requiredLibsIter.remove();
414 private void endPhase(final ModelProcessingPhase phase) {
415 checkState(currentPhase == phase);
416 finishedPhase = currentPhase;
417 LOG.debug("Global phase {} finished", phase);
420 Set<SourceSpecificContext> getSources() {
424 public Set<YangVersion> getSupportedVersions() {
425 return supportedVersions;
428 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
429 mutableStatementsToSeal.add(mutableStatement);
432 void sealMutableStatements() {
433 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
434 mutableStatement.seal();
436 mutableStatementsToSeal.clear();