96d26f7c0ce9847f826d33660e9a9b185ca5dd59
[yangtools.git] / parser / 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.Optional;
18 import java.util.stream.Stream;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
24 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementOrigin;
27 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
28 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
29
30 /**
31  * An inference context associated with an instance of a statement.
32  *
33  * @param <A> Argument type
34  * @param <D> Declared Statement representation
35  * @param <E> Effective Statement representation
36  */
37 public interface StmtContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
38         extends NamespaceStmtCtx, BoundStmtCtxCompat<A, D> {
39     @Deprecated(forRemoval = true)
40     default @NonNull StatementDefinition getPublicDefinition() {
41         return publicDefinition();
42     }
43
44     @Deprecated(forRemoval = true)
45     default @NonNull StatementOrigin getStatementSource() {
46         return origin();
47     }
48
49     @Deprecated(forRemoval = true)
50     default @NonNull StatementSourceReference getStatementSourceReference() {
51         return sourceReference();
52     }
53
54     /**
55      * Return the statement argument in literal format.
56      *
57      * @return raw statement argument string, or null if this statement does not have an argument.
58      * @deprecated Use {@link #rawArgument()} instead.
59      */
60     @Deprecated(forRemoval = true)
61     default @Nullable String rawStatementArgument() {
62         return rawArgument();
63     }
64
65     /**
66      * Return the statement argument in literal format.
67      *
68      * @return raw statement argument string
69      * @throws VerifyException if this statement does not have an argument
70      * @deprecated Use {@link #getRawArgument()} instead.
71      */
72     @Deprecated(forRemoval = true)
73     default @NonNull String coerceRawStatementArgument() {
74         return getRawArgument();
75     }
76
77     /**
78      * Return the statement argument.
79      *
80      * @return statement argument, or null if this statement does not have an argument
81      * @deprecated Use {@link #argument()} instead.
82      */
83     @Deprecated(forRemoval = true)
84     default @Nullable A getStatementArgument() {
85         return argument();
86     }
87
88     /**
89      * Return the statement argument in literal format.
90      *
91      * @return raw statement argument string
92      * @throws VerifyException if this statement does not have an argument
93      * @deprecated Use {@link #getArgument()} instead.
94      */
95     @Deprecated(forRemoval = true)
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     /**
118      * Returns the model root for this statement.
119      *
120      * @return root context of statement
121      */
122     @NonNull RootStmtContext<?, ?, ?> getRoot();
123
124     /**
125      * Return declared substatements. These are the statements which are explicitly written in the source model, but
126      * reflect implicit containment statements as well. To but that statement into practical terms, this snippet:
127      * <pre>
128      *   <code>
129      *     choice foo {
130      *       container bar;
131      *     }
132      *   </code>
133      * </pre>
134      * reports the same structure as the canonical verbose equivalent:
135      * <pre>
136      *   <code>
137      *     choice foo {
138      *       case bar {
139      *         container bar;
140      *       }
141      *     }
142      *   </code>
143      * </pre>
144      * Returned collection is therefore well suited for reasoning about the schema tree. It is not appropriate for
145      * populating populating {@link DeclaredStatement#declaredSubstatements()}.
146      *
147      * @return Collection of declared substatements
148      */
149     @NonNull Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements();
150
151     /**
152      * Return effective substatements. These are the statements which are added as this statement's substatements
153      * complete their effective model phase.
154      *
155      * @return Collection of declared substatements
156      */
157     @NonNull Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements();
158
159     default Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
160         return Iterables.concat(declaredSubstatements(), effectiveSubstatements());
161     }
162
163     default Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
164         return Streams.concat(declaredSubstatements().stream(), effectiveSubstatements().stream());
165     }
166
167     /**
168      * Return the {@link EffectiveStatement} for statement context, creating it if required. Implementations of this
169      * method are required to memoize the returned object, so that subsequent invocation return the same object.
170      *
171      * <p>
172      * If {@link #isSupportedToBuildEffective()} returns {@code false}, this method's behaviour is undefined.
173      *
174      * @return Effective statement instance.
175      */
176     @NonNull E buildEffective();
177
178     boolean isSupportedToBuildEffective();
179
180     boolean isSupportedByFeatures();
181
182     Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement();
183
184     /*
185      * FIXME: YANGTOOLS-784: the next three methods are closely related to the copy process:
186      *        - copyHistory() is a brief summary of what went on
187      *        - getOriginalContext() points to the CopyHistory.ORIGINAL
188      *        - getPreviousCopyCtx() points to the immediate predecessor forming a singly-linked list terminated
189      *          at getOriginalContext()
190      *
191      *        When implementing YANGTOOLS-784, this needs to be taken into account and properly forwarded through
192      *        intermediate MutableTrees. Also note this closely relates to current namespace context, as taken into
193      *        account when creating the argument. At least parts of this are only needed during buildEffective()
194      *        and hence should become arguments to that method.
195      */
196
197     /**
198      * Return the statement context of the original definition, if this statement is an instantiated copy.
199      *
200      * @return Original definition, if this statement was copied.
201      */
202     Optional<StmtContext<A, D, E>> getOriginalCtx();
203
204     /**
205      * Return the context of the previous copy of this statement -- effectively walking towards the source origin
206      * of this statement.
207      *
208      * @return Context of the previous copy of this statement, if this statement has been copied.
209      */
210     Optional<StmtContext<A, D, E>> getPreviousCopyCtx();
211
212     /**
213      * Create a replica of this statement as a substatement of specified {@code parent}. The replica must not be
214      * modified and acts as a source of {@link EffectiveStatement} from outside of {@code parent}'s subtree.
215      *
216      * @param parent Parent of the replica statement
217      * @return replica of this statement
218      * @throws IllegalArgumentException if this statement cannot be replicated into parent, for example because it
219      *                                  comes from an alien implementation.
220      */
221     @NonNull Mutable<A, D, E> replicaAsChildOf(Mutable<?, ?, ?> parent);
222
223     @Beta
224     @NonNull Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(Mutable<?, ?, ?> parent, CopyType type,
225             @Nullable QNameModule targetModule);
226
227     ModelProcessingPhase getCompletedPhase();
228
229     /**
230      * An mutable view of an inference context associated with an instance of a statement.
231      *
232      * @param <A> Argument type
233      * @param <D> Declared Statement representation
234      * @param <E> Effective Statement representation
235      */
236     interface Mutable<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
237             extends StmtContext<A, D, E> {
238
239         @Override
240         Mutable<?, ?, ?> getParentContext();
241
242         @Override
243         default Mutable<?, ?, ?> coerceParentContext() {
244             return verifyNotNull(getParentContext(), "Root context %s does not have a parent", this);
245         }
246
247         /**
248          * Associate a value with a key within a namespace.
249          *
250          * @param type Namespace type
251          * @param key Key
252          * @param value value
253          * @param <K> namespace key type
254          * @param <V> namespace value type
255          * @param <N> namespace type
256          * @param <T> key type
257          * @param <U> value type
258          * @throws NamespaceNotAvailableException when the namespace is not available.
259          */
260         <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(Class<@NonNull N> type,
261                 T key, U value);
262
263         @Override
264         RootStmtContext.Mutable<?, ?, ?> getRoot();
265
266         /**
267          * Create a child sub-statement, which is a child of this statement, inheriting all attributes from specified
268          * child and recording copy type. Resulting object may only be added as a child of this statement.
269          *
270          * @param stmt Statement to be used as a template
271          * @param type Type of copy to record in history
272          * @param targetModule Optional new target module
273          * @return copy of statement considering {@link CopyType} (augment, uses)
274          *
275          * @throws IllegalArgumentException if stmt cannot be copied into this statement, for example because it comes
276          *                                  from an alien implementation.
277          * @throws org.opendaylight.yangtools.yang.parser.spi.source.SourceException instance of SourceException
278          */
279         Mutable<?, ?, ?> childCopyOf(StmtContext<?, ?, ?> stmt, CopyType type, @Nullable QNameModule targetModule);
280
281         /**
282          * Create a child sub-statement, which is a child of this statement, inheriting all attributes from specified
283          * child and recording copy type. Resulting object may only be added as a child of this statement.
284          *
285          * @param stmt Statement to be used as a template
286          * @param type Type of copy to record in history
287          * @return copy of statement considering {@link CopyType} (augment, uses)
288          *
289          * @throws IllegalArgumentException if stmt cannot be copied into this statement, for example because it comes
290          *                                  from an alien implementation.
291          * @throws org.opendaylight.yangtools.yang.parser.spi.source.SourceException instance of SourceException
292          */
293         default Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type) {
294             return childCopyOf(stmt, type, null);
295         }
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 required module. Based on these dependencies are collected required sources from library sources.
345          *
346          * @param dependency
347          *            SourceIdentifier of module required by current root
348          *            context
349          */
350         /*
351          * FIXME: this method is used solely during SOURCE_PRE_LINKAGE reactor phase and does not have a corresponding
352          *        getter -- which makes it rather strange. At some point this method needs to be deprecated and its
353          *        users migrated to use proper global namespace.
354          */
355         void addRequiredSource(SourceIdentifier dependency);
356
357         // YANG example: RPC/action statements always have 'input' and 'output' defined
358         @Beta
359         <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
360             @NonNull Mutable<X, Y, Z> addEffectiveSubstatement(StatementSupport<X, Y, Z> support, @Nullable X arg);
361
362         /**
363          * Adds an effective statement to collection of substatements.
364          *
365          * @param substatement substatement
366          * @throws IllegalStateException if added in declared phase
367          * @throws NullPointerException if statement parameter is null
368          */
369         void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
370
371         /**
372          * Adds an effective statement to collection of substatements.
373          *
374          * @param statements substatements
375          * @throws IllegalStateException if added in declared phase
376          * @throws NullPointerException if statement parameter is null
377          */
378         void addEffectiveSubstatements(Collection<? extends Mutable<?, ?, ?>> statements);
379
380         @Beta
381         void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
382
383         /**
384          * Removes a statement context from the effective substatements based on its statement definition (i.e statement
385          * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
386          * definition and statement argument match with one of the effective substatements' statement definition
387          * and argument.
388          *
389          * <p>
390          * If the statementArg parameter is null, the statement context is removed based only on its statement
391          * definition.
392          *
393          * @param statementDef statement definition of the statement context to remove
394          * @param statementArg statement argument of the statement context to remove
395          */
396         @Beta
397         void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef, String statementArg);
398
399         @Beta
400         // FIXME: this information should be exposed as a well-known Namespace
401         boolean hasImplicitParentSupport();
402
403         @Beta
404         StmtContext<?, ?, ?> wrapWithImplicit(StmtContext<?, ?, ?> original);
405
406         void addAsEffectOfStatement(Collection<? extends StmtContext<?, ?, ?>> ctxs);
407
408         /**
409          * Set identifier of current root context.
410          *
411          * @param identifier
412          *            of current root context, must not be null
413          */
414         void setRootIdentifier(SourceIdentifier identifier);
415
416         void setUnsupported();
417     }
418 }