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