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