Bug 4640: Change semantic-version to openconfig-version
[yangtools.git] / yang / yang-parser-impl / 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.ModuleIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
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.source.BelongsToModuleContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
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.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
64
65     public enum PhaseCompletionProgress {
66         NO_PROGRESS,
67         PROGRESS,
68         FINISHED
69     }
70
71     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
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 isEnabledOpenconfigVersioning(){
94         return currentContext.isEnabledOpenconfigVersioning();
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             final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
117             if (extension != null) {
118                 def = new StatementDefinitionContext<>(extension);
119             }
120         } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
121             /*
122              * This code wraps statements encountered inside an extension so they do not get confused with regular
123              * statements.
124              *
125              * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
126              *        this work. We really should be peeking into the extension definition to find these nodes,
127              *        as otherwise we are not reusing definitions nor support for these nodes.
128              */
129             final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
130             def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
131                 new ModelDefinedStatementDefinition(qName, argument != null)));
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(), root.getRootIdentifier());
164         } else {
165             final QName rootStatement = root.definition().getStatementName();
166             final String rootArgument = root.rawStatementArgument();
167
168             Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
169                 && Objects.equals(argument, rootArgument),
170                 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
171         }
172         return root;
173     }
174
175     RootStatementContext<?, ?, ?> getRoot() {
176         return root;
177     }
178
179     /**
180      * Return version of root statement context.
181      *
182      * @return version of root statement context
183      */
184     YangVersion getRootVersion() {
185         return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
186     }
187
188     DeclaredStatement<?> buildDeclared() {
189         return root.buildDeclared();
190     }
191
192     EffectiveStatement<?, ?> buildEffective() {
193         return root.buildEffective();
194     }
195
196     void startPhase(final ModelProcessingPhase phase) {
197         @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
198         Verify.verify(Objects.equals(previousPhase, finishedPhase),
199             "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
200             finishedPhase);
201
202         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
203         Preconditions.checkState(previousModifiers.isEmpty(),
204             "Previous phase %s has unresolved modifiers %s in source %s",
205             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         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
317         while (modifier.hasNext()) {
318             if (modifier.next().tryApply()) {
319                 modifier.remove();
320                 hasProgressed = true;
321             }
322         }
323
324         return hasProgressed;
325     }
326
327     ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
328         final ModifierImpl action = new ModifierImpl(phase);
329         modifiers.put(phase, action);
330         return action;
331     }
332
333     @Override
334     public String toString() {
335         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
336                 + finishedPhase + "]";
337     }
338
339     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
340         final List<SourceException> exceptions = new ArrayList<>();
341         for (final ModifierImpl mod : modifiers.get(identifier)) {
342             try {
343                 mod.failModifier();
344             } catch (final SourceException e) {
345                 exceptions.add(e);
346             }
347         }
348
349         if (exceptions.isEmpty()) {
350             return Optional.empty();
351         }
352
353         final String message = String.format("Yang model processing phase %s failed", identifier);
354         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
355             exceptions.get(0));
356         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
357
358         return Optional.of(e);
359     }
360
361     void loadStatements() throws SourceException {
362         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
363
364         switch (inProgressPhase) {
365             case SOURCE_PRE_LINKAGE:
366                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
367                 break;
368             case SOURCE_LINKAGE:
369                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(), getRootVersion());
370                 break;
371             case STATEMENT_DEFINITION:
372                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
373                 break;
374             case FULL_DECLARATION:
375                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
376                 break;
377             default:
378                 break;
379         }
380     }
381
382     private PrefixToModule preLinkagePrefixes() {
383         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
384         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
385         if (prefixToNamespaceMap == null) {
386             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
387             return null;
388         }
389
390         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
391         return preLinkagePrefixes;
392     }
393
394     private PrefixToModule prefixes() {
395         final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
396                 .class);
397         final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
398                 (BelongsToPrefixToModuleIdentifier.class);
399         if (belongsToPrefixes != null) {
400             allPrefixes.putAll(belongsToPrefixes);
401         }
402
403         allPrefixes.forEach((key, value) ->
404             prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
405
406         return prefixToModuleMap;
407     }
408
409     private QNameToStatementDefinition stmtDef() {
410         // regular YANG statements and extension supports added
411         final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
412         qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
413         qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
414
415         // No further actions needed
416         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
417             return qNameToStmtDefMap;
418         }
419
420         // We need to any and all extension statements which have been declared in the context
421         final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
422                 StatementDefinitionNamespace.class);
423         if (extensions != null) {
424             extensions.forEach((qname, support) -> {
425                 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
426                 if (existing != null) {
427                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
428                 } else {
429                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
430                 }
431             });
432         }
433
434         return qNameToStmtDefMap;
435     }
436
437     public Set<YangVersion> getSupportedVersions() {
438         return currentContext.getSupportedVersions();
439     }
440
441     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
442         currentContext.addMutableStmtToSeal(mutableStatement);
443     }
444
445     Collection<ModuleIdentifier> getRequiredModules() {
446         return root.getRequiredModules();
447     }
448
449     ModuleIdentifier getRootIdentifier() {
450         return root.getRootIdentifier();
451     }
452 }