Make ParserNamespace an identifier
[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.SourceException;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SourceParserNamespaces;
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(SourceParserNamespaces.SUPPORTED_FEATURES, Empty.value(),
117             ImmutableSet.copyOf(supportedFeatures));
118     }
119
120     void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
121         addToNamespace(SourceParserNamespaces.MODULES_DEVIATED_BY, 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 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 derived) {
167             final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(derived);
168             getNamespaceBehaviour(derived.getDerivedFrom()).addDerivedNamespace(derivedContext);
169             return derivedContext;
170         }
171         return new SimpleNamespaceContext<>(potentialRaw);
172     }
173
174     StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
175         StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
176         if (potential == null) {
177             final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getStatementDefinition(version, name);
178             if (potentialRaw != null) {
179                 potential = new StatementDefinitionContext<>(potentialRaw);
180                 definitions.put(version, name, potential);
181             }
182         }
183         return potential;
184     }
185
186     StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
187         return modelDefinedStmtDefs.get(name);
188     }
189
190     void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
191         modelDefinedStmtDefs.put(name, def);
192     }
193
194     private void executePhases() throws ReactorException {
195         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
196             startPhase(phase);
197             loadPhaseStatements();
198             completePhaseActions();
199             endPhase(phase);
200         }
201     }
202
203     ReactorDeclaredModel build() throws ReactorException {
204         executePhases();
205         return transform();
206     }
207
208     EffectiveSchemaContext buildEffective() throws ReactorException {
209         executePhases();
210         return transformEffective();
211     }
212
213     private ReactorDeclaredModel transform() {
214         checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
215         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
216         for (final SourceSpecificContext source : sources) {
217             rootStatements.add(source.getRoot().declared());
218         }
219         return new ReactorDeclaredModel(rootStatements);
220     }
221
222     private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
223             final RuntimeException cause) throws SomeModifiersUnresolvedException {
224         final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
225         if (!(cause instanceof SourceException)) {
226             /*
227              * This should not be happening as all our processing should provide SourceExceptions.
228              * We will wrap the exception to provide enough information to identify the problematic model,
229              * but also emit a warning so the offending codepath will get fixed.
230              */
231             LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
232                 sourceId, cause);
233         }
234
235         throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
236     }
237
238     private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
239         final QNameModule qNameModule = root.getFromNamespace(SourceParserNamespaces.MODULECTX_TO_QNAME, root);
240         final Object arg = root.getArgument();
241         verify(arg instanceof Unqualified, "Unexpected argument %s", arg);
242
243         if (qNameModule != null) {
244             // creates SourceIdentifier for a module
245             return new SourceIdentifier((Unqualified) arg, qNameModule.getRevision().orElse(null));
246         }
247
248         // creates SourceIdentifier for a submodule
249         return new SourceIdentifier((Unqualified) arg,
250             StmtContextUtils.getLatestRevision(root.declaredSubstatements()).orElse(null));
251     }
252
253     @SuppressWarnings("checkstyle:illegalCatch")
254     private EffectiveSchemaContext transformEffective() throws ReactorException {
255         checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
256         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
257         final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
258
259         for (final SourceSpecificContext source : sources) {
260             final RootStatementContext<?, ?, ?> root = source.getRoot();
261             try {
262                 rootStatements.add(root.declared());
263                 rootEffectiveStatements.add(root.buildEffective());
264             } catch (final RuntimeException ex) {
265                 throw propagateException(source, ex);
266             }
267         }
268
269         sealMutableStatements();
270         return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
271     }
272
273     private void startPhase(final ModelProcessingPhase phase) {
274         checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
275         startPhaseFor(phase, sources);
276         startPhaseFor(phase, libSources);
277
278         currentPhase = phase;
279         LOG.debug("Global phase {} started", phase);
280     }
281
282     private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
283         for (final SourceSpecificContext source : sources) {
284             source.startPhase(phase);
285         }
286     }
287
288     private void loadPhaseStatements() throws ReactorException {
289         checkState(currentPhase != null);
290         loadPhaseStatementsFor(sources);
291         loadPhaseStatementsFor(libSources);
292     }
293
294     @SuppressWarnings("checkstyle:illegalCatch")
295     private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
296         for (final SourceSpecificContext source : srcs) {
297             try {
298                 source.loadStatements();
299             } catch (final RuntimeException ex) {
300                 throw propagateException(source, ex);
301             }
302         }
303     }
304
305     private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
306         boolean addedCause = false;
307         SomeModifiersUnresolvedException buildFailure = null;
308         for (final SourceSpecificContext failedSource : sourcesToProgress) {
309             final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
310             if (optSourceEx.isEmpty()) {
311                 continue;
312             }
313
314             final SourceException sourceEx = optSourceEx.get();
315             // Workaround for broken logging implementations which ignore
316             // suppressed exceptions
317             final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
318             if (LOG.isDebugEnabled()) {
319                 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
320             } else {
321                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
322             }
323
324             final Throwable[] suppressed = sourceEx.getSuppressed();
325             if (suppressed.length > 0) {
326                 LOG.error("{} additional errors reported:", suppressed.length);
327
328                 int count = 1;
329                 for (final Throwable t : suppressed) {
330                     LOG.error("Error {}: {}", count, t.getMessage());
331                     count++;
332                 }
333             }
334
335             if (!addedCause) {
336                 addedCause = true;
337                 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
338                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
339             } else {
340                 buildFailure.addSuppressed(sourceEx);
341             }
342         }
343         return buildFailure;
344     }
345
346     @SuppressWarnings("checkstyle:illegalCatch")
347     private void completePhaseActions() throws ReactorException {
348         checkState(currentPhase != null);
349         final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
350         if (!libSources.isEmpty()) {
351             checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
352                     "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
353                             + "but current phase was %s", currentPhase);
354             sourcesToProgress.addAll(libSources);
355         }
356
357         boolean progressing = true;
358         while (progressing) {
359             // We reset progressing to false.
360             progressing = false;
361             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
362             while (currentSource.hasNext()) {
363                 final SourceSpecificContext nextSourceCtx = currentSource.next();
364                 try {
365                     final PhaseCompletionProgress sourceProgress =
366                         nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
367                     switch (sourceProgress) {
368                         case FINISHED:
369                             currentSource.remove();
370                             // we were able to make progress in computation
371                             progressing = true;
372                             break;
373                         case PROGRESS:
374                             progressing = true;
375                             break;
376                         case NO_PROGRESS:
377                             // Noop
378                             break;
379                         default:
380                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
381                     }
382                 } catch (final RuntimeException ex) {
383                     throw propagateException(nextSourceCtx, ex);
384                 }
385             }
386         }
387
388         if (!libSources.isEmpty()) {
389             final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
390             sources.addAll(requiredLibs);
391             libSources = ImmutableSet.of();
392             /*
393              * We want to report errors of relevant sources only, so any others can
394              * be removed.
395              */
396             sourcesToProgress.retainAll(sources);
397         }
398
399         if (!sourcesToProgress.isEmpty()) {
400             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
401             if (buildFailure != null) {
402                 throw buildFailure;
403             }
404         }
405     }
406
407     private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
408         checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
409                 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
410                         + " but current phase was %s", currentPhase);
411         final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable =
412             TreeBasedTable.create(Unqualified::compareTo, Revision::compare);
413         for (final SourceSpecificContext libSource : libSources) {
414             final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
415             libSourcesTable.put(libSourceIdentifier.name(),
416                 Optional.ofNullable(libSourceIdentifier.revision()), libSource);
417         }
418
419         final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
420         for (final SourceSpecificContext source : sources) {
421             collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
422             removeConflictingLibSources(source, requiredLibs);
423         }
424         return requiredLibs;
425     }
426
427     private void collectRequiredSourcesFromLib(
428             final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable,
429             final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
430         for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
431             final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
432             if (libSource != null && requiredLibs.add(libSource)) {
433                 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
434             }
435         }
436     }
437
438     private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
439             final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
440         final var revision = requiredSource.revision();
441         return revision != null ? libSourcesTable.get(requiredSource.name(), Optional.of(revision))
442             : getLatestRevision(libSourcesTable.row(requiredSource.name()));
443     }
444
445     private static SourceSpecificContext getLatestRevision(
446             final SortedMap<Optional<Revision>, SourceSpecificContext> sourceMap) {
447         return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
448     }
449
450     // removes required library sources which would cause namespace/name conflict with one of the main sources
451     // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
452     // and the same parent module or submodule is added as one of the library sources.
453     // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
454     // as its argument and the same dir is specified as one of the library dirs through -p option).
455     private static void removeConflictingLibSources(final SourceSpecificContext source,
456             final Set<SourceSpecificContext> requiredLibs) {
457         final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
458         while (requiredLibsIter.hasNext()) {
459             final SourceSpecificContext currentReqSource = requiredLibsIter.next();
460             if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
461                 requiredLibsIter.remove();
462             }
463         }
464     }
465
466     private void endPhase(final ModelProcessingPhase phase) {
467         checkState(currentPhase == phase);
468         finishedPhase = currentPhase;
469         LOG.debug("Global phase {} finished", phase);
470     }
471
472     Set<SourceSpecificContext> getSources() {
473         return sources;
474     }
475
476     public Set<YangVersion> getSupportedVersions() {
477         return supportedVersions;
478     }
479
480     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
481         mutableStatementsToSeal.add(mutableStatement);
482     }
483
484     void sealMutableStatements() {
485         for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
486             mutableStatement.seal();
487         }
488         mutableStatementsToSeal.clear();
489     }
490 }