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.api.ImportResolutionMode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
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.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
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.ModulesDeviatedByModules.SupportedModules;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
62 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
64 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
65 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
66 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
71 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
73 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
74 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
75 ModelProcessingPhase.SOURCE_LINKAGE,
76 ModelProcessingPhase.STATEMENT_DEFINITION,
77 ModelProcessingPhase.FULL_DECLARATION,
78 ModelProcessingPhase.EFFECTIVE_MODEL
81 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
82 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
83 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
84 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
85 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
86 private final Set<SourceSpecificContext> sources = new HashSet<>();
87 private final ImmutableSet<YangVersion> supportedVersions;
89 // FIXME: 7.0.0: this flag should really be passed to {Import,Module}StatementSupport's bootstrap to wire the
90 // appropriate behaviour. That requires a change in StatementSupport lifecycle, as statement supports
91 // would no longer be stateless singletons.
92 private final boolean enabledSemanticVersions;
94 private Set<SourceSpecificContext> libSources = new HashSet<>();
95 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
96 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
98 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
99 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation,
100 final ImportResolutionMode statementParserMode) {
101 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
103 switch (statementParserMode) {
105 enabledSemanticVersions = false;
107 case OPENCONFIG_SEMVER:
108 enabledSemanticVersions = true;
111 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
114 addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
116 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
119 boolean isEnabledSemanticVersioning() {
120 return enabledSemanticVersions;
123 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
124 return supports.get(phase);
127 void addSource(final @NonNull StatementStreamSource source) {
128 sources.add(new SourceSpecificContext(this, source));
131 void addLibSource(final @NonNull StatementStreamSource libSource) {
132 checkState(!isEnabledSemanticVersioning(),
133 "Library sources are not supported in semantic version mode currently.");
134 checkState(currentPhase == ModelProcessingPhase.INIT,
135 "Add library source is allowed in ModelProcessingPhase.INIT only");
136 libSources.add(new SourceSpecificContext(this, libSource));
139 void setSupportedFeatures(final Set<QName> supportedFeatures) {
140 addToNamespace(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
141 ImmutableSet.copyOf(supportedFeatures));
144 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
145 addToNamespace(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
146 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
150 public StorageNodeType getStorageNodeType() {
151 return StorageNodeType.GLOBAL;
155 public NamespaceStorageNode getParentNamespaceStorage() {
160 public NamespaceBehaviour.Registry getBehaviourRegistry() {
165 public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
166 final Class<N> type) {
167 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
168 if (potential == null) {
169 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
170 if (potentialRaw != null) {
171 potential = createNamespaceContext(potentialRaw);
172 supportedNamespaces.put(type, potential);
174 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
179 Verify.verify(type.equals(potential.getIdentifier()));
181 * Safe cast, previous checkState checks equivalence of key from which
182 * type argument are derived
184 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
187 @SuppressWarnings({ "unchecked", "rawtypes" })
188 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
189 final NamespaceBehaviour<K, V, N> potentialRaw) {
190 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
191 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
192 (DerivedNamespaceBehaviour) potentialRaw);
193 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
195 return derivedContext;
197 return new SimpleNamespaceContext<>(potentialRaw);
200 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
201 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
202 if (potential == null) {
203 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
205 if (potentialRaw != null) {
206 potential = new StatementDefinitionContext<>(potentialRaw);
207 definitions.put(version, name, potential);
213 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
214 return modelDefinedStmtDefs.get(name);
217 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
218 modelDefinedStmtDefs.put(name, def);
221 private void executePhases() throws ReactorException {
222 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
224 loadPhaseStatements();
225 completePhaseActions();
230 ReactorDeclaredModel build() throws ReactorException {
235 EffectiveSchemaContext buildEffective() throws ReactorException {
237 return transformEffective();
240 private ReactorDeclaredModel transform() {
241 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
242 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
243 for (final SourceSpecificContext source : sources) {
244 rootStatements.add(source.getRoot().declared());
246 return new ReactorDeclaredModel(rootStatements);
249 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
250 final RuntimeException cause) throws SomeModifiersUnresolvedException {
251 final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
252 if (!(cause instanceof SourceException)) {
254 * This should not be happening as all our processing should provide SourceExceptions.
255 * We will wrap the exception to provide enough information to identify the problematic model,
256 * but also emit a warning so the offending codepath will get fixed.
258 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
262 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
265 private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
266 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
267 final String arg = root.getRawArgument();
268 if (qNameModule != null) {
269 // creates SourceIdentifier for a module
270 return RevisionSourceIdentifier.create(arg, qNameModule.getRevision());
273 // creates SourceIdentifier for a submodule
274 return RevisionSourceIdentifier.create(arg, StmtContextUtils.getLatestRevision(root.declaredSubstatements()));
277 @SuppressWarnings("checkstyle:illegalCatch")
278 private EffectiveSchemaContext transformEffective() throws ReactorException {
279 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
280 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
281 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
283 for (final SourceSpecificContext source : sources) {
284 final RootStatementContext<?, ?, ?> root = source.getRoot();
286 rootStatements.add(root.declared());
287 rootEffectiveStatements.add(root.buildEffective());
288 } catch (final RuntimeException ex) {
289 throw propagateException(source, ex);
293 sealMutableStatements();
294 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
297 private void startPhase(final ModelProcessingPhase phase) {
298 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
299 startPhaseFor(phase, sources);
300 startPhaseFor(phase, libSources);
302 currentPhase = phase;
303 LOG.debug("Global phase {} started", phase);
306 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
307 for (final SourceSpecificContext source : sources) {
308 source.startPhase(phase);
312 private void loadPhaseStatements() throws ReactorException {
313 checkState(currentPhase != null);
314 loadPhaseStatementsFor(sources);
315 loadPhaseStatementsFor(libSources);
318 @SuppressWarnings("checkstyle:illegalCatch")
319 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
320 for (final SourceSpecificContext source : srcs) {
322 source.loadStatements();
323 } catch (final RuntimeException ex) {
324 throw propagateException(source, ex);
329 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
330 boolean addedCause = false;
331 SomeModifiersUnresolvedException buildFailure = null;
332 for (final SourceSpecificContext failedSource : sourcesToProgress) {
333 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
334 if (optSourceEx.isEmpty()) {
338 final SourceException sourceEx = optSourceEx.get();
339 // Workaround for broken logging implementations which ignore
340 // suppressed exceptions
341 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
342 if (LOG.isDebugEnabled()) {
343 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
345 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
348 final Throwable[] suppressed = sourceEx.getSuppressed();
349 if (suppressed.length > 0) {
350 LOG.error("{} additional errors reported:", suppressed.length);
353 for (final Throwable t : suppressed) {
354 LOG.error("Error {}: {}", count, t.getMessage());
361 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
362 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
364 buildFailure.addSuppressed(sourceEx);
370 @SuppressWarnings("checkstyle:illegalCatch")
371 private void completePhaseActions() throws ReactorException {
372 checkState(currentPhase != null);
373 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
374 if (!libSources.isEmpty()) {
375 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
376 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
377 + "but current phase was %s", currentPhase);
378 sourcesToProgress.addAll(libSources);
381 boolean progressing = true;
382 while (progressing) {
383 // We reset progressing to false.
385 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
386 while (currentSource.hasNext()) {
387 final SourceSpecificContext nextSourceCtx = currentSource.next();
389 final PhaseCompletionProgress sourceProgress =
390 nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
391 switch (sourceProgress) {
393 currentSource.remove();
394 // we were able to make progress in computation
404 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
406 } catch (final RuntimeException ex) {
407 throw propagateException(nextSourceCtx, ex);
412 if (!libSources.isEmpty()) {
413 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
414 sources.addAll(requiredLibs);
415 libSources = ImmutableSet.of();
417 * We want to report errors of relevant sources only, so any others can
420 sourcesToProgress.retainAll(sources);
423 if (!sourcesToProgress.isEmpty()) {
424 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
425 if (buildFailure != null) {
431 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
432 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
433 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
434 + " but current phase was %s", currentPhase);
435 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
436 String::compareTo, Revision::compare);
437 for (final SourceSpecificContext libSource : libSources) {
438 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
439 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
442 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
443 for (final SourceSpecificContext source : sources) {
444 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
445 removeConflictingLibSources(source, requiredLibs);
450 private void collectRequiredSourcesFromLib(
451 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
452 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
453 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
454 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
455 if (libSource != null && requiredLibs.add(libSource)) {
456 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
461 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
462 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
463 return requiredSource.getRevision().isPresent()
464 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
465 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
468 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
469 SourceSpecificContext> sourceMap) {
470 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
473 // removes required library sources which would cause namespace/name conflict with one of the main sources
474 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
475 // and the same parent module or submodule is added as one of the library sources.
476 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
477 // as its argument and the same dir is specified as one of the library dirs through -p option).
478 private static void removeConflictingLibSources(final SourceSpecificContext source,
479 final Set<SourceSpecificContext> requiredLibs) {
480 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
481 while (requiredLibsIter.hasNext()) {
482 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
483 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
484 requiredLibsIter.remove();
489 private void endPhase(final ModelProcessingPhase phase) {
490 checkState(currentPhase == phase);
491 finishedPhase = currentPhase;
492 LOG.debug("Global phase {} finished", phase);
495 Set<SourceSpecificContext> getSources() {
499 public Set<YangVersion> getSupportedVersions() {
500 return supportedVersions;
503 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
504 mutableStatementsToSeal.add(mutableStatement);
507 void sealMutableStatements() {
508 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
509 mutableStatement.seal();
511 mutableStatementsToSeal.clear();