Remove AugmentationSchemaNode.getOriginalDefinition()
[yangtools.git] / parser / yang-parser-spi / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / AbstractStatementSupport.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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 com.google.common.annotations.Beta;
11 import com.google.common.collect.ImmutableList;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.HashSet;
15 import java.util.List;
16 import java.util.Set;
17 import java.util.stream.Collectors;
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.model.api.meta.DeclarationReference;
22 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
23 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
25 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
26 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
27
28 /**
29  * Baseline implementation class for common {@link StatementSupport} implementations. This class performs many of the
30  * its duties in the canonical way -- taking away some amount of freedom for common functionality.
31  *
32  * @param <A> Argument type
33  * @param <D> Declared Statement representation
34  * @param <E> Effective Statement representation
35  */
36 @Beta
37 public abstract class AbstractStatementSupport<A, D extends DeclaredStatement<A>,
38         E extends EffectiveStatement<A, D>> extends StatementSupport<A, D, E> {
39     private final SubstatementValidator substatementValidator;
40     private final boolean retainDeclarationReference;
41
42     protected AbstractStatementSupport(final StatementDefinition publicDefinition, final StatementPolicy<A, D> policy,
43             final YangParserConfiguration config, final @Nullable SubstatementValidator validator) {
44         super(publicDefinition, policy);
45         this.retainDeclarationReference = config.retainDeclarationReferences();
46         this.substatementValidator = validator;
47     }
48
49     @Override
50     protected final SubstatementValidator substatementValidator() {
51         return substatementValidator;
52     }
53
54     @Override
55     public final D createDeclared(final BoundStmtCtx<A> ctx, final Stream<DeclaredStatement<?>> substatements) {
56         final D stmt = createDeclared(ctx, substatements.collect(ImmutableList.toImmutableList()));
57         return retainDeclarationReference ? attachDeclarationReference(stmt, ctx) : stmt;
58     }
59
60     protected abstract @NonNull D createDeclared(@NonNull BoundStmtCtx<A> ctx,
61             @NonNull ImmutableList<DeclaredStatement<?>> substatements);
62
63     private @NonNull D attachDeclarationReference(final @NonNull D stmt, final @NonNull BoundStmtCtx<A> ctx) {
64         final DeclarationReference ref = ctx.sourceReference().declarationReference();
65         return ref == null ? stmt : attachDeclarationReference(stmt, ref);
66     }
67
68     /**
69      * Attach specified {@link DeclarationReference} to a baseline declared statement. If an implementation does not
70      * support attaching DeclarationReferences, it should return the statement unchanged.
71      *
72      * @param stmt Declared statement
73      * @param reference {@link DeclarationReference} to attach
74      * @return Equivalent of stmt, potentially with specified reference attached.
75      */
76     protected abstract @NonNull D attachDeclarationReference(@NonNull D stmt, @NonNull DeclarationReference reference);
77
78     @Override
79     public final E createEffective(final Current<A, D> stmt,
80             final Stream<? extends StmtContext<?, ?, ?>> declaredSubstatements,
81             final Stream<? extends StmtContext<?, ?, ?>> inferredSubstatements) {
82         final ImmutableList<? extends EffectiveStatement<?, ?>> substatements =
83                 buildEffectiveSubstatements(stmt, statementsToBuild(stmt,
84                     declaredSubstatements(declaredSubstatements, inferredSubstatements)));
85         return createEffective(stmt, substatements);
86     }
87
88     protected abstract @NonNull E createEffective(@NonNull Current<A, D> stmt,
89             @NonNull ImmutableList<? extends EffectiveStatement<?, ?>> substatements);
90
91     @Override
92     public E copyEffective(final Current<A, D> stmt, final E original) {
93         // Most implementations are only interested in substatements. copyOf() here should be a no-op
94         return createEffective(stmt, ImmutableList.copyOf(original.effectiveSubstatements()));
95     }
96
97     /**
98      * Give statement support a hook to transform statement contexts before they are built. Default implementation
99      * does nothing, but note {@code augment} statement performs a real transformation.
100      *
101      * @param ctx Effective capture of this statement's significant state
102      * @param substatements Substatement contexts which have been determined to be built
103      * @return Substatement context which are to be actually built
104      */
105     protected List<? extends StmtContext<?, ?, ?>> statementsToBuild(final Current<A, D> ctx,
106             final List<? extends StmtContext<?, ?, ?>> substatements) {
107         return substatements;
108     }
109
110     // FIXME: add documentation
111     public static final <E extends EffectiveStatement<?, ?>> @Nullable E findFirstStatement(
112             final Collection<? extends EffectiveStatement<?, ?>> statements, final Class<E> type) {
113         for (EffectiveStatement<?, ?> stmt : statements) {
114             if (type.isInstance(stmt)) {
115                 return type.cast(stmt);
116             }
117         }
118         return null;
119     }
120
121     // FIXME: add documentation
122     public static final <A, E extends EffectiveStatement<A, ?>> A findFirstArgument(
123             final Collection<? extends EffectiveStatement<?, ?>> statements, final Class<@NonNull E> type,
124                     final A defValue) {
125         final @Nullable E stmt = findFirstStatement(statements, type);
126         return stmt != null ? stmt.argument() : defValue;
127     }
128
129     /**
130      * Create a set of substatements. This method is split out so it can be overridden in subclasses adjust the
131      * resulting statements.
132      *
133      * @param stmt Current statement context
134      * @param substatements proposed substatements
135      * @return Built effective substatements
136      */
137     protected @NonNull ImmutableList<? extends EffectiveStatement<?, ?>> buildEffectiveSubstatements(
138             final Current<A, D> stmt, final List<? extends StmtContext<?, ?, ?>> substatements) {
139         return substatements.stream().map(StmtContext::buildEffective).collect(ImmutableList.toImmutableList());
140     }
141
142     private static @NonNull List<StmtContext<?, ?, ?>> declaredSubstatements(
143             final Stream<? extends StmtContext<?, ?, ?>> declaredSubstatements,
144             final Stream<? extends StmtContext<?, ?, ?>> effectiveSubstatements) {
145         /*
146          * This dance is required to ensure that effects of 'uses' nodes are applied in the same order as
147          * the statements were defined -- i.e. if we have something like this:
148          *
149          * container foo {
150          *   uses bar;
151          *   uses baz;
152          * }
153          *
154          * grouping baz {
155          *   leaf baz {
156          *     type string;
157          *   }
158          * }
159          *
160          * grouping bar {
161          *   leaf bar {
162          *     type string;
163          *   }
164          * }
165          *
166          * The reactor would first inline 'uses baz' as that definition is the first one completely resolved and then
167          * inline 'uses bar'. Here we are iterating in declaration order re-inline the statements.
168          *
169          * FIXME: 7.0.0: this really should be handled by UsesStatementSupport such that 'uses baz' would have a
170          *               prerequisite of a resolved 'uses bar'.
171          */
172         final List<StmtContext<?, ?, ?>> declaredInit = declaredSubstatements
173             .filter(StmtContext::isSupportedByFeatures)
174             .collect(Collectors.toList());
175
176         final List<StmtContext<?, ?, ?>> substatementsInit = new ArrayList<>();
177         Set<StmtContext<?, ?, ?>> filteredStatements = null;
178         for (final StmtContext<?, ?, ?> declaredSubstatement : declaredInit) {
179             substatementsInit.add(declaredSubstatement);
180
181             // FIXME: YANGTOOLS-1161: we need to integrate this functionality into the reactor, so that this
182             //                        transformation is something reactor's declared statements already take into
183             //                        account.
184             final Collection<? extends StmtContext<?, ?, ?>> effect = declaredSubstatement.getEffectOfStatement();
185             if (!effect.isEmpty()) {
186                 if (filteredStatements == null) {
187                     filteredStatements = new HashSet<>();
188                 }
189                 filteredStatements.addAll(effect);
190                 // Note: we need to filter here to exclude unsupported statements
191                 effect.stream().filter(StmtContext::isSupportedToBuildEffective).forEach(substatementsInit::add);
192             }
193         }
194
195         final Stream<? extends StmtContext<?, ?, ?>> effective;
196         if (filteredStatements != null) {
197             final Set<StmtContext<?, ?, ?>> filtered = filteredStatements;
198             effective = effectiveSubstatements.filter(stmt -> !filtered.contains(stmt));
199         } else {
200             effective = effectiveSubstatements;
201         }
202
203         substatementsInit.addAll(effective.collect(Collectors.toList()));
204         return substatementsInit;
205     }
206 }