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