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