Trim down ReplicaStatementContext
[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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.VerifyException;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableSet;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Optional;
22 import java.util.stream.Stream;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
28 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
33 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextDefaults;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
42 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
48  * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
49  * effective substatements, which are either transformed from that prototype or added by inference.
50  */
51 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52         extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
53     private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
54
55     // Sentinel object for 'substatements'
56     private static final Object SWEPT_SUBSTATEMENTS = new Object();
57
58     private final @NonNull StatementContextBase<A, D, E> prototype;
59     private final @NonNull StatementContextBase<?, ?, ?> parent;
60     private final @NonNull StmtContext<A, D, E> originalCtx;
61     private final @NonNull CopyType childCopyType;
62     private final QNameModule targetModule;
63     private final A argument;
64
65     /**
66      * Effective substatements, lazily materialized. This field can have four states:
67      * <ul>
68      *   <li>it can be {@code null}, in which case no materialization has taken place</li>
69      *   <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
70      *   <li>it can be a {@link List}, in which case full materialization has taken place</li>
71      *   <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li>
72      * </ul>
73      */
74     private Object substatements;
75
76     private InferredStatementContext(final InferredStatementContext<A, D, E> original,
77             final StatementContextBase<?, ?, ?> parent) {
78         super(original);
79         this.parent = requireNonNull(parent);
80         this.childCopyType = original.childCopyType;
81         this.targetModule = original.targetModule;
82         this.prototype = original.prototype;
83         this.originalCtx = original.originalCtx;
84         this.argument = original.argument;
85         // Substatements are initialized here
86         this.substatements = ImmutableList.of();
87     }
88
89     InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
90             final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
91         super(prototype.definition(), CopyHistory.of(myCopyType, prototype.history()));
92         this.parent = requireNonNull(parent);
93         this.prototype = requireNonNull(prototype);
94         this.argument = targetModule == null ? prototype.argument()
95                 : prototype.definition().adaptArgumentValue(prototype, targetModule);
96         this.childCopyType = requireNonNull(childCopyType);
97         this.targetModule = targetModule;
98         this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
99
100         // Mark prototype as blocking statement cleanup
101         prototype.incRef();
102     }
103
104     @Override
105     public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
106         return ImmutableList.of();
107     }
108
109     @Override
110     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
111         return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
112     }
113
114     @Override
115     public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
116         // No need to concat with declared
117         return effectiveSubstatements();
118     }
119
120     @Override
121     public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
122         // No need to concat with declared
123         return effectiveSubstatements().stream();
124     }
125
126     @Override
127     public StatementSourceReference sourceReference() {
128         return originalCtx.sourceReference();
129     }
130
131     @Override
132     public String rawArgument() {
133         return originalCtx.rawArgument();
134     }
135
136     @Override
137     public Optional<StmtContext<A, D, E>> getOriginalCtx() {
138         return Optional.of(originalCtx);
139     }
140
141     @Override
142     public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
143         return Optional.of(prototype);
144     }
145
146     @Override
147     public D declared() {
148         /*
149          * Share original instance of declared statement between all effective statements which have been copied or
150          * derived from this original declared statement.
151          */
152         return originalCtx.declared();
153     }
154
155     @Override
156     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
157         substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
158     }
159
160     @Override
161     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
162             final String statementArg) {
163         substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
164             statementArg);
165     }
166
167     @Override
168     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
169         substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
170     }
171
172     @Override
173     void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
174         substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
175     }
176
177     @Override
178     InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
179         return new InferredStatementContext<>(this, newParent);
180     }
181
182     @Override
183     boolean hasEmptySubstatements() {
184         if (substatements == null) {
185             return prototype.hasEmptySubstatements();
186         }
187         return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
188     }
189
190     @Override
191     public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
192             final @NonNull Class<Z> type) {
193         if (substatements instanceof List) {
194             return StmtContextDefaults.findSubstatementArgument(this, type);
195         }
196
197         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
198         if (templateArg.isEmpty()) {
199             return templateArg;
200         }
201         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
202             // X is known to be QName
203             return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
204         }
205         return templateArg;
206     }
207
208     @Override
209     public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
210         return substatements instanceof List ? StmtContextDefaults.hasSubstatement(prototype, type)
211             // We do not allow deletion of partially-materialized statements, hence this is accurate
212             : prototype.hasSubstatement(type);
213     }
214
215     @Override
216     public <Y extends DeclaredStatement<QName>, Z extends EffectiveStatement<QName, Y>>
217             StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
218         if (substatements instanceof List) {
219             // We have performed materialization, hence we have triggered creation of all our schema tree child
220             // statements.
221             return null;
222         }
223
224         final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
225         LOG.debug("Materializing child {} from {}", qname, templateQName);
226
227         final StmtContext<?, ?, ?> template;
228         if (prototype instanceof InferredStatementContext) {
229             // Note: we need to access namespace here, as the target statement may have already been populated, in which
230             //       case we want to obtain the statement in local namespace storage.
231             template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
232                 SchemaTreeNamespace.class, templateQName);
233         } else {
234             template = prototype.allSubstatementsStream()
235                 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
236                     && templateQName.equals(stmt.argument()))
237                 .findAny()
238                 .orElse(null);
239         }
240
241         if (template == null) {
242             // We do not have a template, this child does not exist. It may be added later, but that is someone else's
243             // responsibility.
244             LOG.debug("Child {} does not have a template", qname);
245             return null;
246         }
247
248         @SuppressWarnings("unchecked")
249         final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
250             .orElseThrow(() -> new InferenceException(sourceReference(),
251                 "Failed to materialize child %s template %s", qname, template));
252         ensureCompletedPhase(ret);
253         addMaterialized(template, ret);
254
255         LOG.debug("Child {} materialized", qname);
256         return ret;
257     }
258
259     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
260     // BuildGlobalContext, hence it must be called at most once.
261     private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
262         accessSubstatements();
263         return substatements instanceof List ? castEffective(substatements)
264             : initializeSubstatements(castMaterialized(substatements));
265     }
266
267     @Override
268     Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
269         // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
270         // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
271         if (substatements == null) {
272             return ImmutableList.of();
273         }
274         accessSubstatements();
275         if (substatements instanceof HashMap) {
276             return castMaterialized(substatements).values();
277         } else {
278             return castEffective(substatements);
279         }
280     }
281
282     @Override
283     Stream<? extends StmtContext<?, ?, ?>> streamDeclared() {
284         return Stream.empty();
285     }
286
287     @Override
288     Stream<? extends StmtContext<?, ?, ?>> streamEffective() {
289         accessSubstatements();
290         return ensureEffectiveSubstatements().stream();
291     }
292
293     private void accessSubstatements() {
294         verify(substatements != SWEPT_SUBSTATEMENTS, "Attempted to access substatements of %s", this);
295     }
296
297     @Override
298     int sweepSubstatements() {
299         final Object local = substatements;
300         substatements = SWEPT_SUBSTATEMENTS;
301         int count = 0;
302         if (local != null) {
303             final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
304             sweep(list);
305             count = countUnswept(list);
306         }
307         return count;
308     }
309
310     private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
311             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
312         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
313         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
314
315         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
316         for (final Mutable<?, ?, ?> stmtContext : declared) {
317             if (stmtContext.isSupportedByFeatures()) {
318                 copySubstatement(stmtContext, buffer, materializedSchemaTree);
319             }
320         }
321         for (final Mutable<?, ?, ?> stmtContext : effective) {
322             copySubstatement(stmtContext, buffer, materializedSchemaTree);
323         }
324
325         final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
326         ret.addAll((Collection) buffer);
327         substatements = ret;
328
329         prototype.decRef();
330         return ret;
331     }
332
333     // Statement copy mess starts here
334     //
335     // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
336     //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
337     //        StatementSupport.
338     // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
339     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
340         YangStmtMapping.TYPE,
341         YangStmtMapping.TYPEDEF,
342         YangStmtMapping.USES);
343
344     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
345             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
346         final StatementDefinition def = substatement.publicDefinition();
347
348         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
349         if (REUSED_DEF_SET.contains(def)) {
350             LOG.trace("Reusing substatement {} for {}", substatement, this);
351             buffer.add(substatement.replicaAsChildOf(this));
352             return;
353         }
354
355         // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
356         // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
357         //
358         // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
359         // against parent would change -- and we certainly do not want that to happen.
360         final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
361         if (materialized == null) {
362             copySubstatement(substatement).ifPresent(copy -> {
363                 ensureCompletedPhase(copy);
364                 buffer.add(copy);
365             });
366         } else {
367             buffer.add(materialized);
368         }
369     }
370
371     private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
372         return substatement.copyAsChildOf(this, childCopyType, targetModule);
373     }
374
375     private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
376         final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
377         if (substatements == null) {
378             // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
379             // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
380             // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
381             // resizing operation.
382             materializedSchemaTree = new HashMap<>(4);
383             substatements = materializedSchemaTree;
384         } else {
385             verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
386             materializedSchemaTree = castMaterialized(substatements);
387         }
388
389         final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
390             (StatementContextBase<?, ?, ?>) copy);
391         if (existing != null) {
392             throw new VerifyException(
393                 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
394         }
395     }
396
397     private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
398             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
399             final StmtContext<?, ?, ?> template) {
400         return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
401     }
402
403     @SuppressWarnings("unchecked")
404     private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
405         return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
406     }
407
408     @SuppressWarnings("unchecked")
409     private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
410         return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
411     }
412
413     // Statement copy mess ends here
414
415     /*
416      * KEEP THINGS ORGANIZED!
417      *
418      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
419      * properly updated there.
420      */
421     @Override
422     @Deprecated
423     public Optional<SchemaPath> schemaPath() {
424         return substatementGetSchemaPath();
425     }
426
427     @Override
428     public A argument() {
429         return argument;
430     }
431
432     @Override
433     public StatementContextBase<?, ?, ?> getParentContext() {
434         return parent;
435     }
436
437     @Override
438     public StorageNodeType getStorageNodeType() {
439         return StorageNodeType.STATEMENT_LOCAL;
440     }
441
442     @Override
443     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
444         return parent;
445     }
446
447     @Override
448     public RootStatementContext<?, ?, ?> getRoot() {
449         return parent.getRoot();
450     }
451
452     @Override
453     public boolean effectiveConfig() {
454         return isConfiguration(parent);
455     }
456
457     @Override
458     protected boolean isIgnoringIfFeatures() {
459         return isIgnoringIfFeatures(parent);
460     }
461
462     @Override
463     protected boolean isIgnoringConfig() {
464         return isIgnoringConfig(parent);
465     }
466
467     @Override
468     protected boolean isParentSupportedByFeatures() {
469         return parent.isSupportedByFeatures();
470     }
471 }