Populate parser/ hierarchy
[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 StmtContext<A, D, ?> ctx) {
56         final D stmt = createDeclared(ctx, ctx.declaredSubstatements().stream()
57             .map(StmtContext::declared)
58             .collect(ImmutableList.toImmutableList()));
59         return retainDeclarationReference ? attachDeclarationReference(stmt, ctx) : stmt;
60     }
61
62     protected abstract @NonNull D createDeclared(@NonNull StmtContext<A, D, ?> ctx,
63             @NonNull ImmutableList<? extends DeclaredStatement<?>> substatements);
64
65     private @NonNull D attachDeclarationReference(final @NonNull D stmt, final @NonNull StmtContext<A, D, ?> ctx) {
66         final DeclarationReference ref = ctx.sourceReference().declarationReference();
67         return ref == null ? stmt : attachDeclarationReference(stmt, ref);
68     }
69
70     /**
71      * Attach specified {@link DeclarationReference} to a baseline declared statement. If an implementation does not
72      * support attaching DeclarationReferences, it should return the statement unchanged.
73      *
74      * @param stmt Declared statement
75      * @param reference {@link DeclarationReference} to attach
76      * @return Equivalent of stmt, potentially with specified reference attached.
77      */
78     protected abstract @NonNull D attachDeclarationReference(@NonNull D stmt, @NonNull DeclarationReference reference);
79
80     @Override
81     public final E createEffective(final Current<A, D> stmt,
82             final Stream<? extends StmtContext<?, ?, ?>> declaredSubstatements,
83             final Stream<? extends StmtContext<?, ?, ?>> inferredSubstatements) {
84         final ImmutableList<? extends EffectiveStatement<?, ?>> substatements =
85                 buildEffectiveSubstatements(stmt, statementsToBuild(stmt,
86                     declaredSubstatements(declaredSubstatements, inferredSubstatements)));
87         return createEffective(stmt, substatements);
88     }
89
90     protected abstract @NonNull E createEffective(@NonNull Current<A, D> stmt,
91             @NonNull ImmutableList<? extends EffectiveStatement<?, ?>> substatements);
92
93     @Override
94     public E copyEffective(final Current<A, D> stmt, final E original) {
95         // Most implementations are only interested in substatements. copyOf() here should be a no-op
96         return createEffective(stmt, ImmutableList.copyOf(original.effectiveSubstatements()));
97     }
98
99     /**
100      * Give statement support a hook to transform statement contexts before they are built. Default implementation
101      * does nothing, but note {@code augment} statement performs a real transformation.
102      *
103      * @param ctx Effective capture of this statement's significant state
104      * @param substatements Substatement contexts which have been determined to be built
105      * @return Substatement context which are to be actually built
106      */
107     protected List<? extends StmtContext<?, ?, ?>> statementsToBuild(final Current<A, D> ctx,
108             final List<? extends StmtContext<?, ?, ?>> substatements) {
109         return substatements;
110     }
111
112     // FIXME: add documentation
113     public static final <E extends EffectiveStatement<?, ?>> @Nullable E findFirstStatement(
114             final Collection<? extends EffectiveStatement<?, ?>> statements, final Class<E> type) {
115         for (EffectiveStatement<?, ?> stmt : statements) {
116             if (type.isInstance(stmt)) {
117                 return type.cast(stmt);
118             }
119         }
120         return null;
121     }
122
123     // FIXME: add documentation
124     public static final <A, E extends EffectiveStatement<A, ?>> A findFirstArgument(
125             final Collection<? extends EffectiveStatement<?, ?>> statements, final Class<@NonNull E> type,
126                     final A defValue) {
127         final @Nullable E stmt = findFirstStatement(statements, type);
128         return stmt != null ? stmt.argument() : defValue;
129     }
130
131     /**
132      * Create a set of substatements. This method is split out so it can be overridden in subclasses adjust the
133      * resulting statements.
134      *
135      * @param stmt Current statement context
136      * @param substatements proposed substatements
137      * @return Built effective substatements
138      */
139     protected @NonNull ImmutableList<? extends EffectiveStatement<?, ?>> buildEffectiveSubstatements(
140             final Current<A, D> stmt, final List<? extends StmtContext<?, ?, ?>> substatements) {
141         return substatements.stream().map(StmtContext::buildEffective).collect(ImmutableList.toImmutableList());
142     }
143
144     private static @NonNull List<StmtContext<?, ?, ?>> declaredSubstatements(
145             final Stream<? extends StmtContext<?, ?, ?>> declaredSubstatements,
146             final Stream<? extends StmtContext<?, ?, ?>> effectiveSubstatements) {
147         /*
148          * This dance is required to ensure that effects of 'uses' nodes are applied in the same order as
149          * the statements were defined -- i.e. if we have something like this:
150          *
151          * container foo {
152          *   uses bar;
153          *   uses baz;
154          * }
155          *
156          * grouping baz {
157          *   leaf baz {
158          *     type string;
159          *   }
160          * }
161          *
162          * grouping bar {
163          *   leaf bar {
164          *     type string;
165          *   }
166          * }
167          *
168          * The reactor would first inline 'uses baz' as that definition is the first one completely resolved and then
169          * inline 'uses bar'. Here we are iterating in declaration order re-inline the statements.
170          *
171          * FIXME: 7.0.0: this really should be handled by UsesStatementSupport such that 'uses baz' would have a
172          *               prerequisite of a resolved 'uses bar'.
173          */
174         final List<StmtContext<?, ?, ?>> declaredInit = declaredSubstatements
175             .filter(StmtContext::isSupportedByFeatures)
176             .collect(Collectors.toList());
177
178         final List<StmtContext<?, ?, ?>> substatementsInit = new ArrayList<>();
179         Set<StmtContext<?, ?, ?>> filteredStatements = null;
180         for (final StmtContext<?, ?, ?> declaredSubstatement : declaredInit) {
181             substatementsInit.add(declaredSubstatement);
182
183             // FIXME: YANGTOOLS-1161: we need to integrate this functionality into the reactor, so that this
184             //                        transformation is something reactor's declared statements already take into
185             //                        account.
186             final Collection<? extends StmtContext<?, ?, ?>> effect = declaredSubstatement.getEffectOfStatement();
187             if (!effect.isEmpty()) {
188                 if (filteredStatements == null) {
189                     filteredStatements = new HashSet<>();
190                 }
191                 filteredStatements.addAll(effect);
192                 // Note: we need to filter here to exclude unsupported statements
193                 effect.stream().filter(StmtContext::isSupportedToBuildEffective).forEach(substatementsInit::add);
194             }
195         }
196
197         final Stream<? extends StmtContext<?, ?, ?>> effective;
198         if (filteredStatements != null) {
199             final Set<StmtContext<?, ?, ?>> filtered = filteredStatements;
200             effective = effectiveSubstatements.filter(stmt -> !filtered.contains(stmt));
201         } else {
202             effective = effectiveSubstatements;
203         }
204
205         substatementsInit.addAll(effective.collect(Collectors.toList()));
206         return substatementsInit;
207     }
208 }