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