Add InferredStatementContext
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / InferredStatementContext.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.stmt.reactor;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableSet;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Optional;
18 import java.util.stream.Stream;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.QNameModule;
21 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
22 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
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.CopyHistory;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
31 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
37  * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
38  * effective substatements, which are either transformed from that prototype or added by inference.
39  */
40 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
41         extends StatementContextBase<A, D, E> {
42     private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
43
44     private final @NonNull StatementContextBase<A, D, E> prototype;
45     private final @NonNull StatementContextBase<?, ?, ?> parent;
46     private final @NonNull CopyType childCopyType;
47     private final QNameModule targetModule;
48     private final A argument;
49
50     private InferredStatementContext(final InferredStatementContext<A, D, E> original,
51             final StatementContextBase<?, ?, ?> parent) {
52         super(original);
53         this.parent = requireNonNull(parent);
54         this.childCopyType = original.childCopyType;
55         this.targetModule = original.targetModule;
56         this.prototype = original.prototype;
57         this.argument = original.argument;
58     }
59
60     InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
61             final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
62         super(prototype.definition(), CopyHistory.of(myCopyType, prototype.getCopyHistory()));
63         this.parent = requireNonNull(parent);
64         this.prototype = requireNonNull(prototype);
65         this.argument = targetModule == null ? prototype.getStatementArgument()
66                 : prototype.definition().adaptArgumentValue(prototype, targetModule);
67         this.childCopyType = requireNonNull(childCopyType);
68         this.targetModule = targetModule;
69
70         // FIXME: YANGTOOLS-784: instantiate these lazily
71         addEffectiveSubstatements(createEffective());
72     }
73
74     @Override
75     public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
76         return ImmutableList.of();
77     }
78
79     @Override
80     public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
81         // No need to concat with declared
82         return effectiveSubstatements();
83     }
84
85     @Override
86     public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
87         // No need to concat with declared
88         return effectiveSubstatements().stream();
89     }
90
91     @Override
92     public StatementSourceReference getStatementSourceReference() {
93         return prototype.getStatementSourceReference();
94     }
95
96     @Override
97     public String rawStatementArgument() {
98         return prototype.rawStatementArgument();
99     }
100
101     @Override
102     public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
103         final Optional<StmtContext<?, ?, ?>> orig = prototype.getOriginalCtx();
104         return orig.isPresent() ? orig : Optional.of(prototype);
105     }
106
107     @Override
108     public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
109         return Optional.of(prototype);
110     }
111
112     @Override
113     InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
114         return new InferredStatementContext<>(this, newParent);
115     }
116
117     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
118     // BuildGlobalContext, hence it must be called at most once.
119     private List<Mutable<?, ?, ?>> createEffective() {
120         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
121         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
122         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
123
124         for (final Mutable<?, ?, ?> stmtContext : declared) {
125             if (stmtContext.isSupportedByFeatures()) {
126                 copySubstatement(stmtContext, buffer);
127             }
128         }
129         for (final Mutable<?, ?, ?> stmtContext : effective) {
130             copySubstatement(stmtContext, buffer);
131         }
132
133         return buffer;
134     }
135
136     // Statement copy mess starts here
137     //
138     // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
139     //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
140     //        StatementSupport.
141     // FIXME: YANGTOOLS-652: these maps look very much like those in UsesStatementImpl
142     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
143         YangStmtMapping.TYPE,
144         YangStmtMapping.TYPEDEF,
145         YangStmtMapping.USES);
146     private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
147         YangStmtMapping.DESCRIPTION,
148         YangStmtMapping.REFERENCE,
149         YangStmtMapping.STATUS);
150
151     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer) {
152         final StatementDefinition def = substatement.getPublicDefinition();
153
154         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
155         if (REUSED_DEF_SET.contains(def)) {
156             LOG.debug("Reusing substatement {} for {}", substatement, this);
157             buffer.add(substatement);
158             return;
159         }
160         // FIXME: YANGTOOLS-652: formerly known as "needToCopyByUses" (note inverted check, though)
161         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
162             // This is to say: if parent of source context is a grouping, ignore this statement.
163             if (YangStmtMapping.GROUPING.equals(substatement.coerceParentContext().getPublicDefinition())) {
164                 LOG.debug("Skipping grouping statement {}", substatement);
165                 return;
166             }
167         }
168
169         // FIXME: YANGTOOLS-694: we are forcing a copy here, hence even statements not affected by parent, copyType
170         //                       or targetModule (and don't forget its substatements!). This really should be a callout
171         //                       to StatementSupport. Note if that callout is allowed to return an Optional, it can
172         //                       take care at least of the 'grouping from uses' case above.
173         final Mutable<?, ?, ?> copy = childCopyOf(substatement, childCopyType, targetModule);
174         LOG.debug("Copying substatement {} for {} as {}", substatement, this, copy);
175         buffer.add(copy);
176     }
177
178     // Statement copy mess ends here
179
180     /*
181      * KEEP THINGS ORGANIZED!
182      *
183      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
184      * properly updated there.
185      */
186     @Override
187     public Optional<SchemaPath> getSchemaPath() {
188         return substatementGetSchemaPath();
189     }
190
191     @Override
192     public A getStatementArgument() {
193         return argument;
194     }
195
196     @Override
197     public StatementContextBase<?, ?, ?> getParentContext() {
198         return parent;
199     }
200
201     @Override
202     public StorageNodeType getStorageNodeType() {
203         return StorageNodeType.STATEMENT_LOCAL;
204     }
205
206     @Override
207     public NamespaceStorageNode getParentNamespaceStorage() {
208         return parent;
209     }
210
211     @Override
212     public RootStatementContext<?, ?, ?> getRoot() {
213         return parent.getRoot();
214     }
215
216     @Override
217     public boolean isConfiguration() {
218         return isConfiguration(parent);
219     }
220
221     @Override
222     protected boolean isIgnoringIfFeatures() {
223         return isIgnoringIfFeatures(parent);
224     }
225
226     @Override
227     protected boolean isIgnoringConfig() {
228         return isIgnoringConfig(parent);
229     }
230
231     @Override
232     protected boolean isParentSupportedByFeatures() {
233         return parent.isSupportedByFeatures();
234     }
235 }