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