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