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