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