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