Bug 6131 - NPE on malformed yang model
[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.collect.HashMultimap;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Multimap;
14 import java.net.URI;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Objects;
22 import javax.annotation.Nullable;
23 import org.opendaylight.yangtools.concepts.Mutable;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.QNameModule;
26 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
30 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ExtensionStatement;
32 import org.opendaylight.yangtools.yang.parser.spi.ExtensionNamespace;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ImportedNamespaceContext;
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.NamespaceBehaviour;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
47 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
48 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
49 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
50 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
52 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
53 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
54 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
55 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
58 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
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 final StatementStreamSource source;
74     private final BuildGlobalContext currentContext;
75     private final Collection<NamespaceStorageNode> importedNamespaces = new ArrayList<>();
76     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
77
78     private RootStatementContext<?, ?, ?> root;
79
80     private ModelProcessingPhase inProgressPhase;
81     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
82     private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
83     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
84
85
86     SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
87         this.source = source;
88         this.currentContext = currentContext;
89     }
90
91     public boolean isEnabledSemanticVersioning(){
92         return currentContext.isEnabledSemanticVersioning();
93     }
94
95     ModelProcessingPhase getInProgressPhase() {
96         return inProgressPhase;
97     }
98
99     StatementDefinitionContext<?, ?, ?> getDefinition(final QName name) {
100         return currentContext.getStatementDefinition(name);
101     }
102
103     ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
104                                                 final StatementSourceReference ref) {
105         StatementDefinitionContext<?, ?, ?> def = getDefinition(name);
106
107         if (def == null) {
108             // unknown-stmts (from import, include or local-scope)
109             if (qNameToStmtDefMap.get(name) != null) {
110                 final StatementContextBase<?, ?, ?> extension =
111                         (StatementContextBase<?, ?, ?>) currentContext.getAllFromNamespace(ExtensionNamespace.class).get(name);
112
113                 SourceException.throwIfNull(extension, current.getStatementSourceReference(), "Extension %s not found",
114                     name);
115
116                 final QName arg = (QName) extension.getStatementArgument();
117                 final QName qName = current.getFromNamespace(QNameCacheNamespace.class,
118                     QName.create(arg, extension.getIdentifier().getArgument()));
119
120                 def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
121                     getNewStatementDefinition(qName)));
122             } else {
123                 // type-body-stmts
124                 def = resolveTypeBodyStmts(name.getLocalName());
125             }
126         } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
127             final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
128
129             def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
130                 getNewStatementDefinition(qName)));
131         }
132
133         Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
134         if (current == null) {
135             return createDeclaredRoot(def, ref);
136         }
137         return current.substatementBuilder(def, ref);
138     }
139
140     // FIXME: This should be populated differently
141     StatementDefinition getNewStatementDefinition(final QName qName) {
142         return new ModelDefinedStatementDefinition(qName);
143     }
144
145     @SuppressWarnings({"rawtypes", "unchecked"})
146     private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
147                                                        final StatementSourceReference ref) {
148         return new ContextBuilder(def, ref) {
149
150             @Override
151             public StatementContextBase build() {
152                 if (root == null) {
153                     root = new RootStatementContext(this, SourceSpecificContext.this);
154                 } else {
155                     Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
156                             "Root statement was already defined as %s.", root.getIdentifier());
157                 }
158                 root.resetLists();
159                 return root;
160             }
161
162         };
163     }
164
165     RootStatementContext<?, ?, ?> getRoot() {
166         return root;
167     }
168
169     DeclaredStatement<?> buildDeclared() {
170         return root.buildDeclared();
171     }
172
173     EffectiveStatement<?, ?> buildEffective() {
174         return root.buildEffective();
175     }
176
177     void startPhase(final ModelProcessingPhase phase) {
178         @Nullable
179         final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
180         Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
181         Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
182         inProgressPhase = phase;
183     }
184
185     @Override
186     public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
187            final V value) {
188         if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
189             importedNamespaces.add((NamespaceStorageNode) value);
190         }
191         getRoot().addToLocalStorage(type, key, value);
192     }
193
194     @Override
195     public StorageNodeType getStorageNodeType() {
196         return StorageNodeType.SOURCE_LOCAL_SPECIAL;
197     }
198
199     @Override
200     public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
201         final V potentialLocal = getRoot().getFromLocalStorage(type, key);
202         if (potentialLocal != null) {
203             return potentialLocal;
204         }
205         for (final NamespaceStorageNode importedSource : importedNamespaces) {
206             final V potential = importedSource.getFromLocalStorage(type, key);
207             if (potential != null) {
208                 return potential;
209             }
210         }
211         return null;
212     }
213
214     @Nullable
215     @Override
216     public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
217         final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
218
219         if (potentialLocal != null) {
220             return potentialLocal;
221         }
222
223         for (final NamespaceStorageNode importedSource : importedNamespaces) {
224             final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
225
226             if (potential != null) {
227                 return potential;
228             }
229         }
230         return null;
231     }
232
233     @Override
234     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
235             final Class<N> type) {
236         return currentContext.getNamespaceBehaviour(type);
237     }
238
239     @Override
240     public NamespaceStorageNode getParentNamespaceStorage() {
241         return currentContext;
242     }
243
244     PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
245         final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
246
247         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
248
249         Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
250         final boolean phaseCompleted = root.tryToCompletePhase(phase);
251
252         hasProgressed = (tryToProgress(currentPhaseModifiers) | hasProgressed);
253
254         if (phaseCompleted && (currentPhaseModifiers.isEmpty())) {
255             finishedPhase = phase;
256             return PhaseCompletionProgress.FINISHED;
257
258         }
259         if (hasProgressed) {
260             return PhaseCompletionProgress.PROGRESS;
261         }
262         return PhaseCompletionProgress.NO_PROGRESS;
263     }
264
265
266     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
267         boolean hasProgressed = false;
268
269         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
270         while (modifier.hasNext()) {
271             if (modifier.next().tryApply()) {
272                 modifier.remove();
273                 hasProgressed = true;
274             }
275         }
276
277         return hasProgressed;
278
279     }
280
281     ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
282         final ModifierImpl action = new ModifierImpl(phase);
283         modifiers.put(phase, action);
284         return action;
285     }
286
287     @Override
288     public String toString() {
289         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
290                 + finishedPhase + "]";
291     }
292
293     SourceException failModifiers(final ModelProcessingPhase identifier) {
294         final List<SourceException> exceptions = new ArrayList<>();
295         for (final ModifierImpl mod : modifiers.get(identifier)) {
296             try {
297                 mod.failModifier();
298             } catch (final SourceException e) {
299                 exceptions.add(e);
300             }
301         }
302
303         final String message = String.format("Yang model processing phase %s failed", identifier);
304         if (exceptions.isEmpty()) {
305             return new InferenceException(message, root.getStatementSourceReference());
306         }
307
308         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
309             exceptions.get(0));
310         final Iterator<SourceException> it = exceptions.listIterator(1);
311         while (it.hasNext()) {
312             e.addSuppressed(it.next());
313         }
314
315         return e;
316     }
317
318     void loadStatements() throws SourceException {
319         switch (inProgressPhase) {
320             case SOURCE_PRE_LINKAGE:
321                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
322                 break;
323             case SOURCE_LINKAGE:
324                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
325                 break;
326             case STATEMENT_DEFINITION:
327                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
328                 break;
329             case FULL_DECLARATION:
330                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
331                 break;
332             default:
333                 break;
334         }
335     }
336
337     private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
338         switch (typeArgument) {
339             case TypeUtils.DECIMAL64:
340                 return new StatementDefinitionContext<>(new Decimal64SpecificationImpl.Definition());
341             case TypeUtils.UNION:
342                 return new StatementDefinitionContext<>(new UnionSpecificationImpl.Definition());
343             case TypeUtils.ENUMERATION:
344                 return new StatementDefinitionContext<>(new EnumSpecificationImpl.Definition());
345             case TypeUtils.LEAF_REF:
346                 return new StatementDefinitionContext<>(new LeafrefSpecificationImpl.Definition());
347             case TypeUtils.BITS:
348                 return new StatementDefinitionContext<>(new BitsSpecificationImpl.Definition());
349             case TypeUtils.IDENTITY_REF:
350                 return new StatementDefinitionContext<>(new IdentityRefSpecificationImpl.Definition());
351             case TypeUtils.INSTANCE_IDENTIFIER:
352                 return new StatementDefinitionContext<>(new InstanceIdentifierSpecificationImpl.Definition());
353             default:
354                 return null;
355         }
356     }
357
358     private PrefixToModule preLinkagePrefixes() {
359         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
360         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
361         if (prefixToNamespaceMap == null) {
362             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
363             return null;
364         }
365         for (final Entry<String, URI> prefixToNamespace : prefixToNamespaceMap.entrySet()) {
366             preLinkagePrefixes.put(prefixToNamespace.getKey(), QNameModule.create(prefixToNamespace.getValue(), null));
367         }
368
369         return preLinkagePrefixes;
370     }
371
372     private PrefixToModule prefixes() {
373         final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
374                 .class);
375         final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
376                 (BelongsToPrefixToModuleIdentifier.class);
377         if (belongsToPrefixes != null) {
378             allPrefixes.putAll(belongsToPrefixes);
379         }
380
381         for (final Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
382             final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
383                 stringModuleIdentifierEntry.getValue());
384             prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
385         }
386         return prefixToModuleMap;
387     }
388
389     private QNameToStatementDefinition stmtDef() {
390         // regular YANG statements and extension supports added
391         final ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
392                 inProgressPhase).getDefinitions();
393         for (final Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
394             qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
395         }
396
397         // extensions added
398         if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
399             final Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions =
400                     currentContext.getAllFromNamespace(ExtensionNamespace.class);
401             if (extensions != null) {
402                 for (final Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension :
403                     extensions.entrySet()) {
404                     if(qNameToStmtDefMap.get(extension.getKey()) == null) {
405                         qNameToStmtDefMap.put((extension.getKey()),
406                         (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension.getValue()).definition()
407                         .getFactory());
408                     }
409                 }
410             }
411         }
412
413         return qNameToStmtDefMap;
414     }
415 }