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