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