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