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