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