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