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.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.eclipse.jdt.annotation.NonNull;
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.YangVersion;
37 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
38 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
56 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
57 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
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.source.SupportedFeaturesNamespace.SupportedFeatures;
63 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
70 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
72 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
73 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
74 ModelProcessingPhase.SOURCE_LINKAGE,
75 ModelProcessingPhase.STATEMENT_DEFINITION,
76 ModelProcessingPhase.FULL_DECLARATION,
77 ModelProcessingPhase.EFFECTIVE_MODEL
80 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
81 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
82 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
83 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
84 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
85 private final Set<SourceSpecificContext> sources = new HashSet<>();
86 private final ImmutableSet<YangVersion> supportedVersions;
88 private Set<SourceSpecificContext> libSources = new HashSet<>();
89 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
90 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
92 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
93 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation) {
94 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
96 addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
98 this.supportedVersions = ImmutableSet.copyOf(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, SupportedFeatures.SUPPORTED_FEATURES,
117 ImmutableSet.copyOf(supportedFeatures));
120 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
121 addToNamespace(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
122 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
126 public StorageNodeType getStorageNodeType() {
127 return StorageNodeType.GLOBAL;
131 public NamespaceStorageNode getParentNamespaceStorage() {
136 public NamespaceBehaviour.Registry getBehaviourRegistry() {
141 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
142 final Class<N> type) {
143 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
144 if (potential == null) {
145 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
146 if (potentialRaw != null) {
147 potential = createNamespaceContext(potentialRaw);
148 supportedNamespaces.put(type, potential);
150 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
155 Verify.verify(type.equals(potential.getIdentifier()));
157 * Safe cast, previous checkState checks equivalence of key from which
158 * type argument are derived
160 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
163 @SuppressWarnings({ "unchecked", "rawtypes" })
164 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
165 final NamespaceBehaviour<K, V, N> potentialRaw) {
166 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
167 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
168 (DerivedNamespaceBehaviour) potentialRaw);
169 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
171 return derivedContext;
173 return new SimpleNamespaceContext<>(potentialRaw);
176 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
177 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
178 if (potential == null) {
179 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
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 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
219 for (final SourceSpecificContext source : sources) {
220 rootStatements.add(source.getRoot().declared());
222 return new ReactorDeclaredModel(rootStatements);
225 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
226 final RuntimeException cause) throws SomeModifiersUnresolvedException {
227 final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
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 private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
242 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
243 final String arg = root.getRawArgument();
244 if (qNameModule != null) {
245 // creates SourceIdentifier for a module
246 return RevisionSourceIdentifier.create(arg, qNameModule.getRevision());
249 // creates SourceIdentifier for a submodule
250 return RevisionSourceIdentifier.create(arg, StmtContextUtils.getLatestRevision(root.declaredSubstatements()));
253 @SuppressWarnings("checkstyle:illegalCatch")
254 private EffectiveSchemaContext transformEffective() throws ReactorException {
255 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
256 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
257 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
259 for (final SourceSpecificContext source : sources) {
260 final RootStatementContext<?, ?, ?> root = source.getRoot();
262 rootStatements.add(root.declared());
263 rootEffectiveStatements.add(root.buildEffective());
264 } catch (final RuntimeException ex) {
265 throw propagateException(source, ex);
269 sealMutableStatements();
270 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
273 private void startPhase(final ModelProcessingPhase phase) {
274 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
275 startPhaseFor(phase, sources);
276 startPhaseFor(phase, libSources);
278 currentPhase = phase;
279 LOG.debug("Global phase {} started", phase);
282 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
283 for (final SourceSpecificContext source : sources) {
284 source.startPhase(phase);
288 private void loadPhaseStatements() throws ReactorException {
289 checkState(currentPhase != null);
290 loadPhaseStatementsFor(sources);
291 loadPhaseStatementsFor(libSources);
294 @SuppressWarnings("checkstyle:illegalCatch")
295 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
296 for (final SourceSpecificContext source : srcs) {
298 source.loadStatements();
299 } catch (final RuntimeException ex) {
300 throw propagateException(source, ex);
305 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
306 boolean addedCause = false;
307 SomeModifiersUnresolvedException buildFailure = null;
308 for (final SourceSpecificContext failedSource : sourcesToProgress) {
309 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
310 if (optSourceEx.isEmpty()) {
314 final SourceException sourceEx = optSourceEx.get();
315 // Workaround for broken logging implementations which ignore
316 // suppressed exceptions
317 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
318 if (LOG.isDebugEnabled()) {
319 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
321 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
324 final Throwable[] suppressed = sourceEx.getSuppressed();
325 if (suppressed.length > 0) {
326 LOG.error("{} additional errors reported:", suppressed.length);
329 for (final Throwable t : suppressed) {
330 LOG.error("Error {}: {}", count, t.getMessage());
337 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
338 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
340 buildFailure.addSuppressed(sourceEx);
346 @SuppressWarnings("checkstyle:illegalCatch")
347 private void completePhaseActions() throws ReactorException {
348 checkState(currentPhase != null);
349 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
350 if (!libSources.isEmpty()) {
351 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
352 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
353 + "but current phase was %s", currentPhase);
354 sourcesToProgress.addAll(libSources);
357 boolean progressing = true;
358 while (progressing) {
359 // We reset progressing to false.
361 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
362 while (currentSource.hasNext()) {
363 final SourceSpecificContext nextSourceCtx = currentSource.next();
365 final PhaseCompletionProgress sourceProgress =
366 nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
367 switch (sourceProgress) {
369 currentSource.remove();
370 // we were able to make progress in computation
380 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
382 } catch (final RuntimeException ex) {
383 throw propagateException(nextSourceCtx, ex);
388 if (!libSources.isEmpty()) {
389 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
390 sources.addAll(requiredLibs);
391 libSources = ImmutableSet.of();
393 * We want to report errors of relevant sources only, so any others can
396 sourcesToProgress.retainAll(sources);
399 if (!sourcesToProgress.isEmpty()) {
400 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
401 if (buildFailure != null) {
407 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
408 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
409 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
410 + " but current phase was %s", currentPhase);
411 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
412 String::compareTo, Revision::compare);
413 for (final SourceSpecificContext libSource : libSources) {
414 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
415 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
418 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
419 for (final SourceSpecificContext source : sources) {
420 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
421 removeConflictingLibSources(source, requiredLibs);
426 private void collectRequiredSourcesFromLib(
427 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
428 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
429 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
430 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
431 if (libSource != null && requiredLibs.add(libSource)) {
432 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
437 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
438 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
439 return requiredSource.getRevision().isPresent()
440 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
441 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
444 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
445 SourceSpecificContext> sourceMap) {
446 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
449 // removes required library sources which would cause namespace/name conflict with one of the main sources
450 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
451 // and the same parent module or submodule is added as one of the library sources.
452 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
453 // as its argument and the same dir is specified as one of the library dirs through -p option).
454 private static void removeConflictingLibSources(final SourceSpecificContext source,
455 final Set<SourceSpecificContext> requiredLibs) {
456 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
457 while (requiredLibsIter.hasNext()) {
458 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
459 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
460 requiredLibsIter.remove();
465 private void endPhase(final ModelProcessingPhase phase) {
466 checkState(currentPhase == phase);
467 finishedPhase = currentPhase;
468 LOG.debug("Global phase {} finished", phase);
471 Set<SourceSpecificContext> getSources() {
475 public Set<YangVersion> getSupportedVersions() {
476 return supportedVersions;
479 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
480 mutableStatementsToSeal.add(mutableStatement);
483 void sealMutableStatements() {
484 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
485 mutableStatement.seal();
487 mutableStatementsToSeal.clear();