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