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