Tighten canReuseCurrent() contract
[yangtools.git] / parser / yang-parser-spi / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / StatementSupport.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.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.VerifyException;
15 import java.util.List;
16 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.opendaylight.yangtools.concepts.Immutable;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.model.api.meta.ArgumentDefinition;
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.parser.spi.meta.EffectiveStmtCtx.Current;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
28 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
29
30 /**
31  * Support for processing concrete YANG statement.
32  *
33  * <p>
34  * This interface is intended to be implemented by developers, which want to introduce support of statement to parser.
35  * Consider subclassing {@link AbstractStatementSupport} for easier implementation of this interface.
36  *
37  * @param <A> Argument type
38  * @param <D> Declared Statement representation
39  * @param <E> Effective Statement representation
40  */
41 public abstract class StatementSupport<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
42         implements StatementFactory<A, D, E> {
43     /**
44      * A baseline class for implementing the {@link StatementFactory#canReuseCurrent(Current, Current, List)}
45      * contract in a manner which is consistent with a statement's {@link CopyPolicy}.
46      *
47      * @param <A> Argument type
48      * @param <D> Declared Statement representation
49      */
50     public abstract static class StatementPolicy<A, D extends DeclaredStatement<A>> implements Immutable {
51         final @NonNull CopyPolicy copyPolicy;
52
53         StatementPolicy(final CopyPolicy copyPolicy) {
54             this.copyPolicy = requireNonNull(copyPolicy);
55         }
56
57         /**
58          * Return a {@link StatementPolicy} for {@link CopyPolicy#CONTEXT_INDEPENDENT}.
59          *
60          * @param <A> Argument type
61          * @param <D> Declared Statement representation
62          * @return Context-independent policy
63          */
64         @SuppressWarnings("unchecked")
65         public static final <A, D extends DeclaredStatement<A>> @NonNull StatementPolicy<A, D> contextIndependent() {
66             return (StatementPolicy<A, D>) EqualSemantics.CONTEXT_INDEPENDENT;
67         }
68
69         /**
70          * Return a {@link StatementPolicy} for {@link CopyPolicy#EXACT_REPLICA}.
71          *
72          * @param <A> Argument type
73          * @param <D> Declared Statement representation
74          * @return Exact-replica policy
75          */
76         @SuppressWarnings("unchecked")
77         public static final <A, D extends DeclaredStatement<A>> @NonNull StatementPolicy<A, D> exactReplica() {
78             return (StatementPolicy<A, D>) EqualSemantics.EXACT_REPLICA;
79         }
80
81         /**
82          * Return a {@link StatementPolicy} for {@link CopyPolicy#IGNORE}.
83          *
84          * @param <A> Argument type
85          * @param <D> Declared Statement representation
86          * @return Ignoring policy
87          */
88         @SuppressWarnings("unchecked")
89         public static final <A, D extends DeclaredStatement<A>> @NonNull StatementPolicy<A, D> ignore() {
90             return (StatementPolicy<A, D>) AlwaysFail.IGNORE;
91         }
92
93         /**
94          * Return a {@link StatementPolicy} for {@link CopyPolicy#REJECT}.
95          *
96          * @param <A> Argument type
97          * @param <D> Declared Statement representation
98          * @return Rejecting statement policy
99          */
100         @SuppressWarnings("unchecked")
101         public static final <A, D extends DeclaredStatement<A>> @NonNull StatementPolicy<A, D> reject() {
102             return (StatementPolicy<A, D>) AlwaysFail.REJECT;
103         }
104
105         /**
106          * Return a {@link StatementPolicy} for {@link CopyPolicy#DECLARED_COPY}, deferring to a
107          * {@link StatementEquality} for individual decisions.
108          *
109          * @param <A> Argument type
110          * @param <D> Declared Statement representation
111          * @param equality {@link StatementEquality} to apply to effective statements
112          * @return Equality-based statement policy
113          */
114         public static final <A, D extends DeclaredStatement<A>> @NonNull StatementPolicy<A, D> copyDeclared(
115                 final @NonNull StatementEquality<A, D> equality) {
116             return new EqualSemantics<>(equality);
117         }
118
119         /**
120          * Return a {@link StatementPolicy} for {@link CopyPolicy#DECLARED_COPY}, always performing a copy operation.
121          *
122          * @param <A> Argument type
123          * @param <D> Declared Statement representation
124          * @return Rejecting statement policy
125          */
126         @SuppressWarnings("unchecked")
127         public static final <A, D extends DeclaredStatement<A>> @NonNull StatementPolicy<A, D> alwaysCopyDeclared() {
128             return (StatementPolicy<A, D>) EqualSemantics.ALWAYS_COPY;
129         }
130
131         abstract boolean canReuseCurrent(@NonNull Current<A, D> copy, @NonNull Current<A, D> current,
132             @NonNull List<? extends EffectiveStatement<?, ?>> substatements);
133
134         private static final class AlwaysFail<A, D extends DeclaredStatement<A>> extends StatementPolicy<A, D> {
135             static final @NonNull AlwaysFail<?, ?> IGNORE = new AlwaysFail<>(CopyPolicy.IGNORE);
136             static final @NonNull AlwaysFail<?, ?> REJECT = new AlwaysFail<>(CopyPolicy.REJECT);
137
138             private AlwaysFail(final CopyPolicy copyPolicy) {
139                 super(copyPolicy);
140             }
141
142             @Override
143             boolean canReuseCurrent(final Current<A, D> copy, final Current<A, D> current,
144                     final List<? extends EffectiveStatement<?, ?>> substatements) {
145                 throw new VerifyException("This implementation should never be invoked");
146             }
147         }
148
149         private static final class EqualSemantics<A, D extends DeclaredStatement<A>> extends StatementPolicy<A, D> {
150             static final @NonNull EqualSemantics<?, ?> ALWAYS_COPY =
151                 new EqualSemantics<>((copy, stmt, substatements) -> false);
152             static final @NonNull EqualSemantics<?, ?> CONTEXT_INDEPENDENT =
153                 new EqualSemantics<>(CopyPolicy.CONTEXT_INDEPENDENT, (copy, stmt, substatements) -> true);
154             static final @NonNull EqualSemantics<?, ?> EXACT_REPLICA =
155                 new EqualSemantics<>(CopyPolicy.EXACT_REPLICA, (copy, stmt, substatements) -> true);
156
157             private final @NonNull StatementEquality<A, D> equality;
158
159             private EqualSemantics(final CopyPolicy copyPolicy, final StatementEquality<A, D> equality) {
160                 super(copyPolicy);
161                 this.equality = requireNonNull(equality);
162             }
163
164             EqualSemantics(final StatementEquality<A, D> equality) {
165                 this(CopyPolicy.DECLARED_COPY, equality);
166             }
167
168             @Override
169             boolean canReuseCurrent(final Current<A, D> copy, final Current<A, D> current,
170                     final List<? extends EffectiveStatement<?, ?>> substatements) {
171                 return equality.canReuseCurrent(copy, current, substatements);
172             }
173         }
174     }
175
176     /**
177      * Abstract base class for comparators associated with statements with a {@link CopyPolicy#DECLARED_COPY} copy
178      * policy.
179      *
180      * @param <A> Argument type
181      * @param <D> Declared Statement representation
182      */
183     @FunctionalInterface
184     public interface StatementEquality<A, D extends DeclaredStatement<A>> {
185         /**
186          * Determine whether {@code current} statement has the same semantics as the provided copy. See the contract
187          * specification of {@link StatementFactory#canReuseCurrent(Current, Current, List)}.
188          *
189          * @param copy Copy of current effective context
190          * @param current Current effective context
191          * @param substatements Current effective substatements
192          * @return True if {@code current} can be reused in place of {@code copy}, false if the copy needs to be used.
193          */
194         boolean canReuseCurrent(@NonNull Current<A, D> copy, @NonNull Current<A, D> current,
195             @NonNull List<? extends EffectiveStatement<?, ?>> substatements);
196     }
197
198     /**
199      * Projection of {@link StatementSupport}s available within a particular source. This namespace is purely virtual
200      * and its behaviour corresponds to {@link NamespaceBehaviour#rootStatementLocal(ParserNamespace)} and is always
201      * available.
202      * Its contents are derived from {@link StatementSupportBundle}s active in the current {@link ModelProcessingPhase}
203      * as well as {@link StatementDefinitions} and {@link StmtContext#yangVersion()} of the source root statement.
204      */
205     @Beta
206     public static final @NonNull ParserNamespace<QName, StatementSupport<?, ?, ?>> NAMESPACE =
207         new ParserNamespace<>("statementSupports");
208
209     private final @NonNull StatementPolicy<A, D> policy;
210     private final @NonNull StatementDefinition publicDefinition;
211     private final @NonNull CopyPolicy copyPolicy;
212
213     @Beta
214     protected StatementSupport(final StatementSupport<A, D, E> delegate) {
215         checkArgument(delegate != this);
216         publicDefinition = delegate.publicDefinition;
217         policy = delegate.policy;
218         copyPolicy = delegate.copyPolicy;
219     }
220
221     @Beta
222     protected StatementSupport(final StatementDefinition publicDefinition, final StatementPolicy<A, D> policy) {
223         this.publicDefinition = requireNonNull(publicDefinition);
224         this.policy = requireNonNull(policy);
225         copyPolicy = policy.copyPolicy;
226     }
227
228     /**
229      * Returns public statement definition, which will be present in built statements.
230      *
231      * <p>
232      * Public statement definition may be used to provide different implementation of statement definition,
233      * which will not retain any build specific data or context.
234      *
235      * @return public statement definition, which will be present in built statements.
236      */
237     public final @NonNull StatementDefinition getPublicView() {
238         return publicDefinition;
239     }
240
241     // Appropriate to most definitions
242     // Non-final for compatible extensions
243     public @NonNull StatementDefinition definition() {
244         return publicDefinition;
245     }
246
247     /**
248      * Return this statement's {@link CopyPolicy}. This is a static value, reflecting how this statement reacts to being
249      * replicated to a different context, without reflecting on behaviour of potential substatements, which would come
250      * into play in something like:
251      *
252      * <pre>
253      *   <code>
254      *     module foo {
255      *       namespace foo;
256      *       prefix foo;
257      *
258      *       extension note {
259      *         argument string {
260      *           type string {
261      *             length 1..max;
262      *           }
263      *         }
264      *         description "Can be used in description/reference statements to attach additional notes";
265      *       }
266      *
267      *       description "A nice module extending description statement semantics" {
268      *         foo:note "We can now attach description/reference a note.";
269      *         foo:note "Also another note";
270      *       }
271      *     }
272      *   </code>
273      * </pre>
274      *
275      * <p>
276      * In this scenario, it is the reactor's job to figure out what to do (like talking to substatements).
277      *
278      * @return This statement's copy policy
279      */
280     public final @NonNull CopyPolicy copyPolicy() {
281         return copyPolicy;
282     }
283
284     @Override
285     public final boolean canReuseCurrent(final Current<A, D> copy, final Current<A, D> current,
286             final List<? extends EffectiveStatement<?, ?>> substatements) {
287         return policy.canReuseCurrent(copy, current, substatements);
288     }
289
290     @Override
291     public EffectiveStatementState extractEffectiveState(final E stmt) {
292         // Not implemented for most statements
293         return null;
294     }
295
296     /**
297      * Parses textual representation of argument in object representation.
298      *
299      * @param ctx Context, which may be used to access source-specific namespaces required for parsing.
300      * @param value String representation of value, as was present in text source.
301      * @return Parsed value
302      * @throws SourceException when an inconsistency is detected.
303      */
304     public abstract A parseArgumentValue(StmtContext<?, ?, ?> ctx, String value);
305
306     /**
307      * Adapts the argument value to match a new module. Default implementation returns original value stored in context,
308      * which is appropriate for most implementations.
309      *
310      * @param ctx Context, which may be used to access source-specific namespaces required for parsing.
311      * @param targetModule Target module, may not be null.
312      * @return Adapted argument value.
313      */
314     public A adaptArgumentValue(final @NonNull StmtContext<A, D, E> ctx, final @NonNull QNameModule targetModule) {
315         return ctx.argument();
316     }
317
318     /**
319      * Invoked when a statement supported by this instance is added to build context. This allows implementations
320      * of this interface to start tracking the statement and perform any modifications to the build context hierarchy,
321      * accessible via {@link StmtContext#getParentContext()}. One such use is populating the parent's namespaces to
322      * allow it to locate this child statement.
323      *
324      * @param stmt Context of added statement. No substatements are available.
325      */
326     public void onStatementAdded(final @NonNull Mutable<A, D, E> stmt) {
327         // NOOP for most implementations
328     }
329
330     /**
331      * Invoked when statement is closed during {@link ModelProcessingPhase#SOURCE_PRE_LINKAGE} phase, only substatements
332      * from this and previous phase are available.
333      *
334      * <p>
335      * Implementation may use method to perform actions on this event or register modification action using
336      * {@link Mutable#newInferenceAction(ModelProcessingPhase)}.
337      *
338      * @param stmt Context of added statement.
339      */
340     public void onPreLinkageDeclared(final @NonNull Mutable<A, D, E> stmt) {
341         // NOOP for most implementations
342     }
343
344     /**
345      * Invoked when statement is closed during {@link ModelProcessingPhase#SOURCE_LINKAGE} phase, only substatements
346      * from this and previous phase are available.
347      *
348      * <p>
349      * Implementation may use method to perform actions on this event or register modification action using
350      * {@link Mutable#newInferenceAction(ModelProcessingPhase)}.
351      *
352      * @param stmt Context of added statement.
353      * @throws SourceException when an inconsistency is detected.
354      */
355     public void onLinkageDeclared(final @NonNull Mutable<A, D, E> stmt) {
356         // NOOP for most implementations
357     }
358
359     /**
360      * Invoked when statement is closed during {@link ModelProcessingPhase#STATEMENT_DEFINITION} phase,
361      * only substatements from this phase are available.
362      *
363      * <p>
364      * Implementation may use method to perform actions on this event or register modification action using
365      * {@link Mutable#newInferenceAction(ModelProcessingPhase)}.
366      *
367      * @param stmt Context of added statement. Argument and statement parent is accessible.
368      * @throws SourceException when an inconsistency is detected.
369      */
370     public void onStatementDefinitionDeclared(final Mutable<A, D, E> stmt) {
371         // NOOP for most implementations
372     }
373
374     /**
375      * Invoked when statement is closed during {@link ModelProcessingPhase#FULL_DECLARATION} phase,
376      * only substatements from this phase are available.
377      *
378      * <p>
379      * Implementation may use method to perform actions on this event or register modification action using
380      * {@link Mutable#newInferenceAction(ModelProcessingPhase)}.
381      *
382      * @param stmt Context of added statement. Argument and statement parent is accessible.
383      * @throws SourceException when an inconsistency is detected.
384      */
385     public void onFullDefinitionDeclared(final Mutable<A, D, E> stmt) {
386         final SubstatementValidator validator = substatementValidator();
387         if (validator != null) {
388             validator.validate(stmt);
389         }
390     }
391
392     /**
393      * Returns corresponding substatement validator of a statement support.
394      *
395      * @return substatement validator or null, if substatement validator is not defined
396      */
397     protected abstract @Nullable SubstatementValidator substatementValidator();
398
399     /**
400      * Returns true if this support has argument specific supports.
401      *
402      * @return true if this support has argument specific supports.
403      */
404     public boolean hasArgumentSpecificSupports() {
405         // Most of statement supports don't have any argument specific supports, so return 'false'.
406         return false;
407     }
408
409     /**
410      * If this support has argument specific supports, the method returns support specific for given argument
411      * (e.g. type statement support need to be specialized based on its argument), otherwise returns null.
412      *
413      * @param argument argument of statement
414      * @return statement support specific for supplied argument or null
415      */
416     public @Nullable StatementSupport<?, ?, ?> getSupportSpecificForArgument(final String argument) {
417         // Most of statement supports don't have any argument specific supports, so return null.
418         return null;
419     }
420
421     /**
422      * Given a raw string representation of an argument, try to use a shared representation. Default implementation
423      * does nothing.
424      *
425      * @param rawArgument Argument string
426      * @return A potentially-shard instance
427      */
428     public String internArgument(final String rawArgument) {
429         return rawArgument;
430     }
431
432     /**
433      * Returns true if this statement support and all its substatements ignore if-feature statements (e.g. yang-data
434      * extension defined in <a href="https://tools.ietf.org/html/rfc8040#section-8">RFC 8040</a>). Default
435      * implementation returns false.
436      *
437      * @return true if this statement support ignores if-feature statements, otherwise false.
438      */
439     @Beta
440     public boolean isIgnoringIfFeatures() {
441         return false;
442     }
443
444     /**
445      * Returns true if this statement support and all its substatements ignore config statements (e.g. yang-data
446      * extension defined in <a href="https://tools.ietf.org/html/rfc8040#section-8">RFC 8040</a>). Default
447      * implementation returns false.
448      *
449      * @return true if this statement support ignores config statements,
450      *         otherwise false.
451      */
452     @Beta
453     public boolean isIgnoringConfig() {
454         return false;
455     }
456
457     public final @NonNull QName statementName() {
458         return publicDefinition.getStatementName();
459     }
460
461     public final @Nullable QName argumentName() {
462         return publicDefinition.getArgumentDefinition().map(ArgumentDefinition::argumentName).orElse(null);
463     }
464
465     public final @NonNull Optional<ArgumentDefinition> getArgumentDefinition() {
466         return publicDefinition.getArgumentDefinition();
467     }
468
469     /**
470      * Statement context copy policy, indicating how should reactor handle statement copy operations. Every statement
471      * copied by the reactor is subject to this policy.
472      */
473     public enum CopyPolicy {
474         /**
475          * Reuse the source statement context in the new place, as it cannot be affected by any further operations. This
476          * implies that the semantics of the effective statement are not affected by any of its substatements. Each
477          * of the substatements is free to make its own policy.
478          *
479          * <p>
480          * This policy is typically used by static constant statements such as {@code description} or {@code length},
481          * where the baseline RFC7950 does not allow any impact. A {@code description} could hold an extension statement
482          * in which case this interaction would come into play. Normal YANG will see empty substatements, so the reactor
483          * will be free to complete reuse the context.
484          *
485          * <p>
486          * In case any substatement is of stronger policy, it is up to the reactor to handle correct handling of
487          * resulting subobjects.
488          */
489         // TODO: does this mean source must have transitioned to ModelProcessingPhase.EFFECTIVE_MODEL?
490         CONTEXT_INDEPENDENT,
491         /**
492          * Reuse the source statement context in the new place completely. This policy is more stringent than
493          * {@link #CONTEXT_INDEPENDENT} in that the statement is dependent on circumstances of its original definition
494          * and any copy operation must replicate it exactly as is. This implies ignoring the usual policy of its
495          * substatements. A typical example of such a statement is {@code type}.
496          */
497         EXACT_REPLICA,
498         /**
499          * Create a copy sharing declared instance, but otherwise having a separate disconnected lifecycle.
500          */
501         // TODO: will the copy transition to ModelProcessingPhase.FULL_DECLARATION or which phase?
502         DECLARED_COPY,
503         /**
504          * Reject any attempt to copy this statement. This is useful for statements that are defined as top-level
505          * constructs, such as {@code contact}, {@code deviation} and similar.
506          */
507         REJECT,
508         /**
509          * Ignore this statement's existence for the purposes of the new place -- it is not impacted. This guidance
510          * is left here for completeness, as it can have justifiable uses (but I can't think of any). Any substatements
511          * need to be ignored, too.
512          */
513         IGNORE;
514     }
515 }