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