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