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.meta.DeclaredStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
35 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
49 * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
50 * effective substatements, which are either transformed from that prototype or added by inference.
52 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
53 extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
54 // An effective copy view, with enough information to decide what to do next
55 private static final class EffectiveCopy implements Immutable {
57 private final ReactorStmtCtx<?, ?, ?> orig;
58 // Effective view, if the statement is to be reused it equals to orig
59 private final ReactorStmtCtx<?, ?, ?> copy;
61 EffectiveCopy(final ReactorStmtCtx<?, ?, ?> orig, final ReactorStmtCtx<?, ?, ?> copy) {
62 this.orig = requireNonNull(orig);
63 this.copy = requireNonNull(copy);
70 ReactorStmtCtx<?, ?, ?> toChildContext(final @NonNull InferredStatementContext<?, ?, ?> parent) {
71 return isReused() ? orig.replicaAsChildOf(parent) : copy;
74 ReactorStmtCtx<?, ?, ?> toReusedChild(final @NonNull InferredStatementContext<?, ?, ?> parent) {
75 verify(isReused(), "Attempted to discard copy %s", copy);
76 return orig.replicaAsChildOf(parent);
80 private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
82 // Sentinel objects for 'substatements', String is a good enough type
83 private static final @NonNull String REUSED_SUBSTATEMENTS = "reused";
84 private static final @NonNull String SWEPT_SUBSTATEMENTS = "swept";
86 private final @NonNull StatementContextBase<A, D, E> prototype;
87 private final @NonNull StatementContextBase<?, ?, ?> parent;
88 private final @NonNull StmtContext<A, D, E> originalCtx;
89 private final QNameModule targetModule;
90 private final A argument;
93 * Effective substatements, lazily materialized. This field can have four states:
95 * <li>it can be {@code null}, in which case no materialization has taken place</li>
96 * <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
97 * <li>it can be a {@link List}, in which case full materialization has taken place</li>
98 * <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li>
101 private Object substatements;
103 private InferredStatementContext(final InferredStatementContext<A, D, E> original,
104 final StatementContextBase<?, ?, ?> parent) {
106 this.parent = requireNonNull(parent);
107 this.targetModule = original.targetModule;
108 this.prototype = original.prototype;
109 this.originalCtx = original.originalCtx;
110 this.argument = original.argument;
111 // Substatements are initialized here
112 this.substatements = ImmutableList.of();
115 InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
116 final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
117 super(prototype, myCopyType, childCopyType);
118 this.parent = requireNonNull(parent);
119 this.prototype = requireNonNull(prototype);
120 this.argument = targetModule == null ? prototype.argument()
121 : prototype.definition().adaptArgumentValue(prototype, targetModule);
122 this.targetModule = targetModule;
123 this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
125 // Mark prototype as blocking statement cleanup
130 public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
131 return ImmutableList.of();
135 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
136 return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
140 public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
141 // No need to concat with declared
142 return effectiveSubstatements();
146 public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
147 // No need to concat with declared
148 return effectiveSubstatements().stream();
152 public StatementSourceReference sourceReference() {
153 return originalCtx.sourceReference();
157 public String rawArgument() {
158 return originalCtx.rawArgument();
162 public Optional<StmtContext<A, D, E>> getOriginalCtx() {
163 return Optional.of(originalCtx);
167 public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
168 return Optional.of(prototype);
172 public D declared() {
174 * Share original instance of declared statement between all effective statements which have been copied or
175 * derived from this original declared statement.
177 return originalCtx.declared();
181 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
182 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
186 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
187 final String statementArg) {
188 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
193 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
194 substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
198 void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
199 substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
203 InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
204 return new InferredStatementContext<>(this, newParent);
208 E createEffective(final StatementFactory<A, D, E> factory) {
209 // If we have not materialized we do not have a difference in effective substatements, hence we can forward
210 // towards the source of the statement.
211 accessSubstatements();
212 return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory);
215 private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
216 final E origEffective = prototype.buildEffective();
217 final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
218 origEffective.effectiveSubstatements();
220 // First check if we can reuse the entire prototype
221 if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
222 // FIXME: YANGTOOLS-1214: deduplicate this return
223 return tryToReuseSubstatements(factory, origEffective);
226 // We can reuse this statement let's see if all statements agree...
227 // ... no substatements to deal with, we can freely reuse the original
228 if (origSubstatements.isEmpty()) {
229 LOG.debug("Reusing empty: {}", origEffective);
230 substatements = ImmutableList.of();
232 return origEffective;
235 // ... all are context independent, reuse the original
236 if (allSubstatementsContextIndependent()) {
237 LOG.debug("Reusing context-independent: {}", origEffective);
238 substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
240 return origEffective;
243 // ... copy-sensitive check
244 final List<EffectiveCopy> declCopy = prototype.streamDeclared()
245 .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
246 .filter(Objects::nonNull)
247 .collect(Collectors.toUnmodifiableList());
248 final List<EffectiveCopy> effCopy = prototype.streamEffective()
249 .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
250 .filter(Objects::nonNull)
251 .collect(Collectors.toUnmodifiableList());
253 // ... are any copy-sensitive?
254 if (allReused(declCopy) && allReused(effCopy)) {
255 LOG.debug("Reusing after substatement check: {}", origEffective);
256 substatements = noRefs() ? REUSED_SUBSTATEMENTS
257 : reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
258 .map(copy -> copy.toReusedChild(this)));
260 return origEffective;
263 // *sigh*, ok, heavy lifting through a shallow copy
264 final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
265 .map(copy -> copy.toChildContext(this))
266 .collect(ImmutableList.toImmutableList());
267 final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
268 .map(copy -> copy.toChildContext(this))
269 .collect(ImmutableList.toImmutableList());
270 substatements = declared.isEmpty() ? effective
271 : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
274 // Values are the effective copies, hence this efficiently deals with recursion.
275 // FIXME: YANGTOOLS-1214: deduplicate this return
276 return factory.createEffective(this, declared.stream(), effective.stream());
279 private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
280 if (allSubstatementsContextIndependent()) {
281 LOG.debug("Reusing substatements of: {}", prototype);
282 substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
284 return factory.copyEffective(this, original);
287 // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
288 // the substatement list, as this operation turned out to not affect them.
289 final E effective = super.createEffective(factory);
290 // Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
293 if (sameSubstatements(original.effectiveSubstatements(), effective)) {
294 LOG.debug("Reusing unchanged substatements of: {}", prototype);
295 return factory.copyEffective(this, original);
300 private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
301 return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
304 private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
307 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
308 ret.buildEffective();
311 .collect(Collectors.toUnmodifiableList());
314 private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
315 final Collection<?> copied = effective.effectiveSubstatements();
316 if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
317 // Do not bother if result is treating substatements as transient
321 final Iterator<?> oit = original.iterator();
322 final Iterator<?> cit = copied.iterator();
323 while (oit.hasNext()) {
324 verify(cit.hasNext());
325 // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
327 if (oit.next() != cit.next()) {
331 verify(!cit.hasNext());
335 private static boolean allReused(final List<EffectiveCopy> entries) {
336 return entries.stream().allMatch(EffectiveCopy::isReused);
340 ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
341 return isModified() ? this : prototype.unmodifiedEffectiveSource();
345 boolean hasEmptySubstatements() {
346 if (substatements == null) {
347 return prototype.hasEmptySubstatements();
349 return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
353 boolean noSensitiveSubstatements() {
354 accessSubstatements();
355 if (substatements == null) {
356 // No difference, defer to prototype
357 return prototype.allSubstatementsContextIndependent();
359 if (substatements instanceof List) {
360 // Fully materialized, walk all statements
361 return noSensitiveSubstatements(castEffective(substatements));
364 // Partially-materialized. This case has three distinct outcomes:
365 // - prototype does not have a sensitive statement (1)
366 // - protype has a sensitive substatement, and
367 // - we have not marked is as unsupported (2)
368 // - we have marked it as unsupported (3)
370 // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
371 // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
372 // as affecting the result.
373 return prototype.allSubstatementsContextIndependent()
374 && noSensitiveSubstatements(castMaterialized(substatements).values());
378 <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
379 final @NonNull Class<Z> type) {
380 if (substatements instanceof List) {
381 return super.findSubstatementArgumentImpl(type);
384 final Optional<X> templateArg = prototype.findSubstatementArgument(type);
385 if (templateArg.isEmpty()) {
388 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
389 // X is known to be QName
390 return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
396 boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
397 return substatements instanceof List ? super.hasSubstatementImpl(type)
398 // We do not allow deletion of partially-materialized statements, hence this is accurate
399 : prototype.hasSubstatement(type);
403 public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
404 StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
405 if (substatements instanceof List) {
406 // We have performed materialization, hence we have triggered creation of all our schema tree child
411 final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
412 LOG.debug("Materializing child {} from {}", qname, templateQName);
414 final StmtContext<?, ?, ?> template;
415 if (prototype instanceof InferredStatementContext) {
416 // Note: we need to access namespace here, as the target statement may have already been populated, in which
417 // case we want to obtain the statement in local namespace storage.
418 template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
419 SchemaTreeNamespace.class, templateQName);
421 template = prototype.allSubstatementsStream()
422 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
423 && templateQName.equals(stmt.argument()))
428 if (template == null) {
429 // We do not have a template, this child does not exist. It may be added later, but that is someone else's
431 LOG.debug("Child {} does not have a template", qname);
435 @SuppressWarnings("unchecked")
436 final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
438 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
439 ensureCompletedPhase(ret);
440 addMaterialized(template, ret);
442 LOG.debug("Child {} materialized", qname);
446 // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
447 // BuildGlobalContext, hence it must be called at most once.
448 private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
449 accessSubstatements();
450 return substatements instanceof List ? castEffective(substatements)
451 : initializeSubstatements(castMaterialized(substatements));
455 Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
456 // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
457 // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
458 if (substatements == null) {
459 return ImmutableList.of();
461 accessSubstatements();
462 if (substatements instanceof HashMap) {
463 return castMaterialized(substatements).values();
465 return castEffective(substatements);
470 Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
471 return Stream.empty();
475 Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
476 return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
479 private void accessSubstatements() {
480 if (substatements instanceof String) {
481 throw new VerifyException("Access to " + substatements + " substatements of " + this);
486 void markNoParentRef() {
487 final Object local = substatements;
489 markNoParentRef(castEffective(local));
494 int sweepSubstatements() {
495 final Object local = substatements;
496 substatements = SWEPT_SUBSTATEMENTS;
498 if (local instanceof List) {
499 final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
501 count = countUnswept(list);
506 private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
507 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
508 final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
509 final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
511 final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
512 for (final Mutable<?, ?, ?> stmtContext : declared) {
513 if (stmtContext.isSupportedByFeatures()) {
514 copySubstatement(stmtContext, buffer, materializedSchemaTree);
517 for (final Mutable<?, ?, ?> stmtContext : effective) {
518 copySubstatement(stmtContext, buffer, materializedSchemaTree);
521 final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
522 ret.addAll((Collection) buffer);
531 // Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
532 // sometimes. Tread softly because you tread on my dreams.
535 private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
536 final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType(), targetModule);
537 return effective == null ? null : new EffectiveCopy(stmt, effective);
540 private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
541 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
542 // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
543 // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
545 // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
546 // against parent would change -- and we certainly do not want that to happen.
547 final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
548 if (materialized == null) {
549 copySubstatement(substatement).ifPresent(copy -> {
550 ensureCompletedPhase(copy);
554 buffer.add(materialized);
558 private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
559 return substatement.copyAsChildOf(this, childCopyType(), targetModule);
562 private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
563 final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
564 if (substatements == null) {
565 // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
566 // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
567 // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
568 // resizing operation.
569 materializedSchemaTree = new HashMap<>(4);
570 substatements = materializedSchemaTree;
573 verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
574 materializedSchemaTree = castMaterialized(substatements);
577 final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
578 (StatementContextBase<?, ?, ?>) copy);
579 if (existing != null) {
580 throw new VerifyException(
581 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
585 private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
586 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
587 final StmtContext<?, ?, ?> template) {
588 return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
591 @SuppressWarnings("unchecked")
592 private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
593 return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
596 @SuppressWarnings("unchecked")
597 private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
598 return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
601 // Statement copy mess ends here
604 * KEEP THINGS ORGANIZED!
606 * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
607 * properly updated there.
610 public A argument() {
615 public StatementContextBase<?, ?, ?> getParentContext() {
620 public StorageNodeType getStorageNodeType() {
621 return StorageNodeType.STATEMENT_LOCAL;
625 public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
630 public RootStatementContext<?, ?, ?> getRoot() {
631 return parent.getRoot();
635 public EffectiveConfig effectiveConfig() {
636 return effectiveConfig(parent);
640 protected boolean isIgnoringIfFeatures() {
641 return isIgnoringIfFeatures(parent);
645 protected boolean isIgnoringConfig() {
646 return isIgnoringConfig(parent);
650 protected boolean isParentSupportedByFeatures() {
651 return parent.isSupportedByFeatures();