2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
10 import static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
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;
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;
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.
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);
54 // Sentinel object for 'substatements'
55 private static final Object SWEPT_SUBSTATEMENTS = new Object();
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;
65 * Effective substatements, lazily materialized. This field can have four states:
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>
73 private Object substatements;
75 private InferredStatementContext(final InferredStatementContext<A, D, E> original,
76 final StatementContextBase<?, ?, ?> parent) {
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();
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);
99 // Mark prototype as blocking statement cleanup
104 public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
105 return ImmutableList.of();
109 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
110 return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
114 public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
115 // No need to concat with declared
116 return effectiveSubstatements();
120 public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
121 // No need to concat with declared
122 return effectiveSubstatements().stream();
126 public StatementSourceReference sourceReference() {
127 return originalCtx.sourceReference();
131 public String rawArgument() {
132 return originalCtx.rawArgument();
136 public Optional<StmtContext<A, D, E>> getOriginalCtx() {
137 return Optional.of(originalCtx);
141 public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
142 return Optional.of(prototype);
146 public D declared() {
148 * Share original instance of declared statement between all effective statements which have been copied or
149 * derived from this original declared statement.
151 return originalCtx.declared();
155 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
156 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
160 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
161 final String statementArg) {
162 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
167 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
168 substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
172 void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
173 substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
177 InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
178 return new InferredStatementContext<>(this, newParent);
182 boolean hasEmptySubstatements() {
183 if (substatements == null) {
184 return prototype.hasEmptySubstatements();
186 return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
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);
196 final Optional<X> templateArg = prototype.findSubstatementArgument(type);
197 if (templateArg.isEmpty()) {
200 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
201 // X is known to be QName
202 return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
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);
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
223 final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
224 LOG.debug("Materializing child {} from {}", qname, templateQName);
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);
233 template = prototype.allSubstatementsStream()
234 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
235 && templateQName.equals(stmt.argument()))
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
243 LOG.debug("Child {} does not have a template", qname);
247 @SuppressWarnings("unchecked")
248 final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
250 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
251 ensureCompletedPhase(ret);
252 addMaterialized(template, ret);
254 LOG.debug("Child {} materialized", qname);
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));
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();
273 accessSubstatements();
274 if (substatements instanceof HashMap) {
275 return castMaterialized(substatements).values();
277 return castEffective(substatements);
282 Stream<? extends StmtContext<?, ?, ?>> streamDeclared() {
283 return Stream.empty();
287 Stream<? extends StmtContext<?, ?, ?>> streamEffective() {
288 accessSubstatements();
289 return ensureEffectiveSubstatements().stream();
292 private void accessSubstatements() {
293 verify(substatements != SWEPT_SUBSTATEMENTS, "Attempted to access substatements of %s", this);
297 void markNoParentRef() {
298 final Object local = substatements;
300 markNoParentRef(castEffective(local));
305 int sweepSubstatements() {
306 final Object local = substatements;
307 substatements = SWEPT_SUBSTATEMENTS;
310 final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
312 count = countUnswept(list);
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();
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);
328 for (final Mutable<?, ?, ?> stmtContext : effective) {
329 copySubstatement(stmtContext, buffer, materializedSchemaTree);
332 final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
333 ret.addAll((Collection) buffer);
340 // Statement copy mess starts here
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
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);
351 private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
352 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
353 final StatementDefinition def = substatement.publicDefinition();
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));
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.
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);
374 buffer.add(materialized);
378 private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
379 // FIXME: YANGTOOLS-1195: this is not exactly what we want to do here, because we are deling with two different
380 // requests: copy for inference purposes (this method), while we also copy for purposes
381 // of buildEffective() -- in which case we want to probably invoke asEffectiveChildOf()
383 return substatement.copyAsChildOf(this, childCopyType, targetModule);
386 private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
387 final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
388 if (substatements == null) {
389 // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
390 // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
391 // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
392 // resizing operation.
393 materializedSchemaTree = new HashMap<>(4);
394 substatements = materializedSchemaTree;
396 verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
397 materializedSchemaTree = castMaterialized(substatements);
400 final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
401 (StatementContextBase<?, ?, ?>) copy);
402 if (existing != null) {
403 throw new VerifyException(
404 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
408 private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
409 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
410 final StmtContext<?, ?, ?> template) {
411 return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
414 @SuppressWarnings("unchecked")
415 private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
416 return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
419 @SuppressWarnings("unchecked")
420 private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
421 return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
424 // Statement copy mess ends here
427 * KEEP THINGS ORGANIZED!
429 * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
430 * properly updated there.
434 public Optional<SchemaPath> schemaPath() {
435 return substatementGetSchemaPath();
439 public A argument() {
444 public StatementContextBase<?, ?, ?> getParentContext() {
449 public StorageNodeType getStorageNodeType() {
450 return StorageNodeType.STATEMENT_LOCAL;
454 public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
459 public RootStatementContext<?, ?, ?> getRoot() {
460 return parent.getRoot();
464 public EffectiveConfig effectiveConfig() {
465 return effectiveConfig(parent);
469 protected boolean isIgnoringIfFeatures() {
470 return isIgnoringIfFeatures(parent);
474 protected boolean isIgnoringConfig() {
475 return isIgnoringConfig(parent);
479 protected boolean isParentSupportedByFeatures() {
480 return parent.isSupportedByFeatures();