Promote SchemaSourceRepresentation
[yangtools.git] / parser / 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 com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
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.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;
58
59 final class BuildGlobalContext extends AbstractNamespaceStorage implements GlobalStorage {
60     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
61
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
68     };
69
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;
77
78     private Set<SourceSpecificContext> libSources = new HashSet<>();
79     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
80     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
81
82     BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
83             final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation) {
84         this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
85
86         final var access = accessNamespace(ValidationBundles.NAMESPACE);
87         for (var validationBundle : supportedValidation.entrySet()) {
88             access.valueTo(this, validationBundle.getKey(), validationBundle.getValue());
89         }
90
91         supportedVersions = ImmutableSet.copyOf(
92             verifyNotNull(supports.get(ModelProcessingPhase.INIT)).getSupportedVersions());
93     }
94
95     StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
96         return supports.get(phase);
97     }
98
99     void addSource(final StatementStreamSource source) {
100         sources.add(new SourceSpecificContext(this, source));
101     }
102
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));
107     }
108
109     void setSupportedFeatures(final FeatureSet supportedFeatures) {
110         addToNamespace(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), requireNonNull(supportedFeatures));
111     }
112
113     void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
114         addToNamespace(ParserNamespaces.MODULES_DEVIATED_BY, Empty.value(),
115             ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
116     }
117
118     @Override
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) {
123             return existing;
124         }
125
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);
131         }
132
133         final var created = new BehaviourNamespaceAccess<>(this, behaviour);
134         supportedNamespaces.put(namespace, created);
135         return created;
136     }
137
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);
145             }
146         }
147         return potential;
148     }
149
150     StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
151         return modelDefinedStmtDefs.get(name);
152     }
153
154     void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
155         modelDefinedStmtDefs.put(name, def);
156     }
157
158     private void executePhases() throws ReactorException {
159         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
160             startPhase(phase);
161             loadPhaseStatements();
162             completePhaseActions();
163             endPhase(phase);
164         }
165     }
166
167     ReactorDeclaredModel build() throws ReactorException {
168         executePhases();
169         return transform();
170     }
171
172     EffectiveSchemaContext buildEffective() throws ReactorException {
173         executePhases();
174         return transformEffective();
175     }
176
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());
182         }
183         return new ReactorDeclaredModel(rootStatements);
184     }
185
186     private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
187             final RuntimeException cause) throws SomeModifiersUnresolvedException {
188         final SourceIdentifier sourceId = source.identifySource();
189         if (!(cause instanceof SourceException)) {
190             /*
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.
194              */
195             LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
196                 sourceId, cause);
197         }
198
199         throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
200     }
201
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());
207
208         for (var source : sources) {
209             try {
210                 rootStatements.add(source.declaredRoot());
211                 rootEffectiveStatements.add(source.effectiveRoot());
212             } catch (final RuntimeException ex) {
213                 throw propagateException(source, ex);
214             }
215         }
216
217         sealMutableStatements();
218         return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
219     }
220
221     private void startPhase(final ModelProcessingPhase phase) {
222         checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
223         startPhaseFor(phase, sources);
224         startPhaseFor(phase, libSources);
225
226         currentPhase = phase;
227         LOG.debug("Global phase {} started", phase);
228     }
229
230     private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
231         for (final SourceSpecificContext source : sources) {
232             source.startPhase(phase);
233         }
234     }
235
236     private void loadPhaseStatements() throws ReactorException {
237         checkState(currentPhase != null);
238         loadPhaseStatementsFor(sources);
239         loadPhaseStatementsFor(libSources);
240     }
241
242     @SuppressWarnings("checkstyle:illegalCatch")
243     private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
244         for (final SourceSpecificContext source : srcs) {
245             try {
246                 source.loadStatements();
247             } catch (final RuntimeException ex) {
248                 throw propagateException(source, ex);
249             }
250         }
251     }
252
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()) {
259                 continue;
260             }
261
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);
268             } else {
269                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
270             }
271
272             final Throwable[] suppressed = sourceEx.getSuppressed();
273             if (suppressed.length > 0) {
274                 LOG.error("{} additional errors reported:", suppressed.length);
275
276                 int count = 1;
277                 for (final Throwable t : suppressed) {
278                     LOG.error("Error {}: {}", count, t.getMessage());
279                     count++;
280                 }
281             }
282
283             if (!addedCause) {
284                 addedCause = true;
285                 final SourceIdentifier sourceId = failedSource.identifySource();
286                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
287             } else {
288                 buildFailure.addSuppressed(sourceEx);
289             }
290         }
291         return buildFailure;
292     }
293
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);
303         }
304
305         boolean progressing = true;
306         while (progressing) {
307             // We reset progressing to false.
308             progressing = false;
309             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
310             while (currentSource.hasNext()) {
311                 final SourceSpecificContext nextSourceCtx = currentSource.next();
312                 try {
313                     final PhaseCompletionProgress sourceProgress =
314                         nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
315                     switch (sourceProgress) {
316                         case FINISHED:
317                             currentSource.remove();
318                             // we were able to make progress in computation
319                             progressing = true;
320                             break;
321                         case PROGRESS:
322                             progressing = true;
323                             break;
324                         case NO_PROGRESS:
325                             // Noop
326                             break;
327                         default:
328                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
329                     }
330                 } catch (final RuntimeException ex) {
331                     throw propagateException(nextSourceCtx, ex);
332                 }
333             }
334         }
335
336         if (!libSources.isEmpty()) {
337             final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
338             sources.addAll(requiredLibs);
339             libSources = ImmutableSet.of();
340             /*
341              * We want to report errors of relevant sources only, so any others can
342              * be removed.
343              */
344             sourcesToProgress.retainAll(sources);
345         }
346
347         if (!sourcesToProgress.isEmpty()) {
348             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
349             if (buildFailure != null) {
350                 throw buildFailure;
351             }
352         }
353     }
354
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);
365         }
366
367         final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
368         for (final SourceSpecificContext source : sources) {
369             collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
370             removeConflictingLibSources(source, requiredLibs);
371         }
372         return requiredLibs;
373     }
374
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);
382             }
383         }
384     }
385
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()));
391     }
392
393     private static SourceSpecificContext getLatestRevision(
394             final SortedMap<Optional<Revision>, SourceSpecificContext> sourceMap) {
395         return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
396     }
397
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();
410             }
411         }
412     }
413
414     private void endPhase(final ModelProcessingPhase phase) {
415         checkState(currentPhase == phase);
416         finishedPhase = currentPhase;
417         LOG.debug("Global phase {} finished", phase);
418     }
419
420     Set<SourceSpecificContext> getSources() {
421         return sources;
422     }
423
424     public Set<YangVersion> getSupportedVersions() {
425         return supportedVersions;
426     }
427
428     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
429         mutableStatementsToSeal.add(mutableStatement);
430     }
431
432     void sealMutableStatements() {
433         for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
434             mutableStatement.seal();
435         }
436         mutableStatementsToSeal.clear();
437     }
438 }