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