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