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