Remove @ThreadSafe annotation from AbstractCodecFactory
[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                 .hasArgument()) {
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
303         checkNotNull(this.root, "Malformed source. Valid root element is missing.");
304         final boolean phaseCompleted = root.tryToCompletePhase(phase);
305
306         hasProgressed |= tryToProgress(currentPhaseModifiers);
307
308         if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
309             finishedPhase = phase;
310             LOG.debug("Source {} finished phase {}", source, phase);
311             return PhaseCompletionProgress.FINISHED;
312
313         }
314
315         return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
316     }
317
318     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
319         boolean hasProgressed = false;
320
321         // Try making forward progress ...
322         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
323         while (modifier.hasNext()) {
324             if (modifier.next().tryApply()) {
325                 modifier.remove();
326                 hasProgressed = true;
327             }
328         }
329
330         return hasProgressed;
331     }
332
333     @NonNull ModelActionBuilder newInferenceAction(final @NonNull ModelProcessingPhase phase) {
334         final ModifierImpl action = new ModifierImpl();
335         modifiers.put(phase, action);
336         return action;
337     }
338
339     @Override
340     public String toString() {
341         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
342                 + finishedPhase + "]";
343     }
344
345     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
346         final List<SourceException> exceptions = new ArrayList<>();
347         for (final ModifierImpl mod : modifiers.get(identifier)) {
348             try {
349                 mod.failModifier();
350             } catch (final SourceException e) {
351                 exceptions.add(e);
352             }
353         }
354
355         if (exceptions.isEmpty()) {
356             return Optional.empty();
357         }
358
359         final String message = String.format("Yang model processing phase %s failed", identifier);
360         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
361             exceptions.get(0));
362         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
363
364         return Optional.of(e);
365     }
366
367     void loadStatements() {
368         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
369
370         switch (inProgressPhase) {
371             case SOURCE_PRE_LINKAGE:
372                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
373                 break;
374             case SOURCE_LINKAGE:
375                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
376                     getRootVersion());
377                 break;
378             case STATEMENT_DEFINITION:
379                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
380                     prefixes(), getRootVersion());
381                 break;
382             case FULL_DECLARATION:
383                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
384                     getRootVersion());
385                 break;
386             default:
387                 break;
388         }
389     }
390
391     private PrefixToModule preLinkagePrefixes() {
392         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
393         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
394         if (prefixToNamespaceMap == null) {
395             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
396             return null;
397         }
398
399         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
400         return preLinkagePrefixes;
401     }
402
403     private PrefixToModule prefixes() {
404         final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
405             ImportPrefixToModuleCtx.class);
406         if (allImports != null) {
407             allImports.forEach((key, value) ->
408                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
409         }
410
411         final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
412             BelongsToPrefixToModuleCtx.class);
413         if (allBelongsTo != null) {
414             allBelongsTo.forEach((key, value) ->
415                 prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
416         }
417
418         return prefixToModuleMap;
419     }
420
421     private QNameToStatementDefinition stmtDef() {
422         // regular YANG statements and extension supports added
423         final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
424         qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
425         qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
426
427         // No further actions needed
428         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
429             return qnameToStmtDefMap;
430         }
431
432         // We need to any and all extension statements which have been declared in the context
433         final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
434                 StatementDefinitionNamespace.class);
435         if (extensions != null) {
436             extensions.forEach((qname, support) -> {
437                 final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
438                 if (existing != null) {
439                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
440                 } else {
441                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
442                 }
443             });
444         }
445
446         return qnameToStmtDefMap;
447     }
448
449     public Set<YangVersion> getSupportedVersions() {
450         return currentContext.getSupportedVersions();
451     }
452
453     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
454         currentContext.addMutableStmtToSeal(mutableStatement);
455     }
456
457     Collection<SourceIdentifier> getRequiredSources() {
458         return root.getRequiredSources();
459     }
460
461     SourceIdentifier getRootIdentifier() {
462         return root.getRootIdentifier();
463     }
464 }