Upstream StmtContextUtils.producesDeclared()
[yangtools.git] / yang / yang-parser-spi / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / StmtContext.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.spi.meta;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.VerifyException;
14 import com.google.common.collect.Iterables;
15 import com.google.common.collect.Streams;
16 import java.util.Collection;
17 import java.util.Map;
18 import java.util.Optional;
19 import java.util.stream.Stream;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.yangtools.yang.common.QNameModule;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
30 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
31 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
32
33 /**
34  * An inference context associated with an instance of a statement.
35  *
36  * @param <A> Argument type
37  * @param <D> Declared Statement representation
38  * @param <E> Effective Statement representation
39  */
40 public interface StmtContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> {
41     /**
42      * Returns the origin of the statement.
43      *
44      * @return origin of statement
45      */
46     @NonNull StatementSource getStatementSource();
47
48     /**
49      * Returns a reference to statement source.
50      *
51      * @return reference of statement source
52      */
53     @NonNull StatementSourceReference getStatementSourceReference();
54
55     /**
56      * See {@link StatementSupport#getPublicView()}.
57      */
58     @NonNull StatementDefinition getPublicDefinition();
59
60     /**
61      * Return the parent statement context, or null if this is the root statement.
62      *
63      * @return context of parent of statement, or null if this is the root statement.
64      */
65     @Nullable StmtContext<?, ?, ?> getParentContext();
66
67     /**
68      * Return the parent statement context, forcing a VerifyException if this is the root statement.
69      *
70      * @return context of parent of statement
71      * @throws VerifyException if this statement is the root statement
72      */
73     default @NonNull StmtContext<?, ?, ?> coerceParentContext() {
74         return verifyNotNull(getParentContext(), "Root context %s does not have a parent", this);
75     }
76
77     /**
78      * Return the statement argument in literal format.
79      *
80      * @return raw statement argument string, or null if this statement does not have an argument.
81      */
82     @Nullable String rawStatementArgument();
83
84     /**
85      * Return the statement argument in literal format.
86      *
87      * @return raw statement argument string
88      * @throws VerifyException if this statement does not have an argument
89      */
90     default @NonNull String coerceRawStatementArgument() {
91         return verifyNotNull(rawStatementArgument(), "Statement context %s does not have an argument", this);
92     }
93
94     /**
95      * Return the statement argument.
96      *
97      * @return statement argument, or null if this statement does not have an argument
98      */
99     @Nullable A getStatementArgument();
100
101     /**
102      * Return the statement argument in literal format.
103      *
104      * @return raw statement argument string
105      * @throws VerifyException if this statement does not have an argument
106      */
107     default @NonNull A coerceStatementArgument() {
108         return verifyNotNull(getStatementArgument(), "Statement context %s does not have an argument", this);
109     }
110
111     default <X, Y extends DeclaredStatement<X>> boolean producesDeclared(final Class<? super Y> type) {
112         return type.isAssignableFrom(getPublicDefinition().getDeclaredRepresentationClass());
113     }
114
115     default <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<A, D>> boolean producesEffective(
116             final Class<? super Z> type) {
117         return type.isAssignableFrom(getPublicDefinition().getEffectiveRepresentationClass());
118     }
119
120     /**
121      * Return the {@link SchemaPath} of this statement. Not all statements have a SchemaPath, in which case
122      * {@link Optional#empty()} is returned.
123      *
124      * @return Optional SchemaPath
125      */
126     @NonNull Optional<SchemaPath> getSchemaPath();
127
128     boolean isConfiguration();
129
130     boolean isEnabledSemanticVersioning();
131
132     /**
133      * Return a value associated with specified key within a namespace.
134      *
135      * @param type Namespace type
136      * @param key Key
137      * @param <K> namespace key type
138      * @param <V> namespace value type
139      * @param <N> namespace type
140      * @param <T> key type
141      * @return Value, or null if there is no element
142      * @throws NamespaceNotAvailableException when the namespace is not available.
143      */
144     <K, V, T extends K, N extends IdentifierNamespace<K, V>> @Nullable V getFromNamespace(Class<N> type, T key);
145
146     <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(Class<N> type);
147
148     <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(Class<N> type);
149
150     @NonNull StmtContext<?, ?, ?> getRoot();
151
152     /**
153      * Return declared substatements. These are the statements which are explicitly written in the source model.
154      *
155      * @return Collection of declared substatements
156      */
157     @NonNull Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements();
158
159     /**
160      * Return effective substatements. These are the statements which are added as this statement's substatements
161      * complete their effective model phase.
162      *
163      * @return Collection of declared substatements
164      */
165     @NonNull Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements();
166
167     default Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
168         return Iterables.concat(declaredSubstatements(), effectiveSubstatements());
169     }
170
171     default Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
172         return Streams.concat(declaredSubstatements().stream(), effectiveSubstatements().stream());
173     }
174
175     /**
176      * Builds {@link DeclaredStatement} for statement context.
177      */
178     D buildDeclared();
179
180     /**
181      * Builds {@link EffectiveStatement} for statement context.
182      */
183     E buildEffective();
184
185     boolean isSupportedToBuildEffective();
186
187     boolean isSupportedByFeatures();
188
189     Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement();
190
191     /*
192      * FIXME: YANGTOOLS-784: the next three methods are closely related to the copy process:
193      *        - getCopyHistory() is a brief summary of what went on
194      *        - getOriginalContext() points to the CopyHistory.ORIGINAL
195      *        - getPreviousCopyCtx() points to the immediate predecessor forming a singly-linked list terminated
196      *          at getOriginalContext()
197      *
198      *        When implementing YANGTOOLS-784, this needs to be taken into account and properly forwarded through
199      *        intermediate MutableTrees. Also note this closely relates to current namespace context, as taken into
200      *        account when creating the argument. At least parts of this are only needed during buildEffective()
201      *        and hence should become arguments to that method.
202      */
203
204     /**
205      * Return the executive summary of the copy process that has produced this context.
206      *
207      * @return A simplified summary of the copy process.
208      */
209     CopyHistory getCopyHistory();
210
211     /**
212      * Return the statement context of the original definition, if this statement is an instantiated copy.
213      *
214      * @return Original definition, if this statement was copied.
215      */
216     // FIXME: 5.0.0: this should return Optional<? extends StmtContext<A, D, E>>, is that feasible?
217     Optional<StmtContext<?, ?, ?>> getOriginalCtx();
218
219     /**
220      * Return the context of the previous copy of this statement -- effectively walking towards the source origin
221      * of this statement.
222      *
223      * @return Context of the previous copy of this statement, if this statement has been copied.
224      */
225     // FIXME: 5.0.0: this should return Optional<? extends StmtContext<A, D, E>>
226     Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx();
227
228     ModelProcessingPhase getCompletedPhase();
229
230     /**
231      * Return version of root statement context.
232      *
233      * @return version of root statement context
234      */
235     @NonNull YangVersion getRootVersion();
236
237     /**
238      * An mutable view of an inference context associated with an instance of a statement.
239      *
240      * @param <A> Argument type
241      * @param <D> Declared Statement representation
242      * @param <E> Effective Statement representation
243      */
244     interface Mutable<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
245             extends StmtContext<A, D, E> {
246
247         @Override
248         Mutable<?, ?, ?> getParentContext();
249
250         @Override
251         default Mutable<?, ?, ?> coerceParentContext() {
252             return verifyNotNull(getParentContext(), "Root context %s does not have a parent", this);
253         }
254
255         /**
256          * Associate a value with a key within a namespace.
257          *
258          * @param type Namespace type
259          * @param key Key
260          * @param value value
261          * @param <K> namespace key type
262          * @param <V> namespace value type
263          * @param <N> namespace type
264          * @param <T> key type
265          * @param <U> value type
266          * @throws NamespaceNotAvailableException when the namespace is not available.
267          */
268         <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(Class<N> type, T key,
269                 U value);
270
271         @Override
272         Mutable<?, ?, ?> getRoot();
273
274         /**
275          * Create a child sub-statement, which is a child of this statement, inheriting all attributes from specified
276          * child and recording copy type. Resulting object may only be added as a child of this statement.
277          *
278          * @param stmt Statement to be used as a template
279          * @param type Type of copy to record in history
280          * @param targetModule Optional new target module
281          * @return copy of statement considering {@link CopyType} (augment, uses)
282          *
283          * @throws IllegalArgumentException if stmt cannot be copied into this statement, for example because it comes
284          *                                  from an alien implementation.
285          * @throws org.opendaylight.yangtools.yang.parser.spi.source.SourceException instance of SourceException
286          */
287         // FIXME: 5.0.0: remove generic arguments X, Y, Z. Callers should not care, as the returned copy can actually
288         //               be an encapsulating implicit statement.
289         <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
290                 StmtContext<X, Y, Z> stmt, CopyType type, @Nullable QNameModule targetModule);
291
292         /**
293          * Create a child sub-statement, which is a child of this statement, inheriting all attributes from specified
294          * child and recording copy type. Resulting object may only be added as a child of this statement.
295          *
296          * @param stmt Statement to be used as a template
297          * @param type Type of copy to record in history
298          * @return copy of statement considering {@link CopyType} (augment, uses)
299          *
300          * @throws IllegalArgumentException if stmt cannot be copied into this statement, for example because it comes
301          *                                  from an alien implementation.
302          * @throws org.opendaylight.yangtools.yang.parser.spi.source.SourceException instance of SourceException
303          */
304         default <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
305                 final StmtContext<X, Y, Z> stmt, final CopyType type) {
306             return childCopyOf(stmt, type, null);
307         }
308
309         @Beta
310         @NonNull Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(Mutable<?, ?, ?> parent, CopyType type,
311                 @Nullable QNameModule targetModule);
312
313         @Override
314         default Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
315             return mutableDeclaredSubstatements();
316         }
317
318         @NonNull Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements();
319
320         @Override
321         default Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
322             return mutableEffectiveSubstatements();
323         }
324
325         @NonNull Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements();
326
327         /**
328          * Create a new inference action to be executed during specified phase. The action cannot be cancelled
329          * and will be executed even if its definition remains incomplete. The specified phase cannot complete until
330          * this action is resolved. If the action cannot be resolved, model processing will fail.
331          *
332          * @param phase Target phase in which the action will resolved.
333          * @return A new action builder.
334          * @throws NullPointerException if the specified phase is null
335          */
336         @NonNull ModelActionBuilder newInferenceAction(@NonNull ModelProcessingPhase phase);
337
338         /**
339          * Adds s statement to namespace map with a key.
340          *
341          * @param namespace
342          *            {@link StatementNamespace} child that determines namespace to be added to
343          * @param key
344          *            of type according to namespace class specification
345          * @param stmt
346          *            to be added to namespace map
347          */
348         <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(Class<N> namespace, KT key,
349                 StmtContext<?, ?, ?> stmt);
350
351         /**
352          * Set version of root statement context.
353          *
354          * @param version
355          *            of root statement context
356          */
357         void setRootVersion(YangVersion version);
358
359         /**
360          * Add mutable statement to seal. Each mutable statement must be sealed
361          * as the last step of statement parser processing.
362          *
363          * @param mutableStatement
364          *            mutable statement which should be sealed
365          */
366         void addMutableStmtToSeal(MutableStatement mutableStatement);
367
368         /**
369          * Add required module. Based on these dependencies are collected required sources from library sources.
370          *
371          * @param dependency
372          *            SourceIdentifier of module required by current root
373          *            context
374          */
375         /*
376          * FIXME: this method is used solely during SOURCE_PRE_LINKAGE reactor phase and does not have a corresponding
377          *        getter -- which makes it rather strange. At some point this method needs to be deprecated and its
378          *        users migrated to use proper global namespace.
379          */
380         void addRequiredSource(SourceIdentifier dependency);
381
382         void addAsEffectOfStatement(StmtContext<?, ?, ?> ctx);
383
384         void addAsEffectOfStatement(Collection<? extends StmtContext<?, ?, ?>> ctxs);
385
386         /**
387          * Set identifier of current root context.
388          *
389          * @param identifier
390          *            of current root context, must not be null
391          */
392         void setRootIdentifier(SourceIdentifier identifier);
393
394         void setIsSupportedToBuildEffective(boolean isSupportedToBuild);
395
396         // FIXME: this seems to be unused, but looks useful.
397         void setCompletedPhase(ModelProcessingPhase completedPhase);
398     }
399 }