Cleanup StmtContext nullness annotations
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SourceSpecificContext.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.checkNotNull;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.collect.HashMultimap;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Multimap;
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26 import java.util.Set;
27 import javax.annotation.Nullable;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.yangtools.concepts.Mutable;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.common.YangVersion;
33 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
36 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
37 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
50 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
51 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleCtx;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
56 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
57 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
58 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
59 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
62 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
67
68     public enum PhaseCompletionProgress {
69         NO_PROGRESS,
70         PROGRESS,
71         FINISHED
72     }
73
74     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
75
76     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
77     private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
78     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
79     private final BuildGlobalContext currentContext;
80     private final StatementStreamSource source;
81
82     /*
83      * "imported" namespaces in this source -- this points to RootStatementContexts of
84      * - modules imported via 'import' statement
85      * - parent module, declared via 'belongs-to' statement
86      */
87     private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
88     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
89     private ModelProcessingPhase inProgressPhase;
90     private RootStatementContext<?, ?, ?> root;
91
92     SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
93         this.currentContext = requireNonNull(currentContext);
94         this.source = requireNonNull(source);
95     }
96
97     boolean isEnabledSemanticVersioning() {
98         return currentContext.isEnabledSemanticVersioning();
99     }
100
101     ModelProcessingPhase getInProgressPhase() {
102         return inProgressPhase;
103     }
104
105     Optional<StatementContextBase<?, ?, ?>> lookupDeclaredChild(final StatementContextBase<?, ?, ?> current,
106             final int childId) {
107         if (current == null) {
108             return Optional.empty();
109         }
110
111         // Fast path: we are entering a statement which was emitted in previous phase
112         StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
113         while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
114             existing = existing.lookupSubstatement(childId);
115         }
116
117         return Optional.ofNullable(existing);
118     }
119
120     StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
121             final QName name, final String argument, final StatementSourceReference ref) {
122         StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
123         if (def == null) {
124             def = currentContext.getModelDefinedStatementDefinition(name);
125             if (def == null) {
126                 final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
127                 if (extension != null) {
128                     def = new StatementDefinitionContext<>(extension);
129                     currentContext.putModelDefinedStatementDefinition(name, def);
130                 }
131             }
132         } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
133             /*
134              * This code wraps statements encountered inside an extension so
135              * they do not get confused with regular statements.
136              */
137             def = checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
138                     "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
139                     current);
140         }
141
142         InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
143         if (def.hasArgument()) {
144             SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
145         } else {
146             SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
147         }
148
149         /*
150          * If the current statement definition has argument specific
151          * sub-definitions, get argument specific sub-definition based on given
152          * argument (e.g. type statement need to be specialized based on its
153          * argument).
154          */
155         if (def.hasArgumentSpecificSubDefinitions()) {
156             def = def.getSubDefinitionSpecificForArgument(argument);
157         }
158
159         if (current != null) {
160             return current.createSubstatement(childId, def, ref, argument);
161         }
162
163         /*
164          * If root is null or root version is other than default,
165          * we need to create new root.
166          */
167         if (root == null) {
168             root = new RootStatementContext<>(this, def, ref, argument);
169         } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
170                 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
171             root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
172                     root.getRootIdentifier());
173         } else {
174             final QName rootStatement = root.definition().getStatementName();
175             final String rootArgument = root.rawStatementArgument();
176
177             checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
178                 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
179         }
180         return root;
181     }
182
183     RootStatementContext<?, ?, ?> getRoot() {
184         return root;
185     }
186
187     /**
188      * Return version of root statement context.
189      *
190      * @return version of root statement context
191      */
192     YangVersion getRootVersion() {
193         return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
194     }
195
196     DeclaredStatement<?> buildDeclared() {
197         return root.buildDeclared();
198     }
199
200     EffectiveStatement<?, ?> buildEffective() {
201         return root.buildEffective();
202     }
203
204     void startPhase(final ModelProcessingPhase phase) {
205         @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
206         verify(Objects.equals(previousPhase, finishedPhase),
207             "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
208             finishedPhase);
209
210         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
211         checkState(previousModifiers.isEmpty(), "Previous phase %s has unresolved modifiers %s in source %s",
212             previousPhase, previousModifiers, source);
213
214         inProgressPhase = phase;
215         LOG.debug("Source {} started phase {}", source, phase);
216     }
217
218     private void updateImportedNamespaces(final Class<?> type, final Object value) {
219         if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
220             if (importedNamespaces.isEmpty()) {
221                 importedNamespaces = new ArrayList<>(1);
222             }
223
224             verify(value instanceof RootStatementContext);
225             importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
226         }
227     }
228
229     @Override
230     public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
231            final V value) {
232         // RootStatementContext takes care of IncludedModuleContext and the rest...
233         final V ret = getRoot().putToLocalStorage(type, key, value);
234         // FIXME: what about duplicates?
235         updateImportedNamespaces(type, value);
236         return ret;
237     }
238
239     @Override
240     public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
241            final V value) {
242         // RootStatementContext takes care of IncludedModuleContext and the rest...
243         final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
244         if (ret == null) {
245             updateImportedNamespaces(type, value);
246         }
247         return ret;
248     }
249
250     @Override
251     public StorageNodeType getStorageNodeType() {
252         return StorageNodeType.SOURCE_LOCAL_SPECIAL;
253     }
254
255     @Override
256     public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
257         final V potentialLocal = getRoot().getFromLocalStorage(type, key);
258         if (potentialLocal != null) {
259             return potentialLocal;
260         }
261
262         for (final NamespaceStorageNode importedSource : importedNamespaces) {
263             final V potential = importedSource.getFromLocalStorage(type, key);
264             if (potential != null) {
265                 return potential;
266             }
267         }
268         return null;
269     }
270
271     @Nullable
272     @Override
273     public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
274         final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
275         if (potentialLocal != null) {
276             return potentialLocal;
277         }
278
279         for (final NamespaceStorageNode importedSource : importedNamespaces) {
280             final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
281
282             if (potential != null) {
283                 return potential;
284             }
285         }
286         return null;
287     }
288
289     @Override
290     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
291             final Class<N> type) {
292         return currentContext.getNamespaceBehaviour(type);
293     }
294
295     @Override
296     public NamespaceStorageNode getParentNamespaceStorage() {
297         return currentContext;
298     }
299
300     PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) {
301         final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
302
303         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
304
305         checkNotNull(this.root, "Malformed source. Valid root element is missing.");
306         final boolean phaseCompleted = root.tryToCompletePhase(phase);
307
308         hasProgressed |= tryToProgress(currentPhaseModifiers);
309
310         if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
311             finishedPhase = phase;
312             LOG.debug("Source {} finished phase {}", source, phase);
313             return PhaseCompletionProgress.FINISHED;
314
315         }
316
317         return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
318     }
319
320     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
321         boolean hasProgressed = false;
322
323         // Try making forward progress ...
324         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
325         while (modifier.hasNext()) {
326             if (modifier.next().tryApply()) {
327                 modifier.remove();
328                 hasProgressed = true;
329             }
330         }
331
332         return hasProgressed;
333     }
334
335     @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
336         final ModifierImpl action = new ModifierImpl();
337         modifiers.put(phase, action);
338         return action;
339     }
340
341     @Override
342     public String toString() {
343         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
344                 + finishedPhase + "]";
345     }
346
347     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
348         final List<SourceException> exceptions = new ArrayList<>();
349         for (final ModifierImpl mod : modifiers.get(identifier)) {
350             try {
351                 mod.failModifier();
352             } catch (final SourceException e) {
353                 exceptions.add(e);
354             }
355         }
356
357         if (exceptions.isEmpty()) {
358             return Optional.empty();
359         }
360
361         final String message = String.format("Yang model processing phase %s failed", identifier);
362         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
363             exceptions.get(0));
364         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
365
366         return Optional.of(e);
367     }
368
369     void loadStatements() {
370         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
371
372         switch (inProgressPhase) {
373             case SOURCE_PRE_LINKAGE:
374                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
375                 break;
376             case SOURCE_LINKAGE:
377                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
378                     getRootVersion());
379                 break;
380             case STATEMENT_DEFINITION:
381                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
382                     prefixes(), getRootVersion());
383                 break;
384             case FULL_DECLARATION:
385                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
386                     getRootVersion());
387                 break;
388             default:
389                 break;
390         }
391     }
392
393     private PrefixToModule preLinkagePrefixes() {
394         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
395         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
396         if (prefixToNamespaceMap == null) {
397             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
398             return null;
399         }
400
401         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
402         return preLinkagePrefixes;
403     }
404
405     private PrefixToModule prefixes() {
406         final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
407             ImportPrefixToModuleCtx.class);
408         if (allImports != null) {
409             allImports.forEach((key, value) ->
410                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
411         }
412
413         final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
414             BelongsToPrefixToModuleCtx.class);
415         if (allBelongsTo != null) {
416             allBelongsTo.forEach((key, value) ->
417                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
418         }
419
420         return prefixToModuleMap;
421     }
422
423     private QNameToStatementDefinition stmtDef() {
424         // regular YANG statements and extension supports added
425         final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
426         qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
427         qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
428
429         // No further actions needed
430         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
431             return qnameToStmtDefMap;
432         }
433
434         // We need to any and all extension statements which have been declared in the context
435         final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
436                 StatementDefinitionNamespace.class);
437         if (extensions != null) {
438             extensions.forEach((qname, support) -> {
439                 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
440                 if (existing != null) {
441                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
442                 } else {
443                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
444                 }
445             });
446         }
447
448         return qnameToStmtDefMap;
449     }
450
451     public Set<YangVersion> getSupportedVersions() {
452         return currentContext.getSupportedVersions();
453     }
454
455     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
456         currentContext.addMutableStmtToSeal(mutableStatement);
457     }
458
459     Collection<SourceIdentifier> getRequiredSources() {
460         return root.getRequiredSources();
461     }
462
463     SourceIdentifier getRootIdentifier() {
464         return root.getRootIdentifier();
465     }
466 }