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