Add a refcount mechanism for substatements
[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.getCopyHistory()));
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 buildDeclared() {
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.buildDeclared();
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<StatementContextBase<?, ?, ?>> ensureEffectiveSubstatements() {
262         accessSubstatements();
263         return substatements instanceof List ? castEffective(substatements)
264             : initializeSubstatements(castMaterialized(substatements));
265     }
266
267     @Override
268     Iterable<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> list = castEffective(local);
304             sweep(list);
305             count = countUnswept(list);
306         }
307         return count;
308     }
309
310     private List<StatementContextBase<?, ?, ?>> initializeSubstatements(
311             final Map<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(),
326             buffer.size());
327         ret.addAll((Collection) buffer);
328         substatements = ret;
329
330         prototype.decRef();
331         return ret;
332     }
333
334     // Statement copy mess starts here
335     //
336     // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
337     //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
338     //        StatementSupport.
339     // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
340     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
341         YangStmtMapping.TYPE,
342         YangStmtMapping.TYPEDEF,
343         YangStmtMapping.USES);
344
345     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
346             final Map<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree) {
347         final StatementDefinition def = substatement.publicDefinition();
348
349         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
350         if (REUSED_DEF_SET.contains(def)) {
351             LOG.trace("Reusing substatement {} for {}", substatement, this);
352             buffer.add(substatement.replicaAsChildOf(this));
353             return;
354         }
355
356         // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
357         // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
358         //
359         // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
360         // against parent would change -- and we certainly do not want that to happen.
361         final StatementContextBase<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
362         if (materialized == null) {
363             copySubstatement(substatement).ifPresent(copy -> {
364                 ensureCompletedPhase(copy);
365                 buffer.add(copy);
366             });
367         } else {
368             buffer.add(materialized);
369         }
370     }
371
372     private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
373         return substatement.copyAsChildOf(this, childCopyType, targetModule);
374     }
375
376     private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
377         final HashMap<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree;
378         if (substatements == null) {
379             // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
380             // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
381             // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
382             // resizing operation.
383             materializedSchemaTree = new HashMap<>(4);
384             substatements = materializedSchemaTree;
385         } else {
386             verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
387             materializedSchemaTree = castMaterialized(substatements);
388         }
389
390         final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
391             (StatementContextBase<?, ?, ?>) copy);
392         if (existing != null) {
393             throw new VerifyException(
394                 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
395         }
396     }
397
398     private static @Nullable StatementContextBase<?, ?, ?> findMaterialized(
399             final Map<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree,
400             final StmtContext<?, ?, ?> template) {
401         return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
402     }
403
404     @SuppressWarnings("unchecked")
405     private static List<StatementContextBase<?, ?, ?>> castEffective(final Object substatements) {
406         return (List<StatementContextBase<?, ?, ?>>) substatements;
407     }
408
409     @SuppressWarnings("unchecked")
410     private static HashMap<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> castMaterialized(
411             final Object substatements) {
412         return (HashMap<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>>) substatements;
413     }
414
415     // Statement copy mess ends here
416
417     /*
418      * KEEP THINGS ORGANIZED!
419      *
420      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
421      * properly updated there.
422      */
423     @Override
424     @Deprecated
425     Optional<SchemaPath> schemaPath() {
426         return substatementGetSchemaPath();
427     }
428
429     @Override
430     public A argument() {
431         return argument;
432     }
433
434     @Override
435     public StatementContextBase<?, ?, ?> getParentContext() {
436         return parent;
437     }
438
439     @Override
440     public StorageNodeType getStorageNodeType() {
441         return StorageNodeType.STATEMENT_LOCAL;
442     }
443
444     @Override
445     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
446         return parent;
447     }
448
449     @Override
450     public RootStatementContext<?, ?, ?> getRoot() {
451         return parent.getRoot();
452     }
453
454     @Override
455     public boolean isConfiguration() {
456         return isConfiguration(parent);
457     }
458
459     @Override
460     protected boolean isIgnoringIfFeatures() {
461         return isIgnoringIfFeatures(parent);
462     }
463
464     @Override
465     protected boolean isIgnoringConfig() {
466         return isIgnoringConfig(parent);
467     }
468
469     @Override
470     protected boolean isParentSupportedByFeatures() {
471         return parent.isSupportedByFeatures();
472     }
473 }