2 * Copyright (c) 2015 Cisco Systems, Inc. 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.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static com.google.common.base.Verify.verify;
14 import static java.util.Objects.requireNonNull;
16 import com.google.common.annotations.Beta;
17 import com.google.common.collect.ImmutableCollection;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMultimap;
20 import com.google.common.collect.Multimap;
21 import com.google.common.collect.Multimaps;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.EnumMap;
26 import java.util.EventListener;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Optional;
32 import java.util.stream.Stream;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
38 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
39 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
41 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
42 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
47 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
61 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
62 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
66 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * Core reactor statement implementation of {@link Mutable}.
73 * @param <A> Argument type
74 * @param <D> Declared Statement representation
75 * @param <E> Effective Statement representation
77 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
78 extends ReactorStmtCtx<A, D, E> {
80 * Event listener when an item is added to model namespace.
82 interface OnNamespaceItemAdded extends EventListener {
84 * Invoked whenever a new item is added to a namespace.
86 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
90 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
92 interface OnPhaseFinished extends EventListener {
94 * Invoked whenever a processing phase has finished.
96 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
100 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
102 interface ContextMutation {
104 boolean isFinished();
107 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
109 // Flag bit assignments
110 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
111 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
112 private static final int IS_IGNORE_IF_FEATURE = 0x04;
113 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
114 // Note: these four are related
115 private static final int IS_IGNORE_CONFIG = 0x10;
116 private static final int HAVE_IGNORE_CONFIG = 0x20;
117 private static final int IS_CONFIGURATION = 0x40;
118 private static final int HAVE_CONFIGURATION = 0x80;
120 // Have-and-set flag constants, also used as masks
121 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
122 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
123 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
124 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
125 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
127 private final CopyHistory copyHistory;
128 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
129 // operations, hence we want to keep it close by.
130 private final @NonNull StatementDefinitionContext<A, D, E> definition;
132 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
133 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
135 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
137 private @Nullable ModelProcessingPhase completedPhase;
139 // Master flag controlling whether this context can yield an effective statement
140 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
141 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
142 private boolean isSupportedToBuildEffective = true;
144 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
145 private boolean fullyDefined;
147 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
148 // hence improve memory layout.
151 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
152 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
153 private volatile SchemaPath schemaPath;
155 // Copy constructor used by subclasses to implement reparent()
156 StatementContextBase(final StatementContextBase<A, D, E> original) {
157 this.copyHistory = original.copyHistory;
158 this.definition = original.definition;
160 this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
161 this.fullyDefined = original.fullyDefined;
162 this.completedPhase = original.completedPhase;
163 this.flags = original.flags;
166 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
167 this.definition = requireNonNull(def);
168 this.copyHistory = CopyHistory.original();
171 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
172 this.definition = requireNonNull(def);
173 this.copyHistory = requireNonNull(copyHistory);
177 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
178 return effectOfStatement;
182 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
183 if (effectOfStatement.isEmpty()) {
184 effectOfStatement = new ArrayList<>(1);
186 effectOfStatement.add(ctx);
190 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
191 if (ctxs.isEmpty()) {
195 if (effectOfStatement.isEmpty()) {
196 effectOfStatement = new ArrayList<>(ctxs.size());
198 effectOfStatement.addAll(ctxs);
202 public boolean isSupportedByFeatures() {
203 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
205 return fl == SET_SUPPORTED_BY_FEATURES;
207 if (isIgnoringIfFeatures()) {
208 flags |= SET_SUPPORTED_BY_FEATURES;
213 * If parent is supported, we need to check if-features statements of this context.
215 if (isParentSupportedByFeatures()) {
216 // If the set of supported features has not been provided, all features are supported by default.
217 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
218 SupportedFeatures.SUPPORTED_FEATURES);
219 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
220 flags |= SET_SUPPORTED_BY_FEATURES;
225 // Either parent is not supported or this statement is not supported
226 flags |= HAVE_SUPPORTED_BY_FEATURES;
230 protected abstract boolean isParentSupportedByFeatures();
233 public boolean isSupportedToBuildEffective() {
234 return isSupportedToBuildEffective;
238 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
239 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
243 public CopyHistory getCopyHistory() {
248 public ModelProcessingPhase getCompletedPhase() {
249 return completedPhase;
252 // FIXME: this should be propagated through a correct constructor
254 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
255 this.completedPhase = completedPhase;
259 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
260 final Class<@NonNull N> type, final T key, final U value) {
261 addToNamespace(type, key, value);
264 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
265 final List<StatementContextBase<?, ?, ?>> effective) {
266 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
269 private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
270 final List<StatementContextBase<?, ?, ?>> effective) {
271 return effective.isEmpty() ? ImmutableList.of() : effective;
274 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
276 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
277 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef) {
278 if (effective.isEmpty()) {
282 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
283 while (iterator.hasNext()) {
284 final StmtContext<?, ?, ?> next = iterator.next();
285 if (statementDef.equals(next.publicDefinition())) {
290 return shrinkEffective(effective);
294 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
295 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
296 * definition and statement argument match with one of the effective substatements' statement definition
300 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
302 * @param statementDef statement definition of the statement context to remove
303 * @param statementArg statement argument of the statement context to remove
305 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
306 String statementArg);
308 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
309 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef,
310 final String statementArg) {
311 if (statementArg == null) {
312 return removeStatementFromEffectiveSubstatements(effective, statementDef);
315 if (effective.isEmpty()) {
319 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
320 while (iterator.hasNext()) {
321 final Mutable<?, ?, ?> next = iterator.next();
322 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
327 return shrinkEffective(effective);
330 // YANG example: RPC/action statements always have 'input' and 'output' defined
332 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
333 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
334 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
335 // StatementContextBase subclass.
336 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
337 ImplicitSubstatement.of(sourceReference()), rawArg);
338 support.onStatementAdded(ret);
339 addEffectiveSubstatement(ret);
344 * Adds an effective statement to collection of substatements.
346 * @param substatement substatement
347 * @throws IllegalStateException if added in declared phase
348 * @throws NullPointerException if statement parameter is null
350 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
352 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
353 final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
354 verifyStatement(substatement);
356 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
357 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
358 final ModelProcessingPhase phase = completedPhase;
360 ensureCompletedPhase(stmt, phase);
367 * Adds an effective statement to collection of substatements.
369 * @param statements substatements
370 * @throws IllegalStateException
371 * if added in declared phase
372 * @throws NullPointerException
373 * if statement parameter is null
375 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
376 if (!statements.isEmpty()) {
377 statements.forEach(StatementContextBase::verifyStatement);
378 addEffectiveSubstatementsImpl(statements);
382 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
384 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
385 final List<StatementContextBase<?, ?, ?>> effective,
386 final Collection<? extends Mutable<?, ?, ?>> statements) {
387 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
388 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
389 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
390 final ModelProcessingPhase phase = completedPhase;
392 for (StatementContextBase<?, ?, ?> stmt : casted) {
393 ensureCompletedPhase(stmt, phase);
397 resized.addAll(casted);
401 abstract Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete();
403 // exposed for InferredStatementContext only
404 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
405 verifyStatement(stmt);
406 final ModelProcessingPhase phase = completedPhase;
408 ensureCompletedPhase((StatementContextBase<?, ?, ?>) stmt, phase);
412 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
413 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
414 // any statements which did not complete the same phase as the root statement.
415 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
416 final ModelProcessingPhase phase) {
417 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
420 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
421 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
424 private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
425 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
426 // We cannot allow statement to be further mutated
427 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
429 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
432 final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
433 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
434 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
435 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
436 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
437 "Effective statement cannot be added in declared phase at: %s", sourceReference());
439 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
442 // These two exists only due to memory optimization, should live in AbstractResumedStatement
443 final boolean fullyDefined() {
447 final void setFullyDefined() {
451 // Exposed for ReplicaStatementContext
453 E createEffective() {
454 return definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this), streamDeclared(),
458 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
460 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
463 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
464 * this method does nothing.
466 * @param phase to be executed (completed)
467 * @return true if phase was successfully completed
468 * @throws SourceException when an error occurred in source parsing
470 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
471 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
474 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
475 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
476 if (completeChildren(phase) && finished) {
477 onPhaseCompleted(phase);
483 private boolean completeChildren(final ModelProcessingPhase phase) {
484 boolean finished = true;
485 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
486 finished &= child.tryToCompletePhase(phase);
488 for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
489 finished &= child.tryToCompletePhase(phase);
494 private boolean runMutations(final ModelProcessingPhase phase) {
495 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
496 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
499 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
500 boolean finished = true;
501 final Iterator<ContextMutation> it = openMutations.iterator();
502 while (it.hasNext()) {
503 final ContextMutation current = it.next();
504 if (current.isFinished()) {
511 if (openMutations.isEmpty()) {
512 phaseMutation.removeAll(phase);
513 cleanupPhaseMutation();
518 private void cleanupPhaseMutation() {
519 if (phaseMutation.isEmpty()) {
520 phaseMutation = ImmutableMultimap.of();
525 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
528 * that was to be completed (finished)
529 * @throws SourceException
530 * when an error occurred in source parsing
532 private void onPhaseCompleted(final ModelProcessingPhase phase) {
533 completedPhase = phase;
535 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
536 if (!listeners.isEmpty()) {
537 runPhaseListeners(phase, listeners);
541 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
542 final Iterator<OnPhaseFinished> listener = listeners.iterator();
543 while (listener.hasNext()) {
544 final OnPhaseFinished next = listener.next();
545 if (next.phaseFinished(this, phase)) {
550 if (listeners.isEmpty()) {
551 phaseListeners.removeAll(phase);
552 if (phaseListeners.isEmpty()) {
553 phaseListeners = ImmutableMultimap.of();
559 * Ends declared section of current node.
561 void endDeclared(final ModelProcessingPhase phase) {
562 definition.onDeclarationFinished(this, phase);
566 final StatementDefinitionContext<A, D, E> definition() {
570 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
571 final OnNamespaceItemAdded listener) {
572 final Object potential = getFromNamespace(type, key);
573 if (potential != null) {
574 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
575 listener.namespaceItemAdded(this, type, key, potential);
579 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
581 void onValueAdded(final Object value) {
582 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
587 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
588 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
589 final OnNamespaceItemAdded listener) {
590 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
591 if (existing.isPresent()) {
592 final Entry<K, V> entry = existing.get();
593 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
594 waitForPhase(entry.getValue(), type, phase, criterion, listener);
598 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
599 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
601 boolean onValueAdded(final K key, final V value) {
602 if (criterion.match(key)) {
603 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
604 waitForPhase(value, type, phase, criterion, listener);
613 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
614 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
615 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
616 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
618 final Entry<K, V> match = optMatch.get();
619 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
622 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
623 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
624 final OnNamespaceItemAdded listener) {
625 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
626 (context, phaseCompleted) -> {
627 selectMatch(type, criterion, listener);
632 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
633 final Class<N> type) {
634 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
635 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
638 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
641 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
642 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
646 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
647 * the listener is notified immediately.
649 * @param phase requested completion phase
650 * @param listener listener to invoke
651 * @throws NullPointerException if any of the arguments is null
653 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
654 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
655 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
657 ModelProcessingPhase finishedPhase = completedPhase;
658 while (finishedPhase != null) {
659 if (phase.equals(finishedPhase)) {
660 listener.phaseFinished(this, finishedPhase);
663 finishedPhase = finishedPhase.getPreviousPhase();
665 if (phaseListeners.isEmpty()) {
666 phaseListeners = newMultimap();
669 phaseListeners.put(phase, listener);
673 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
675 * @throws IllegalStateException when the mutation was registered after phase was completed
677 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
678 ModelProcessingPhase finishedPhase = completedPhase;
679 while (finishedPhase != null) {
680 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
682 finishedPhase = finishedPhase.getPreviousPhase();
685 if (phaseMutation.isEmpty()) {
686 phaseMutation = newMultimap();
688 phaseMutation.put(phase, mutation);
691 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
692 if (!phaseMutation.isEmpty()) {
693 phaseMutation.remove(phase, mutation);
694 cleanupPhaseMutation();
699 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
700 final KT key,final StmtContext<?, ?, ?> stmt) {
701 addContextToNamespace(namespace, key, stmt);
705 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
706 final QNameModule targetModule) {
707 checkEffectiveModelCompleted(this);
709 final StatementSupport<A, D, E> support = definition.support();
710 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
712 case CONTEXT_INDEPENDENT:
713 if (hasEmptySubstatements()) {
714 // This statement is context-independent and has no substatements -- hence it can be freely shared.
715 return Optional.of(replicaAsChildOf(parent));
717 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
720 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
721 // context, so that we can support building an effective statement without copying
722 // anything -- we will typically end up not being inferred against. In that case,
723 // this slim context should end up dealing with differences at buildContext()
724 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
725 // cannot be shared across instances).
726 return Optional.of(parent.childCopyOf(this, type, targetModule));
728 return Optional.empty();
730 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
732 throw new IllegalStateException("Unhandled policy " + policy);
737 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
738 final QNameModule targetModule) {
739 checkEffectiveModelCompleted(stmt);
740 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
741 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
744 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
745 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
746 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
747 original.publicDefinition());
749 final StatementContextBase<X, Y, Z> result;
750 final InferredStatementContext<X, Y, Z> copy;
752 if (implicitParent.isPresent()) {
753 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
754 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
755 original.argument(), type);
757 final CopyType childCopyType;
759 case ADDED_BY_AUGMENTATION:
760 childCopyType = CopyType.ORIGINAL;
762 case ADDED_BY_USES_AUGMENTATION:
763 childCopyType = CopyType.ADDED_BY_USES;
768 childCopyType = type;
771 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
772 result.addEffectiveSubstatement(copy);
774 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
777 original.definition.onStatementAdded(copy);
782 public final StatementContextBase<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
783 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
784 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
787 final @NonNull StatementContextBase<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
788 return new ReplicaStatementContext<>(stmt, this);
791 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
792 final ModelProcessingPhase phase = stmt.getCompletedPhase();
793 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
794 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
798 public final boolean hasImplicitParentSupport() {
799 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
803 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
804 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
805 original.publicDefinition());
806 if (optImplicit.isEmpty()) {
810 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
811 final CopyType type = original.getCopyHistory().getLastOperation();
812 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
813 original.sourceReference(), original.rawArgument(), original.argument(), type);
815 result.addEffectiveSubstatement(original.reparent(result));
816 result.setCompletedPhase(original.getCompletedPhase());
820 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
823 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
825 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
827 abstract boolean hasEmptySubstatements();
830 * Config statements are not all that common which means we are performing a recursive search towards the root
831 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
832 * for the (usually non-existent) config statement.
835 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
836 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
839 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
840 * {@link #isIgnoringConfig(StatementContextBase)}.
842 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
843 final int fl = flags & SET_CONFIGURATION;
845 return fl == SET_CONFIGURATION;
847 if (isIgnoringConfig(parent)) {
848 // Note: SET_CONFIGURATION has been stored in flags
852 final boolean isConfig;
853 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
854 if (optConfig.isPresent()) {
855 isConfig = optConfig.orElseThrow();
857 // Validity check: if parent is config=false this cannot be a config=true
858 InferenceException.throwIf(!parent.isConfiguration(), sourceReference(),
859 "Parent node has config=false, this node must not be specifed as config=true");
862 // If "config" statement is not specified, the default is the same as the parent's "config" value.
863 isConfig = parent.isConfiguration();
866 // Resolved, make sure we cache this return
867 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
871 protected abstract boolean isIgnoringConfig();
874 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
875 * keep on returning the same result without performing any lookups. Exists only to support
876 * {@link SubstatementContext#isIgnoringConfig()}.
879 * Note: use of this method implies that {@link #isConfiguration()} is realized with
880 * {@link #isConfiguration(StatementContextBase)}.
882 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
883 final int fl = flags & SET_IGNORE_CONFIG;
885 return fl == SET_IGNORE_CONFIG;
887 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
888 flags |= SET_IGNORE_CONFIG;
892 flags |= HAVE_IGNORE_CONFIG;
896 protected abstract boolean isIgnoringIfFeatures();
899 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
900 * keep on returning the same result without performing any lookups. Exists only to support
901 * {@link SubstatementContext#isIgnoringIfFeatures()}.
903 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
904 final int fl = flags & SET_IGNORE_IF_FEATURE;
906 return fl == SET_IGNORE_IF_FEATURE;
908 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
909 flags |= SET_IGNORE_IF_FEATURE;
913 flags |= HAVE_IGNORE_IF_FEATURE;
917 abstract @NonNull Optional<SchemaPath> schemaPath();
919 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
921 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
922 SchemaPath local = schemaPath;
924 synchronized (this) {
927 schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
932 return Optional.ofNullable(local);
936 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
937 final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
938 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
939 final SchemaPath parentPath = maybeParentPath.get();
941 if (StmtContextUtils.isUnknownStatement(this)) {
942 return parentPath.createChild(publicDefinition().getStatementName());
944 final Object argument = argument();
945 if (argument instanceof QName) {
946 final QName qname = (QName) argument;
947 if (producesDeclared(UsesStatement.class)) {
948 return maybeParentPath.orElse(null);
951 return parentPath.createChild(qname);
953 if (argument instanceof String) {
954 // FIXME: This may yield illegal argument exceptions
955 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
956 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
957 return parentPath.createChild(qname);
959 if (argument instanceof SchemaNodeIdentifier
960 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
961 || producesDeclared(DeviationStatement.class))) {
963 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
966 // FIXME: this does not look right
967 return maybeParentPath.orElse(null);