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