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.Streams;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.List;
22 import java.util.Objects;
23 import java.util.Optional;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.yangtools.concepts.Immutable;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.QNameModule;
31 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
32 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
36 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
51 * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
52 * effective substatements, which are either transformed from that prototype or added by inference.
54 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
55 extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
56 // An effective copy view, with enough information to decide what to do next
57 private static final class EffectiveCopy implements Immutable {
59 private final ReactorStmtCtx<?, ?, ?> orig;
60 // Effective view, if the statement is to be reused it equals to orig
61 private final ReactorStmtCtx<?, ?, ?> copy;
63 EffectiveCopy(final ReactorStmtCtx<?, ?, ?> orig, final ReactorStmtCtx<?, ?, ?> copy) {
64 this.orig = requireNonNull(orig);
65 this.copy = requireNonNull(copy);
72 ReactorStmtCtx<?, ?, ?> toChildContext(final @NonNull InferredStatementContext<?, ?, ?> parent) {
73 return isReused() ? orig.replicaAsChildOf(parent) : copy;
76 ReactorStmtCtx<?, ?, ?> toReusedChild(final @NonNull InferredStatementContext<?, ?, ?> parent) {
77 verify(isReused(), "Attempted to discard copy %s", copy);
78 return orig.replicaAsChildOf(parent);
82 private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
84 // Sentinel object for 'substatements'
85 private static final Object SWEPT_SUBSTATEMENTS = new Object();
87 private final @NonNull StatementContextBase<A, D, E> prototype;
88 private final @NonNull StatementContextBase<?, ?, ?> parent;
89 private final @NonNull StmtContext<A, D, E> originalCtx;
90 private final @NonNull CopyType childCopyType;
91 private final QNameModule targetModule;
92 private final A argument;
95 * Effective substatements, lazily materialized. This field can have four states:
97 * <li>it can be {@code null}, in which case no materialization has taken place</li>
98 * <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
99 * <li>it can be a {@link List}, in which case full materialization has taken place</li>
100 * <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li>
103 private Object substatements;
105 private InferredStatementContext(final InferredStatementContext<A, D, E> original,
106 final StatementContextBase<?, ?, ?> parent) {
108 this.parent = requireNonNull(parent);
109 this.childCopyType = original.childCopyType;
110 this.targetModule = original.targetModule;
111 this.prototype = original.prototype;
112 this.originalCtx = original.originalCtx;
113 this.argument = original.argument;
114 // Substatements are initialized here
115 this.substatements = ImmutableList.of();
118 InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
119 final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
120 super(prototype.definition(), CopyHistory.of(myCopyType, prototype.history()));
121 this.parent = requireNonNull(parent);
122 this.prototype = requireNonNull(prototype);
123 this.argument = targetModule == null ? prototype.argument()
124 : prototype.definition().adaptArgumentValue(prototype, targetModule);
125 this.childCopyType = requireNonNull(childCopyType);
126 this.targetModule = targetModule;
127 this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
129 // Mark prototype as blocking statement cleanup
134 public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
135 return ImmutableList.of();
139 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
140 return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
144 public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
145 // No need to concat with declared
146 return effectiveSubstatements();
150 public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
151 // No need to concat with declared
152 return effectiveSubstatements().stream();
156 public StatementSourceReference sourceReference() {
157 return originalCtx.sourceReference();
161 public String rawArgument() {
162 return originalCtx.rawArgument();
166 public Optional<StmtContext<A, D, E>> getOriginalCtx() {
167 return Optional.of(originalCtx);
171 public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
172 return Optional.of(prototype);
176 public D declared() {
178 * Share original instance of declared statement between all effective statements which have been copied or
179 * derived from this original declared statement.
181 return originalCtx.declared();
185 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
186 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
190 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
191 final String statementArg) {
192 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
197 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
198 substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
202 void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
203 substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
207 InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
208 return new InferredStatementContext<>(this, newParent);
212 E createEffective(final StatementFactory<A, D, E> factory) {
213 // If we have not materialized we do not have a difference in effective substatements, hence we can forward
214 // towards the source of the statement.
215 return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory);
218 private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
219 final E origEffective = prototype.buildEffective();
220 final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
221 origEffective.effectiveSubstatements();
223 // First check if we can reuse the entire prototype
224 if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
225 return tryToReuseSubstatements(factory, origEffective);
228 // No substatements to deal with, we can freely reuse the original
229 if (origSubstatements.isEmpty()) {
230 LOG.debug("Reusing empty: {}", origEffective);
231 substatements = ImmutableList.of();
233 return origEffective;
236 // We can reuse this statement let's see if all the statements agree
237 final List<EffectiveCopy> declCopy = prototype.streamDeclared()
238 .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
239 .filter(Objects::nonNull)
240 .collect(Collectors.toUnmodifiableList());
241 final List<EffectiveCopy> effCopy = prototype.streamEffective()
242 .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
243 .filter(Objects::nonNull)
244 .collect(Collectors.toUnmodifiableList());
246 if (allReused(declCopy) && allReused(effCopy)) {
247 LOG.debug("Reusing after substatement check: {}", origEffective);
248 // FIXME: can we skip this if !haveRef()?
249 substatements = reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
250 .map(copy -> copy.toReusedChild(this)));
252 return origEffective;
255 final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
256 .map(copy -> copy.toChildContext(this))
257 .collect(ImmutableList.toImmutableList());
258 final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
259 .map(copy -> copy.toChildContext(this))
260 .collect(ImmutableList.toImmutableList());
261 substatements = declared.isEmpty() ? effective
262 : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
265 // Values are the effective copies, hence this efficiently deals with recursion.
266 return factory.createEffective(this, declared.stream(), effective.stream());
269 private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
270 if (allSubstatementsContextIndependent()) {
271 LOG.debug("Reusing substatements of: {}", prototype);
272 // FIXME: can we skip this if !haveRef()?
273 substatements = reusePrototypeReplicas();
275 return factory.copyEffective(this, original);
278 // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
279 // the substatement list, as this operation turned out to not affect them.
280 final E effective = super.createEffective(factory);
281 if (sameSubstatements(original.effectiveSubstatements(), effective)) {
282 LOG.debug("Reusing unchanged substatements of: {}", prototype);
283 return factory.copyEffective(this, original);
288 private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
289 return reusePrototypeReplicas(Streams.concat(
290 prototype.streamDeclared(), prototype.streamEffective()));
293 private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
296 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
297 ret.buildEffective();
300 .collect(Collectors.toUnmodifiableList());
303 private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
304 final Collection<?> copied = effective.effectiveSubstatements();
305 if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
306 // Do not bother if result is treating substatements as transient
310 final Iterator<?> oit = original.iterator();
311 final Iterator<?> cit = copied.iterator();
312 while (oit.hasNext()) {
313 verify(cit.hasNext());
314 // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
316 if (oit.next() != cit.next()) {
320 verify(!cit.hasNext());
324 private static boolean allReused(final List<EffectiveCopy> entries) {
325 return entries.stream().allMatch(EffectiveCopy::isReused);
329 boolean hasEmptySubstatements() {
330 if (substatements == null) {
331 return prototype.hasEmptySubstatements();
333 return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
337 boolean noSensitiveSubstatements() {
338 accessSubstatements();
339 if (substatements == null) {
340 // No difference, defer to prototype
341 return prototype.allSubstatementsContextIndependent();
343 if (substatements instanceof List) {
344 // Fully materialized, walk all statements
345 return noSensitiveSubstatements(castEffective(substatements));
348 // Partially-materialized. This case has three distinct outcomes:
349 // - prototype does not have a sensitive statement (1)
350 // - protype has a sensitive substatement, and
351 // - we have not marked is as unsupported (2)
352 // - we have marked it as unsupported (3)
354 // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
355 // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
356 // as affecting the result.
357 return prototype.allSubstatementsContextIndependent()
358 && noSensitiveSubstatements(castMaterialized(substatements).values());
362 public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
363 final @NonNull Class<Z> type) {
364 if (substatements instanceof List) {
365 return super.findSubstatementArgument(type);
368 final Optional<X> templateArg = prototype.findSubstatementArgument(type);
369 if (templateArg.isEmpty()) {
372 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
373 // X is known to be QName
374 return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
380 public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
381 return substatements instanceof List ? super.hasSubstatement(type)
382 // We do not allow deletion of partially-materialized statements, hence this is accurate
383 : prototype.hasSubstatement(type);
387 public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
388 StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
389 if (substatements instanceof List) {
390 // We have performed materialization, hence we have triggered creation of all our schema tree child
395 final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
396 LOG.debug("Materializing child {} from {}", qname, templateQName);
398 final StmtContext<?, ?, ?> template;
399 if (prototype instanceof InferredStatementContext) {
400 // Note: we need to access namespace here, as the target statement may have already been populated, in which
401 // case we want to obtain the statement in local namespace storage.
402 template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
403 SchemaTreeNamespace.class, templateQName);
405 template = prototype.allSubstatementsStream()
406 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
407 && templateQName.equals(stmt.argument()))
412 if (template == null) {
413 // We do not have a template, this child does not exist. It may be added later, but that is someone else's
415 LOG.debug("Child {} does not have a template", qname);
419 @SuppressWarnings("unchecked")
420 final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
422 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
423 ensureCompletedPhase(ret);
424 addMaterialized(template, ret);
426 LOG.debug("Child {} materialized", qname);
430 // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
431 // BuildGlobalContext, hence it must be called at most once.
432 private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
433 accessSubstatements();
434 return substatements instanceof List ? castEffective(substatements)
435 : initializeSubstatements(castMaterialized(substatements));
439 Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
440 // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
441 // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
442 if (substatements == null) {
443 return ImmutableList.of();
445 accessSubstatements();
446 if (substatements instanceof HashMap) {
447 return castMaterialized(substatements).values();
449 return castEffective(substatements);
454 Stream<? extends StmtContext<?, ?, ?>> streamDeclared() {
455 return Stream.empty();
459 Stream<? extends StmtContext<?, ?, ?>> streamEffective() {
460 accessSubstatements();
461 return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
464 private void accessSubstatements() {
465 verify(substatements != SWEPT_SUBSTATEMENTS, "Attempted to access substatements of %s", this);
469 void markNoParentRef() {
470 final Object local = substatements;
472 markNoParentRef(castEffective(local));
477 int sweepSubstatements() {
478 final Object local = substatements;
479 substatements = SWEPT_SUBSTATEMENTS;
482 final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
484 count = countUnswept(list);
489 private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
490 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
491 final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
492 final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
494 final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
495 for (final Mutable<?, ?, ?> stmtContext : declared) {
496 if (stmtContext.isSupportedByFeatures()) {
497 copySubstatement(stmtContext, buffer, materializedSchemaTree);
500 for (final Mutable<?, ?, ?> stmtContext : effective) {
501 copySubstatement(stmtContext, buffer, materializedSchemaTree);
504 final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
505 ret.addAll((Collection) buffer);
513 // Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
514 // sometimes. Tread softly because you tread on my dreams.
517 private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
518 final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType, targetModule);
519 return effective == null ? null : new EffectiveCopy(stmt, effective);
522 private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
523 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
524 // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
525 // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
527 // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
528 // against parent would change -- and we certainly do not want that to happen.
529 final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
530 if (materialized == null) {
531 copySubstatement(substatement).ifPresent(copy -> {
532 ensureCompletedPhase(copy);
536 buffer.add(materialized);
540 private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
541 // FIXME: YANGTOOLS-1195: this is not exactly what we want to do here, because we are dealing with two different
542 // requests: copy for inference purposes (this method), while we also copy for purposes
543 // of buildEffective() -- in which case we want to probably invoke asEffectiveChildOf()
545 return substatement.copyAsChildOf(this, childCopyType, targetModule);
548 private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
549 final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
550 if (substatements == null) {
551 // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
552 // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
553 // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
554 // resizing operation.
555 materializedSchemaTree = new HashMap<>(4);
556 substatements = materializedSchemaTree;
558 verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
559 materializedSchemaTree = castMaterialized(substatements);
562 final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
563 (StatementContextBase<?, ?, ?>) copy);
564 if (existing != null) {
565 throw new VerifyException(
566 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
570 private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
571 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
572 final StmtContext<?, ?, ?> template) {
573 return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
576 @SuppressWarnings("unchecked")
577 private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
578 return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
581 @SuppressWarnings("unchecked")
582 private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
583 return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
586 // Statement copy mess ends here
589 * KEEP THINGS ORGANIZED!
591 * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
592 * properly updated there.
596 public SchemaPath schemaPath() {
597 return substatementGetSchemaPath();
601 public A argument() {
606 public StatementContextBase<?, ?, ?> getParentContext() {
611 public StorageNodeType getStorageNodeType() {
612 return StorageNodeType.STATEMENT_LOCAL;
616 public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
621 public RootStatementContext<?, ?, ?> getRoot() {
622 return parent.getRoot();
626 public EffectiveConfig effectiveConfig() {
627 return effectiveConfig(parent);
631 protected boolean isIgnoringIfFeatures() {
632 return isIgnoringIfFeatures(parent);
636 protected boolean isIgnoringConfig() {
637 return isIgnoringConfig(parent);
641 protected boolean isParentSupportedByFeatures() {
642 return parent.isSupportedByFeatures();