cfbd93377cf5e4adecc7db49bf2b040031e07b83
[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.base.Verify;
12 import com.google.common.collect.HashMultimap;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableTable;
15 import com.google.common.collect.Multimap;
16 import com.google.common.collect.Table;
17 import java.net.URI;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.Optional;
25 import java.util.Set;
26 import javax.annotation.Nullable;
27 import org.opendaylight.yangtools.concepts.Mutable;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.YangConstants;
31 import org.opendaylight.yangtools.yang.common.YangVersion;
32 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
34 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
37 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
48 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
49 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
55 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
56 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
57 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
58 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
59 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
64 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
65 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
66 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
67 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
68 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
69 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
70 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
71 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
72 import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.IdentityrefSpecificationRfc7950Support;
73 import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.LeafrefSpecificationRfc7950Support;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
78
79     public enum PhaseCompletionProgress {
80         NO_PROGRESS,
81         PROGRESS,
82         FINISHED
83     }
84
85     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
86     private static final Table<YangVersion, String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
87             ImmutableTable.<YangVersion, String, StatementSupport<?, ?, ?>>builder()
88             .put(YangVersion.VERSION_1, TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
89             .put(YangVersion.VERSION_1, TypeUtils.UNION, new UnionSpecificationImpl.Definition())
90             .put(YangVersion.VERSION_1, TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
91             .put(YangVersion.VERSION_1, TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
92             .put(YangVersion.VERSION_1_1, TypeUtils.LEAF_REF, new LeafrefSpecificationRfc7950Support())
93             .put(YangVersion.VERSION_1, TypeUtils.BITS, new BitsSpecificationImpl.Definition())
94             .put(YangVersion.VERSION_1, TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
95             .put(YangVersion.VERSION_1_1, TypeUtils.IDENTITY_REF, new IdentityrefSpecificationRfc7950Support())
96             .put(YangVersion.VERSION_1, TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
97                     .build();
98
99     private static final QName TYPE = YangStmtMapping.TYPE.getStatementName();
100
101     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
102     private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
103     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
104     private final BuildGlobalContext currentContext;
105     private final StatementStreamSource source;
106
107     /*
108      * "imported" namespaces in this source -- this points to RootStatementContexts of
109      * - modules imported via 'import' statement
110      * - parent module, declared via 'belongs-to' statement
111      */
112     private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
113     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
114     private ModelProcessingPhase inProgressPhase;
115     private RootStatementContext<?, ?, ?> root;
116
117     SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
118         this.currentContext = Preconditions.checkNotNull(currentContext);
119         this.source = Preconditions.checkNotNull(source);
120     }
121
122     boolean isEnabledSemanticVersioning(){
123         return currentContext.isEnabledSemanticVersioning();
124     }
125
126     ModelProcessingPhase getInProgressPhase() {
127         return inProgressPhase;
128     }
129
130     StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
131             QName name, final String argument, final StatementSourceReference ref) {
132         if (current != null) {
133             // Fast path: we are entering a statement which was emitted in previous phase
134             StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
135             while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
136                 existing = existing.lookupSubstatement(childId);
137             }
138             if (existing != null) {
139                 return existing;
140             }
141         }
142
143         // FIXME: BUG-7038: Refactor/clean up this special case
144         if (TYPE.equals(name)) {
145             SourceException.throwIfNull(argument, ref, "Type statement requires an argument");
146             if (TypeUtils.isYangTypeBodyStmtString(argument)) {
147                 name = QName.create(YangConstants.RFC6020_YIN_MODULE, argument);
148             } else {
149                 name = QName.create(YangConstants.RFC6020_YIN_MODULE, TYPE.getLocalName());
150             }
151         }
152
153         StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
154         if (def == null) {
155             final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
156             if (extension != null) {
157                 def = new StatementDefinitionContext<>(extension);
158             } else {
159                 // type-body-stmts
160                 def = resolveTypeBodyStmts(name.getLocalName(), getRootVersion());
161             }
162         } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
163             /*
164              * This code wraps statements encountered inside an extension so they do not get confused with regular
165              * statements.
166              *
167              * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
168              *        this work. We really should be peeking into the extension definition to find these nodes,
169              *        as otherwise we are not reusing definitions nor support for these nodes.
170              */
171             final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
172             def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
173                 new ModelDefinedStatementDefinition(qName, argument != null)));
174         }
175
176         InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
177         if (def.hasArgument()) {
178             SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
179         } else {
180             SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
181         }
182
183         if (current != null) {
184             return current.createSubstatement(childId, def, ref, argument);
185         }
186
187         /*
188          * If root is null or root version is other than default,
189          * we need to create new root.
190          */
191         if (root == null) {
192             root = new RootStatementContext<>(this, def, ref, argument);
193         } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
194                 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
195             root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(), root.getRootIdentifier());
196         } else {
197             final QName rootStatement = root.definition().getStatementName();
198             final String rootArgument = root.rawStatementArgument();
199
200             Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
201                 && Objects.equals(argument, rootArgument),
202                 "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
203         }
204         return root;
205     }
206
207     RootStatementContext<?, ?, ?> getRoot() {
208         return root;
209     }
210
211     /**
212      * Return version of root statement context.
213      *
214      * @return version of root statement context
215      */
216     YangVersion getRootVersion() {
217         return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
218     }
219
220     DeclaredStatement<?> buildDeclared() {
221         return root.buildDeclared();
222     }
223
224     EffectiveStatement<?, ?> buildEffective() {
225         return root.buildEffective();
226     }
227
228     void startPhase(final ModelProcessingPhase phase) {
229         @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
230         Verify.verify(Objects.equals(previousPhase, finishedPhase),
231             "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
232             finishedPhase);
233
234         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
235         Preconditions.checkState(previousModifiers.isEmpty(),
236             "Previous phase %s has unresolved modifiers %s in source %s",
237             previousPhase, previousModifiers, source);
238
239         inProgressPhase = phase;
240         LOG.debug("Source {} started phase {}", source, phase);
241     }
242
243     private void updateImportedNamespaces(final Class<?> type, final Object value) {
244         if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
245             if (importedNamespaces.isEmpty()) {
246                 importedNamespaces = new ArrayList<>(1);
247             }
248
249             Verify.verify(value instanceof RootStatementContext);
250             importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
251         }
252     }
253
254     @Override
255     public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
256            final V value) {
257         // RootStatementContext takes care of IncludedModuleContext and the rest...
258         final V ret = getRoot().putToLocalStorage(type, key, value);
259         // FIXME: what about duplicates?
260         updateImportedNamespaces(type, value);
261         return ret;
262     }
263
264     @Override
265     public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
266            final V value) {
267         // RootStatementContext takes care of IncludedModuleContext and the rest...
268         final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
269         if (ret == null) {
270             updateImportedNamespaces(type, value);
271         }
272         return ret;
273     }
274
275     @Override
276     public StorageNodeType getStorageNodeType() {
277         return StorageNodeType.SOURCE_LOCAL_SPECIAL;
278     }
279
280     @Override
281     public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
282         final V potentialLocal = getRoot().getFromLocalStorage(type, key);
283         if (potentialLocal != null) {
284             return potentialLocal;
285         }
286
287         for (final NamespaceStorageNode importedSource : importedNamespaces) {
288             final V potential = importedSource.getFromLocalStorage(type, key);
289             if (potential != null) {
290                 return potential;
291             }
292         }
293         return null;
294     }
295
296     @Nullable
297     @Override
298     public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
299         final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
300         if (potentialLocal != null) {
301             return potentialLocal;
302         }
303
304         for (final NamespaceStorageNode importedSource : importedNamespaces) {
305             final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
306
307             if (potential != null) {
308                 return potential;
309             }
310         }
311         return null;
312     }
313
314     @Override
315     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
316             final Class<N> type) {
317         return currentContext.getNamespaceBehaviour(type);
318     }
319
320     @Override
321     public NamespaceStorageNode getParentNamespaceStorage() {
322         return currentContext;
323     }
324
325     PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
326         final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
327
328         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
329
330         Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
331         final boolean phaseCompleted = root.tryToCompletePhase(phase);
332
333         hasProgressed |= tryToProgress(currentPhaseModifiers);
334
335         if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
336             finishedPhase = phase;
337             LOG.debug("Source {} finished phase {}", source, phase);
338             return PhaseCompletionProgress.FINISHED;
339
340         }
341
342         return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
343     }
344
345     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
346         boolean hasProgressed = false;
347
348         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
349         while (modifier.hasNext()) {
350             if (modifier.next().tryApply()) {
351                 modifier.remove();
352                 hasProgressed = true;
353             }
354         }
355
356         return hasProgressed;
357     }
358
359     ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
360         final ModifierImpl action = new ModifierImpl(phase);
361         modifiers.put(phase, action);
362         return action;
363     }
364
365     @Override
366     public String toString() {
367         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
368                 + finishedPhase + "]";
369     }
370
371     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
372         final List<SourceException> exceptions = new ArrayList<>();
373         for (final ModifierImpl mod : modifiers.get(identifier)) {
374             try {
375                 mod.failModifier();
376             } catch (final SourceException e) {
377                 exceptions.add(e);
378             }
379         }
380
381         if (exceptions.isEmpty()) {
382             return Optional.empty();
383         }
384
385         final String message = String.format("Yang model processing phase %s failed", identifier);
386         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
387             exceptions.get(0));
388         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
389
390         return Optional.of(e);
391     }
392
393     void loadStatements() throws SourceException {
394         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
395
396         switch (inProgressPhase) {
397             case SOURCE_PRE_LINKAGE:
398                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
399                 break;
400             case SOURCE_LINKAGE:
401                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(), getRootVersion());
402                 break;
403             case STATEMENT_DEFINITION:
404                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
405                 break;
406             case FULL_DECLARATION:
407                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(), getRootVersion());
408                 break;
409             default:
410                 break;
411         }
412     }
413
414     private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument,
415             final YangVersion version) {
416         StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(version, typeArgument);
417
418         if (support == null) {
419             support = BUILTIN_TYPE_SUPPORTS.get(YangVersion.VERSION_1, typeArgument);
420         }
421
422         return support == null ? null : new StatementDefinitionContext<>(support);
423     }
424
425     private PrefixToModule preLinkagePrefixes() {
426         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
427         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
428         if (prefixToNamespaceMap == null) {
429             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
430             return null;
431         }
432
433         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
434         return preLinkagePrefixes;
435     }
436
437     private PrefixToModule prefixes() {
438         final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
439                 .class);
440         final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
441                 (BelongsToPrefixToModuleIdentifier.class);
442         if (belongsToPrefixes != null) {
443             allPrefixes.putAll(belongsToPrefixes);
444         }
445
446         allPrefixes.forEach((key, value) ->
447             prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
448
449         return prefixToModuleMap;
450     }
451
452     private QNameToStatementDefinition stmtDef() {
453         // regular YANG statements and extension supports added
454         final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
455         qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
456         qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
457
458         // No further actions needed
459         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
460             return qNameToStmtDefMap;
461         }
462
463         // We need to any and all extension statements which have been declared in the context
464         final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
465                 StatementDefinitionNamespace.class);
466         if (extensions != null) {
467             extensions.forEach((qname, support) -> {
468                 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
469                 if (existing != null) {
470                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
471                 } else {
472                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
473                 }
474             });
475         }
476
477         return qNameToStmtDefMap;
478     }
479
480     public Set<YangVersion> getSupportedVersions() {
481         return currentContext.getSupportedVersions();
482     }
483
484     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
485         currentContext.addMutableStmtToSeal(mutableStatement);
486     }
487
488     Collection<ModuleIdentifier> getRequiredModules() {
489         return root.getRequiredModules();
490     }
491
492     ModuleIdentifier getRootIdentifier() {
493         return root.getRootIdentifier();
494     }
495 }