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.CopyType;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
44 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
50 * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
51 * effective substatements, which are either transformed from that prototype or added by inference.
53 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
54 extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
55 // An effective copy view, with enough information to decide what to do next
56 private static final class EffectiveCopy implements Immutable {
58 private final ReactorStmtCtx<?, ?, ?> orig;
59 // Effective view, if the statement is to be reused it equals to orig
60 private final ReactorStmtCtx<?, ?, ?> copy;
62 EffectiveCopy(final ReactorStmtCtx<?, ?, ?> orig, final ReactorStmtCtx<?, ?, ?> copy) {
63 this.orig = requireNonNull(orig);
64 this.copy = requireNonNull(copy);
71 ReactorStmtCtx<?, ?, ?> toChildContext(final @NonNull InferredStatementContext<?, ?, ?> parent) {
72 return isReused() ? orig.replicaAsChildOf(parent) : copy;
75 ReactorStmtCtx<?, ?, ?> toReusedChild(final @NonNull InferredStatementContext<?, ?, ?> parent) {
76 verify(isReused(), "Attempted to discard copy %s", copy);
77 return orig.replicaAsChildOf(parent);
81 private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
83 // Sentinel objects for 'substatements', String is a good enough type
84 private static final @NonNull String REUSED_SUBSTATEMENTS = "reused";
85 private static final @NonNull String SWEPT_SUBSTATEMENTS = "swept";
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 QNameModule targetModule;
91 private final A argument;
94 * Effective substatements, lazily materialized. This field can have four states:
96 * <li>it can be {@code null}, in which case no materialization has taken place</li>
97 * <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
98 * <li>it can be a {@link List}, in which case full materialization has taken place</li>
99 * <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li>
102 private Object substatements;
104 private InferredStatementContext(final InferredStatementContext<A, D, E> original,
105 final StatementContextBase<?, ?, ?> parent) {
107 this.parent = requireNonNull(parent);
108 this.targetModule = original.targetModule;
109 this.prototype = original.prototype;
110 this.originalCtx = original.originalCtx;
111 this.argument = original.argument;
112 // Substatements are initialized here
113 this.substatements = ImmutableList.of();
116 InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
117 final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
118 super(prototype, myCopyType, childCopyType);
119 this.parent = requireNonNull(parent);
120 this.prototype = requireNonNull(prototype);
121 this.argument = targetModule == null ? prototype.argument()
122 : prototype.definition().adaptArgumentValue(prototype, targetModule);
123 this.targetModule = targetModule;
124 this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
126 // Mark prototype as blocking statement cleanup
131 public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
132 return ImmutableList.of();
136 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
137 return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
141 public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
142 // No need to concat with declared
143 return effectiveSubstatements();
147 public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
148 // No need to concat with declared
149 return effectiveSubstatements().stream();
153 public StatementSourceReference sourceReference() {
154 return originalCtx.sourceReference();
158 public String rawArgument() {
159 return originalCtx.rawArgument();
163 public Optional<StmtContext<A, D, E>> getOriginalCtx() {
164 return Optional.of(originalCtx);
168 public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
169 return Optional.of(prototype);
173 public D declared() {
175 * Share original instance of declared statement between all effective statements which have been copied or
176 * derived from this original declared statement.
178 return originalCtx.declared();
182 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
183 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
187 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
188 final String statementArg) {
189 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
194 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
195 substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
199 void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
200 substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
204 InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
205 return new InferredStatementContext<>(this, newParent);
209 E createEffective(final StatementFactory<A, D, E> factory) {
210 // If we have not materialized we do not have a difference in effective substatements, hence we can forward
211 // towards the source of the statement.
212 accessSubstatements();
213 return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory);
216 private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
217 final E origEffective = prototype.buildEffective();
218 final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
219 origEffective.effectiveSubstatements();
221 // First check if we can reuse the entire prototype
222 if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
223 // FIXME: YANGTOOLS-1214: deduplicate this return
224 return tryToReuseSubstatements(factory, origEffective);
227 // We can reuse this statement let's see if all statements agree...
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 // ... all are context independent, reuse the original
237 if (allSubstatementsContextIndependent()) {
238 LOG.debug("Reusing context-independent: {}", origEffective);
239 substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
241 return origEffective;
244 // ... copy-sensitive check
245 final List<EffectiveCopy> declCopy = prototype.streamDeclared()
246 .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
247 .filter(Objects::nonNull)
248 .collect(Collectors.toUnmodifiableList());
249 final List<EffectiveCopy> effCopy = prototype.streamEffective()
250 .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
251 .filter(Objects::nonNull)
252 .collect(Collectors.toUnmodifiableList());
254 // ... are any copy-sensitive?
255 if (allReused(declCopy) && allReused(effCopy)) {
256 LOG.debug("Reusing after substatement check: {}", origEffective);
257 substatements = noRefs() ? REUSED_SUBSTATEMENTS
258 : reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
259 .map(copy -> copy.toReusedChild(this)));
261 return origEffective;
264 // *sigh*, ok, heavy lifting through a shallow copy
265 final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
266 .map(copy -> copy.toChildContext(this))
267 .collect(ImmutableList.toImmutableList());
268 final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
269 .map(copy -> copy.toChildContext(this))
270 .collect(ImmutableList.toImmutableList());
271 substatements = declared.isEmpty() ? effective
272 : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
275 // Values are the effective copies, hence this efficiently deals with recursion.
276 // FIXME: YANGTOOLS-1214: deduplicate this return
277 return factory.createEffective(this, declared.stream(), effective.stream());
280 private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
281 if (allSubstatementsContextIndependent()) {
282 LOG.debug("Reusing substatements of: {}", prototype);
283 substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
285 return factory.copyEffective(this, original);
288 // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
289 // the substatement list, as this operation turned out to not affect them.
290 final E effective = super.createEffective(factory);
291 // Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
294 if (sameSubstatements(original.effectiveSubstatements(), effective)) {
295 LOG.debug("Reusing unchanged substatements of: {}", prototype);
296 return factory.copyEffective(this, original);
301 private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
302 return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
305 private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
308 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
309 ret.buildEffective();
312 .collect(Collectors.toUnmodifiableList());
315 private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
316 final Collection<?> copied = effective.effectiveSubstatements();
317 if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
318 // Do not bother if result is treating substatements as transient
322 final Iterator<?> oit = original.iterator();
323 final Iterator<?> cit = copied.iterator();
324 while (oit.hasNext()) {
325 verify(cit.hasNext());
326 // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
328 if (oit.next() != cit.next()) {
332 verify(!cit.hasNext());
336 private static boolean allReused(final List<EffectiveCopy> entries) {
337 return entries.stream().allMatch(EffectiveCopy::isReused);
341 ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
342 return isModified() ? this : prototype.unmodifiedEffectiveSource();
346 boolean hasEmptySubstatements() {
347 if (substatements == null) {
348 return prototype.hasEmptySubstatements();
350 return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
354 boolean noSensitiveSubstatements() {
355 accessSubstatements();
356 if (substatements == null) {
357 // No difference, defer to prototype
358 return prototype.allSubstatementsContextIndependent();
360 if (substatements instanceof List) {
361 // Fully materialized, walk all statements
362 return noSensitiveSubstatements(castEffective(substatements));
365 // Partially-materialized. This case has three distinct outcomes:
366 // - prototype does not have a sensitive statement (1)
367 // - protype has a sensitive substatement, and
368 // - we have not marked is as unsupported (2)
369 // - we have marked it as unsupported (3)
371 // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
372 // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
373 // as affecting the result.
374 return prototype.allSubstatementsContextIndependent()
375 && noSensitiveSubstatements(castMaterialized(substatements).values());
379 <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
380 final @NonNull Class<Z> type) {
381 if (substatements instanceof List) {
382 return super.findSubstatementArgumentImpl(type);
385 final Optional<X> templateArg = prototype.findSubstatementArgument(type);
386 if (templateArg.isEmpty()) {
389 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
390 // X is known to be QName
391 return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
397 boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
398 return substatements instanceof List ? super.hasSubstatementImpl(type)
399 // We do not allow deletion of partially-materialized statements, hence this is accurate
400 : prototype.hasSubstatement(type);
404 public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
405 StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
406 if (substatements instanceof List) {
407 // We have performed materialization, hence we have triggered creation of all our schema tree child
412 final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
413 LOG.debug("Materializing child {} from {}", qname, templateQName);
415 final StmtContext<?, ?, ?> template;
416 if (prototype instanceof InferredStatementContext) {
417 // Note: we need to access namespace here, as the target statement may have already been populated, in which
418 // case we want to obtain the statement in local namespace storage.
419 template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
420 SchemaTreeNamespace.class, templateQName);
422 template = prototype.allSubstatementsStream()
423 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
424 && templateQName.equals(stmt.argument()))
429 if (template == null) {
430 // We do not have a template, this child does not exist. It may be added later, but that is someone else's
432 LOG.debug("Child {} does not have a template", qname);
436 @SuppressWarnings("unchecked")
437 final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
439 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
440 ensureCompletedPhase(ret);
441 addMaterialized(template, ret);
443 LOG.debug("Child {} materialized", qname);
447 // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
448 // BuildGlobalContext, hence it must be called at most once.
449 private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
450 accessSubstatements();
451 return substatements instanceof List ? castEffective(substatements)
452 : initializeSubstatements(castMaterialized(substatements));
456 Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
457 // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
458 // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
459 if (substatements == null) {
460 return ImmutableList.of();
462 accessSubstatements();
463 if (substatements instanceof HashMap) {
464 return castMaterialized(substatements).values();
466 return castEffective(substatements);
471 Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
472 return Stream.empty();
476 Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
477 return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
480 private void accessSubstatements() {
481 if (substatements instanceof String) {
482 throw new VerifyException("Access to " + substatements + " substatements of " + this);
487 void markNoParentRef() {
488 final Object local = substatements;
490 markNoParentRef(castEffective(local));
495 int sweepSubstatements() {
496 final Object local = substatements;
497 substatements = SWEPT_SUBSTATEMENTS;
499 if (local instanceof List) {
500 final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
502 count = countUnswept(list);
507 private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
508 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
509 final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
510 final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
512 final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
513 for (final Mutable<?, ?, ?> stmtContext : declared) {
514 if (stmtContext.isSupportedByFeatures()) {
515 copySubstatement(stmtContext, buffer, materializedSchemaTree);
518 for (final Mutable<?, ?, ?> stmtContext : effective) {
519 copySubstatement(stmtContext, buffer, materializedSchemaTree);
522 final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
523 ret.addAll((Collection) buffer);
532 // Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
533 // sometimes. Tread softly because you tread on my dreams.
536 private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
537 final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType(), targetModule);
538 return effective == null ? null : new EffectiveCopy(stmt, effective);
541 private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
542 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
543 // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
544 // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
546 // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
547 // against parent would change -- and we certainly do not want that to happen.
548 final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
549 if (materialized == null) {
550 copySubstatement(substatement).ifPresent(copy -> {
551 ensureCompletedPhase(copy);
555 buffer.add(materialized);
559 private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
560 return substatement.copyAsChildOf(this, childCopyType(), targetModule);
563 private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
564 final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
565 if (substatements == null) {
566 // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
567 // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
568 // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
569 // resizing operation.
570 materializedSchemaTree = new HashMap<>(4);
571 substatements = materializedSchemaTree;
574 verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
575 materializedSchemaTree = castMaterialized(substatements);
578 final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
579 (StatementContextBase<?, ?, ?>) copy);
580 if (existing != null) {
581 throw new VerifyException(
582 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
586 private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
587 final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
588 final StmtContext<?, ?, ?> template) {
589 return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
592 @SuppressWarnings("unchecked")
593 private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
594 return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
597 @SuppressWarnings("unchecked")
598 private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
599 return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
602 // Statement copy mess ends here
605 * KEEP THINGS ORGANIZED!
607 * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
608 * properly updated there.
612 public SchemaPath schemaPath() {
613 return substatementGetSchemaPath();
617 public A argument() {
622 public StatementContextBase<?, ?, ?> getParentContext() {
627 public StorageNodeType getStorageNodeType() {
628 return StorageNodeType.STATEMENT_LOCAL;
632 public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
637 public RootStatementContext<?, ?, ?> getRoot() {
638 return parent.getRoot();
642 public EffectiveConfig effectiveConfig() {
643 return effectiveConfig(parent);
647 protected boolean isIgnoringIfFeatures() {
648 return isIgnoringIfFeatures(parent);
652 protected boolean isIgnoringConfig() {
653 return isIgnoringConfig(parent);
657 protected boolean isParentSupportedByFeatures() {
658 return parent.isSupportedByFeatures();