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