Fix InvalidRangeConstraintException serializability
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / BuildGlobalContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
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;
27 import java.util.Map;
28 import java.util.Objects;
29 import java.util.Optional;
30 import java.util.Set;
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.model.repo.api.StatementParserMode;
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;
69
70 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
71     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
72
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
79     };
80
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;
88     private final boolean enabledSemanticVersions;
89
90     private Set<SourceSpecificContext> libSources = new HashSet<>();
91     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
92     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
93
94     BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
95             final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation,
96             final StatementParserMode statementParserMode) {
97         this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
98
99         switch (statementParserMode) {
100             case DEFAULT_MODE:
101                 enabledSemanticVersions = false;
102                 break;
103             case SEMVER_MODE:
104                 enabledSemanticVersions = true;
105                 break;
106             default:
107                 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
108         }
109
110         addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
111
112         this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
113     }
114
115     boolean isEnabledSemanticVersioning() {
116         return enabledSemanticVersions;
117     }
118
119     StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
120         return supports.get(phase);
121     }
122
123     void addSource(final @NonNull StatementStreamSource source) {
124         sources.add(new SourceSpecificContext(this, source));
125     }
126
127     void addLibSource(final @NonNull StatementStreamSource libSource) {
128         checkState(!isEnabledSemanticVersioning(),
129             "Library sources are not supported in semantic version mode currently.");
130         checkState(currentPhase == ModelProcessingPhase.INIT,
131                 "Add library source is allowed in ModelProcessingPhase.INIT only");
132         libSources.add(new SourceSpecificContext(this, libSource));
133     }
134
135     void setSupportedFeatures(final Set<QName> supportedFeatures) {
136         addToNamespace(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
137                     ImmutableSet.copyOf(supportedFeatures));
138     }
139
140     void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
141         addToNamespace(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
142                     ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
143     }
144
145     @Override
146     public StorageNodeType getStorageNodeType() {
147         return StorageNodeType.GLOBAL;
148     }
149
150     @Override
151     public NamespaceStorageNode getParentNamespaceStorage() {
152         return null;
153     }
154
155     @Override
156     public NamespaceBehaviour.Registry getBehaviourRegistry() {
157         return this;
158     }
159
160     @Override
161     public <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
162             final Class<N> type) {
163         NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
164         if (potential == null) {
165             final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
166             if (potentialRaw != null) {
167                 potential = createNamespaceContext(potentialRaw);
168                 supportedNamespaces.put(type, potential);
169             } else {
170                 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
171                         + currentPhase);
172             }
173         }
174
175         Verify.verify(type.equals(potential.getIdentifier()));
176         /*
177          * Safe cast, previous checkState checks equivalence of key from which
178          * type argument are derived
179          */
180         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
181     }
182
183     @SuppressWarnings({ "unchecked", "rawtypes" })
184     private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
185             final NamespaceBehaviour<K, V, N> potentialRaw) {
186         if (potentialRaw instanceof DerivedNamespaceBehaviour) {
187             final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
188                     (DerivedNamespaceBehaviour) potentialRaw);
189             getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
190                     derivedContext);
191             return derivedContext;
192         }
193         return new SimpleNamespaceContext<>(potentialRaw);
194     }
195
196     StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
197         StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
198         if (potential == null) {
199             final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
200                     name);
201             if (potentialRaw != null) {
202                 potential = new StatementDefinitionContext<>(potentialRaw);
203                 definitions.put(version, name, potential);
204             }
205         }
206         return potential;
207     }
208
209     StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
210         return modelDefinedStmtDefs.get(name);
211     }
212
213     void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
214         modelDefinedStmtDefs.put(name, def);
215     }
216
217     private void executePhases() throws ReactorException {
218         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
219             startPhase(phase);
220             loadPhaseStatements();
221             completePhaseActions();
222             endPhase(phase);
223         }
224     }
225
226     ReactorDeclaredModel build() throws ReactorException {
227         executePhases();
228         return transform();
229     }
230
231     EffectiveSchemaContext buildEffective() throws ReactorException {
232         executePhases();
233         return transformEffective();
234     }
235
236     private ReactorDeclaredModel transform() {
237         checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
238         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
239         for (final SourceSpecificContext source : sources) {
240             rootStatements.add(source.getRoot().declared());
241         }
242         return new ReactorDeclaredModel(rootStatements);
243     }
244
245     private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
246             final RuntimeException cause) throws SomeModifiersUnresolvedException {
247         final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
248         if (!(cause instanceof SourceException)) {
249             /*
250              * This should not be happening as all our processing should provide SourceExceptions.
251              * We will wrap the exception to provide enough information to identify the problematic model,
252              * but also emit a warning so the offending codepath will get fixed.
253              */
254             LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
255                 sourceId, cause);
256         }
257
258         throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
259     }
260
261     private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
262         final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
263         final String arg = root.getRawArgument();
264         if (qNameModule != null) {
265             // creates SourceIdentifier for a module
266             return RevisionSourceIdentifier.create(arg, qNameModule.getRevision());
267         }
268
269         // creates SourceIdentifier for a submodule
270         return RevisionSourceIdentifier.create(arg, StmtContextUtils.getLatestRevision(root.declaredSubstatements()));
271     }
272
273     @SuppressWarnings("checkstyle:illegalCatch")
274     private EffectiveSchemaContext transformEffective() throws ReactorException {
275         checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
276         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
277         final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
278
279         for (final SourceSpecificContext source : sources) {
280             final RootStatementContext<?, ?, ?> root = source.getRoot();
281             try {
282                 rootStatements.add(root.declared());
283                 rootEffectiveStatements.add(root.buildEffective());
284             } catch (final RuntimeException ex) {
285                 throw propagateException(source, ex);
286             }
287         }
288
289         sealMutableStatements();
290         return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
291     }
292
293     private void startPhase(final ModelProcessingPhase phase) {
294         checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
295         startPhaseFor(phase, sources);
296         startPhaseFor(phase, libSources);
297
298         currentPhase = phase;
299         LOG.debug("Global phase {} started", phase);
300     }
301
302     private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
303         for (final SourceSpecificContext source : sources) {
304             source.startPhase(phase);
305         }
306     }
307
308     private void loadPhaseStatements() throws ReactorException {
309         checkState(currentPhase != null);
310         loadPhaseStatementsFor(sources);
311         loadPhaseStatementsFor(libSources);
312     }
313
314     @SuppressWarnings("checkstyle:illegalCatch")
315     private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
316         for (final SourceSpecificContext source : srcs) {
317             try {
318                 source.loadStatements();
319             } catch (final RuntimeException ex) {
320                 throw propagateException(source, ex);
321             }
322         }
323     }
324
325     private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
326         boolean addedCause = false;
327         SomeModifiersUnresolvedException buildFailure = null;
328         for (final SourceSpecificContext failedSource : sourcesToProgress) {
329             final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
330             if (optSourceEx.isEmpty()) {
331                 continue;
332             }
333
334             final SourceException sourceEx = optSourceEx.get();
335             // Workaround for broken logging implementations which ignore
336             // suppressed exceptions
337             final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
338             if (LOG.isDebugEnabled()) {
339                 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
340             } else {
341                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
342             }
343
344             final Throwable[] suppressed = sourceEx.getSuppressed();
345             if (suppressed.length > 0) {
346                 LOG.error("{} additional errors reported:", suppressed.length);
347
348                 int count = 1;
349                 for (final Throwable t : suppressed) {
350                     LOG.error("Error {}: {}", count, t.getMessage());
351                     count++;
352                 }
353             }
354
355             if (!addedCause) {
356                 addedCause = true;
357                 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
358                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
359             } else {
360                 buildFailure.addSuppressed(sourceEx);
361             }
362         }
363         return buildFailure;
364     }
365
366     @SuppressWarnings("checkstyle:illegalCatch")
367     private void completePhaseActions() throws ReactorException {
368         checkState(currentPhase != null);
369         final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
370         if (!libSources.isEmpty()) {
371             checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
372                     "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
373                             + "but current phase was %s", currentPhase);
374             sourcesToProgress.addAll(libSources);
375         }
376
377         boolean progressing = true;
378         while (progressing) {
379             // We reset progressing to false.
380             progressing = false;
381             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
382             while (currentSource.hasNext()) {
383                 final SourceSpecificContext nextSourceCtx = currentSource.next();
384                 try {
385                     final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
386                     switch (sourceProgress) {
387                         case FINISHED:
388                             currentSource.remove();
389                             // we were able to make progress in computation
390                             progressing = true;
391                             break;
392                         case PROGRESS:
393                             progressing = true;
394                             break;
395                         case NO_PROGRESS:
396                             // Noop
397                             break;
398                         default:
399                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
400                     }
401                 } catch (final RuntimeException ex) {
402                     throw propagateException(nextSourceCtx, ex);
403                 }
404             }
405         }
406
407         if (!libSources.isEmpty()) {
408             final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
409             sources.addAll(requiredLibs);
410             libSources = ImmutableSet.of();
411             /*
412              * We want to report errors of relevant sources only, so any others can
413              * be removed.
414              */
415             sourcesToProgress.retainAll(sources);
416         }
417
418         if (!sourcesToProgress.isEmpty()) {
419             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
420             if (buildFailure != null) {
421                 throw buildFailure;
422             }
423         }
424     }
425
426     private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
427         checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
428                 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
429                         + " but current phase was %s", currentPhase);
430         final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
431             String::compareTo, Revision::compare);
432         for (final SourceSpecificContext libSource : libSources) {
433             final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
434             libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
435         }
436
437         final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
438         for (final SourceSpecificContext source : sources) {
439             collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
440             removeConflictingLibSources(source, requiredLibs);
441         }
442         return requiredLibs;
443     }
444
445     private void collectRequiredSourcesFromLib(
446             final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
447             final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
448         for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
449             final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
450             if (libSource != null && requiredLibs.add(libSource)) {
451                 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
452             }
453         }
454     }
455
456     private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
457             final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
458         return requiredSource.getRevision().isPresent()
459                 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
460                         : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
461     }
462
463     private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
464             SourceSpecificContext> sourceMap) {
465         return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
466     }
467
468     // removes required library sources which would cause namespace/name conflict with one of the main sources
469     // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
470     // and the same parent module or submodule is added as one of the library sources.
471     // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
472     // as its argument and the same dir is specified as one of the library dirs through -p option).
473     private static void removeConflictingLibSources(final SourceSpecificContext source,
474             final Set<SourceSpecificContext> requiredLibs) {
475         final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
476         while (requiredLibsIter.hasNext()) {
477             final SourceSpecificContext currentReqSource = requiredLibsIter.next();
478             if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
479                 requiredLibsIter.remove();
480             }
481         }
482     }
483
484     private void endPhase(final ModelProcessingPhase phase) {
485         checkState(currentPhase == phase);
486         finishedPhase = currentPhase;
487         LOG.debug("Global phase {} finished", phase);
488     }
489
490     Set<SourceSpecificContext> getSources() {
491         return sources;
492     }
493
494     public Set<YangVersion> getSupportedVersions() {
495         return supportedVersions;
496     }
497
498     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
499         mutableStatementsToSeal.add(mutableStatement);
500     }
501
502     void sealMutableStatements() {
503         for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
504             mutableStatement.seal();
505         }
506         mutableStatementsToSeal.clear();
507     }
508 }