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