Enhance phase sequencing assertions
[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.YangStmtMapping;
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 = YangStmtMapping.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         Verify.verify(Objects.equals(previousPhase, finishedPhase),
223             "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
224             finishedPhase);
225
226         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
227         Preconditions.checkState(previousModifiers.isEmpty(),
228             "Previous phase %s has unresolved modifiers %s in source %s",
229             previousPhase, previousModifiers, source);
230
231         inProgressPhase = phase;
232         LOG.debug("Source {} started phase {}", source, phase);
233     }
234
235     @Override
236     public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
237            final V value) {
238
239         if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
240             if (importedNamespaces.isEmpty()) {
241                 importedNamespaces = new ArrayList<>(1);
242             }
243
244             Verify.verify(value instanceof RootStatementContext);
245             importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
246         }
247
248         // RootStatementContext takes care of IncludedModuleContext and the rest...
249         getRoot().addToLocalStorage(type, key, value);
250     }
251
252     @Override
253     public StorageNodeType getStorageNodeType() {
254         return StorageNodeType.SOURCE_LOCAL_SPECIAL;
255     }
256
257     @Override
258     public <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(final Class<N> type, final K key) {
259         final V potentialLocal = getRoot().getFromLocalStorage(type, key);
260         if (potentialLocal != null) {
261             return potentialLocal;
262         }
263
264         for (final NamespaceStorageNode importedSource : importedNamespaces) {
265             final V potential = importedSource.getFromLocalStorage(type, key);
266             if (potential != null) {
267                 return potential;
268             }
269         }
270         return null;
271     }
272
273     @Nullable
274     @Override
275     public <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(final Class<N> type) {
276         final Map<K, V> potentialLocal = getRoot().getAllFromLocalStorage(type);
277         if (potentialLocal != null) {
278             return potentialLocal;
279         }
280
281         for (final NamespaceStorageNode importedSource : importedNamespaces) {
282             final Map<K, V> potential = importedSource.getAllFromLocalStorage(type);
283
284             if (potential != null) {
285                 return potential;
286             }
287         }
288         return null;
289     }
290
291     @Override
292     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
293             final Class<N> type) {
294         return currentContext.getNamespaceBehaviour(type);
295     }
296
297     @Override
298     public NamespaceStorageNode getParentNamespaceStorage() {
299         return currentContext;
300     }
301
302     PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
303         final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
304
305         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
306
307         Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
308         final boolean phaseCompleted = root.tryToCompletePhase(phase);
309
310         hasProgressed |= tryToProgress(currentPhaseModifiers);
311
312         if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
313             finishedPhase = phase;
314             LOG.debug("Source {} finished phase {}", source, phase);
315             return PhaseCompletionProgress.FINISHED;
316
317         }
318
319         return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
320     }
321
322     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
323         boolean hasProgressed = false;
324
325         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
326         while (modifier.hasNext()) {
327             if (modifier.next().tryApply()) {
328                 modifier.remove();
329                 hasProgressed = true;
330             }
331         }
332
333         return hasProgressed;
334     }
335
336     ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
337         final ModifierImpl action = new ModifierImpl(phase);
338         modifiers.put(phase, action);
339         return action;
340     }
341
342     @Override
343     public String toString() {
344         return "SourceSpecificContext [source=" + source + ", current=" + inProgressPhase + ", finished="
345                 + finishedPhase + "]";
346     }
347
348     Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
349         final List<SourceException> exceptions = new ArrayList<>();
350         for (final ModifierImpl mod : modifiers.get(identifier)) {
351             try {
352                 mod.failModifier();
353             } catch (final SourceException e) {
354                 exceptions.add(e);
355             }
356         }
357
358         if (exceptions.isEmpty()) {
359             return Optional.empty();
360         }
361
362         final String message = String.format("Yang model processing phase %s failed", identifier);
363         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
364             exceptions.get(0));
365         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
366
367         return Optional.of(e);
368     }
369
370     void loadStatements() throws SourceException {
371         LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
372
373         switch (inProgressPhase) {
374             case SOURCE_PRE_LINKAGE:
375                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
376                 break;
377             case SOURCE_LINKAGE:
378                 source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
379                 break;
380             case STATEMENT_DEFINITION:
381                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
382                 break;
383             case FULL_DECLARATION:
384                 source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
385                 break;
386             default:
387                 break;
388         }
389     }
390
391     private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
392         final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
393         return support == null ? null : new StatementDefinitionContext<>(support);
394     }
395
396     private PrefixToModule preLinkagePrefixes() {
397         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
398         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
399         if (prefixToNamespaceMap == null) {
400             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
401             return null;
402         }
403
404         prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
405         return preLinkagePrefixes;
406     }
407
408     private PrefixToModule prefixes() {
409         final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
410                 .class);
411         final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
412                 (BelongsToPrefixToModuleIdentifier.class);
413         if (belongsToPrefixes != null) {
414             allPrefixes.putAll(belongsToPrefixes);
415         }
416
417         allPrefixes.forEach((key, value) ->
418             prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
419
420         return prefixToModuleMap;
421     }
422
423     private QNameToStatementDefinition stmtDef() {
424         // regular YANG statements and extension supports added
425         final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
426         qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
427         qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
428
429         // No further actions needed
430         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
431             return qNameToStmtDefMap;
432         }
433
434         // We need to any and all extension statements which have been declared in the context
435         final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
436                 StatementDefinitionNamespace.class);
437         if (extensions != null) {
438             extensions.forEach((qname, support) -> {
439                 final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
440                 if (existing != null) {
441                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
442                 } else {
443                     LOG.debug("Source {} defined statement {} as {}", source, qname, support);
444                 }
445             });
446         }
447
448         return qNameToStmtDefMap;
449     }
450
451     public Set<YangVersion> getSupportedVersions() {
452         return currentContext.getSupportedVersions();
453     }
454 }