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