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