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.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.MoreObjects;
17 import com.google.common.base.MoreObjects.ToStringHelper;
18 import com.google.common.collect.ImmutableCollection;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMultimap;
21 import com.google.common.collect.Multimap;
22 import com.google.common.collect.Multimaps;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.EventListener;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.Optional;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.common.YangVersion;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
43 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
44 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
45 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
50 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
51 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
69 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
70 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
73 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * Core reactor statement implementation of {@link Mutable}.
81 * @param <A> Argument type
82 * @param <D> Declared Statement representation
83 * @param <E> Effective Statement representation
85 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
86 extends NamespaceStorageSupport implements Mutable<A, D, E> {
88 * Event listener when an item is added to model namespace.
90 interface OnNamespaceItemAdded extends EventListener {
92 * Invoked whenever a new item is added to a namespace.
94 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
98 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
100 interface OnPhaseFinished extends EventListener {
102 * Invoked whenever a processing phase has finished.
104 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
108 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
110 interface ContextMutation {
112 boolean isFinished();
115 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
117 // Flag bit assignments
118 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
119 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
120 private static final int IS_IGNORE_IF_FEATURE = 0x04;
121 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
122 // Note: these four are related
123 private static final int IS_IGNORE_CONFIG = 0x10;
124 private static final int HAVE_IGNORE_CONFIG = 0x20;
125 private static final int IS_CONFIGURATION = 0x40;
126 private static final int HAVE_CONFIGURATION = 0x80;
128 // Have-and-set flag constants, also used as masks
129 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
130 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
131 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
132 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
133 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
135 private final CopyHistory copyHistory;
136 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
137 // operations, hence we want to keep it close by.
138 private final @NonNull StatementDefinitionContext<A, D, E> definition;
140 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
141 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
143 // Note: this field is accessed either directly, or under substatementsInitialized == true
144 private List<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
146 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
148 private @Nullable ModelProcessingPhase completedPhase;
149 private @Nullable E effectiveInstance;
151 // Master flag controlling whether this context can yield an effective statement
152 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
153 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
154 private boolean isSupportedToBuildEffective = true;
156 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
157 private boolean fullyDefined;
159 // Flag for InferredStatementContext. This is hiding in the alignment shadow created by above boolean.
160 private boolean substatementsInitialized;
162 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
163 // hence improve memory layout.
166 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
167 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
168 private SchemaPath schemaPath;
170 // Copy constructor used by subclasses to implement reparent()
171 StatementContextBase(final StatementContextBase<A, D, E> original) {
172 this.copyHistory = original.copyHistory;
173 this.definition = original.definition;
175 this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
176 this.fullyDefined = original.fullyDefined;
177 this.completedPhase = original.completedPhase;
178 this.flags = original.flags;
181 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
182 this.definition = requireNonNull(def);
183 this.copyHistory = CopyHistory.original();
186 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
187 this.definition = requireNonNull(def);
188 this.copyHistory = requireNonNull(copyHistory);
192 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
193 return effectOfStatement;
197 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
198 if (effectOfStatement.isEmpty()) {
199 effectOfStatement = new ArrayList<>(1);
201 effectOfStatement.add(ctx);
205 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
206 if (ctxs.isEmpty()) {
210 if (effectOfStatement.isEmpty()) {
211 effectOfStatement = new ArrayList<>(ctxs.size());
213 effectOfStatement.addAll(ctxs);
217 public boolean isSupportedByFeatures() {
218 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
220 return fl == SET_SUPPORTED_BY_FEATURES;
222 if (isIgnoringIfFeatures()) {
223 flags |= SET_SUPPORTED_BY_FEATURES;
228 * If parent is supported, we need to check if-features statements of this context.
230 if (isParentSupportedByFeatures()) {
231 // If the set of supported features has not been provided, all features are supported by default.
232 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
233 SupportedFeatures.SUPPORTED_FEATURES);
234 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
235 flags |= SET_SUPPORTED_BY_FEATURES;
240 // Either parent is not supported or this statement is not supported
241 flags |= HAVE_SUPPORTED_BY_FEATURES;
245 protected abstract boolean isParentSupportedByFeatures();
248 public boolean isSupportedToBuildEffective() {
249 return isSupportedToBuildEffective;
253 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
254 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
258 public CopyHistory getCopyHistory() {
263 public ModelProcessingPhase getCompletedPhase() {
264 return completedPhase;
267 // FIXME: this should be propagated through a correct constructor
269 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
270 this.completedPhase = completedPhase;
274 public abstract StatementContextBase<?, ?, ?> getParentContext();
277 * Returns the model root for this statement.
279 * @return root context of statement
282 public abstract RootStatementContext<?, ?, ?> getRoot();
285 public final @NonNull Registry getBehaviourRegistry() {
286 return getRoot().getBehaviourRegistryImpl();
290 public final YangVersion getRootVersion() {
291 return getRoot().getRootVersionImpl();
295 public final void setRootVersion(final YangVersion version) {
296 getRoot().setRootVersionImpl(version);
300 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
301 getRoot().addMutableStmtToSealImpl(mutableStatement);
305 public final void addRequiredSource(final SourceIdentifier dependency) {
306 getRoot().addRequiredSourceImpl(dependency);
310 public final void setRootIdentifier(final SourceIdentifier identifier) {
311 getRoot().setRootIdentifierImpl(identifier);
315 public final boolean isEnabledSemanticVersioning() {
316 return getRoot().isEnabledSemanticVersioningImpl();
320 public StatementSource getStatementSource() {
321 return getStatementSourceReference().getStatementSource();
325 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
326 final Class<N> type) {
327 return getLocalNamespace(type);
331 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
332 return getNamespace(type);
336 * Associate a value with a key within a namespace.
338 * @param type Namespace type
341 * @param <K> namespace key type
342 * @param <V> namespace value type
343 * @param <N> namespace type
344 * @param <T> key type
345 * @param <U> value type
346 * @throws NamespaceNotAvailableException when the namespace is not available.
349 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
350 final Class<@NonNull N> type, final T key, final U value) {
351 addToNamespace(type, key, value);
355 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
358 * Return a value associated with specified key within a namespace.
360 * @param type Namespace type
362 * @param <K> namespace key type
363 * @param <V> namespace value type
364 * @param <N> namespace type
365 * @param <T> key type
366 * @return Value, or null if there is no element
367 * @throws NamespaceNotAvailableException when the namespace is not available.
370 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(
371 final Class<@NonNull N> type, final T key) {
372 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
376 public final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
377 ensureEffectiveSubstatements();
378 if (effective instanceof ImmutableCollection) {
382 return Collections.unmodifiableCollection(effective);
385 private void shrinkEffective() {
386 // Initialization guarded by all callers
387 if (effective.isEmpty()) {
388 effective = ImmutableList.of();
392 // Note: has side-effect of ensureEffectiveSubstatements()
393 public final void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
394 ensureEffectiveSubstatements();
395 if (effective.isEmpty()) {
399 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
400 while (iterator.hasNext()) {
401 final StmtContext<?, ?, ?> next = iterator.next();
402 if (statementDef.equals(next.getPublicDefinition())) {
411 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
412 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
413 * definition and statement argument match with one of the effective substatements' statement definition
417 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
419 * @param statementDef statement definition of the statement context to remove
420 * @param statementArg statement argument of the statement context to remove
422 public final void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
423 final String statementArg) {
424 if (statementArg == null) {
425 // Note: has side-effect of ensureEffectiveSubstatements()
426 removeStatementFromEffectiveSubstatements(statementDef);
428 ensureEffectiveSubstatements();
431 if (effective.isEmpty()) {
435 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
436 while (iterator.hasNext()) {
437 final Mutable<?, ?, ?> next = iterator.next();
438 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
446 // YANG example: RPC/action statements always have 'input' and 'output' defined
448 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
449 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
450 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
451 // StatementContextBase subclass.
452 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
453 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
454 support.onStatementAdded(ret);
455 addEffectiveSubstatement(ret);
460 * Adds an effective statement to collection of substatements.
462 * @param substatement substatement
463 * @throws IllegalStateException
464 * if added in declared phase
465 * @throws NullPointerException
466 * if statement parameter is null
468 public final void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
469 verifyStatement(substatement);
470 ensureEffectiveSubstatements();
471 beforeAddEffectiveStatement(1);
473 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
474 final ModelProcessingPhase phase = completedPhase;
476 ensureCompletedPhase(stmt, phase);
482 * Adds an effective statement to collection of substatements.
484 * @param statements substatements
485 * @throws IllegalStateException
486 * if added in declared phase
487 * @throws NullPointerException
488 * if statement parameter is null
490 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
491 if (!statements.isEmpty()) {
492 statements.forEach(StatementContextBase::verifyStatement);
493 ensureEffectiveSubstatements();
494 beforeAddEffectiveStatement(statements.size());
495 doAddEffectiveSubstatements(statements);
499 // exposed for InferredStatementContext, which we expect to initialize effective substatements
500 void ensureEffectiveSubstatements() {
501 // No-op for everything except InferredStatementContext
504 // Exposed for InferredStatementContextr only, others do not need initialization
505 Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete() {
509 // exposed for InferredStatementContext only
510 final void addInitialEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
511 verify(!substatementsInitialized, "Attempted to re-initialized statement {} with {}", this, statements);
512 substatementsInitialized = true;
514 if (!statements.isEmpty()) {
515 statements.forEach(StatementContextBase::verifyStatement);
516 beforeAddEffectiveStatementUnsafe(statements.size());
517 doAddEffectiveSubstatements(statements);
521 private void doAddEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
522 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
523 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
524 final ModelProcessingPhase phase = completedPhase;
526 for (StatementContextBase<?, ?, ?> stmt : casted) {
527 ensureCompletedPhase(stmt, phase);
531 // Initialization guarded by all callers
532 effective.addAll(casted);
535 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
536 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
537 // any statements which did not complete the same phase as the root statement.
538 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
539 final ModelProcessingPhase phase) {
540 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
543 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
544 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
547 private void beforeAddEffectiveStatement(final int toAdd) {
548 // We cannot allow statement to be further mutated
549 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
550 getStatementSourceReference());
551 beforeAddEffectiveStatementUnsafe(toAdd);
554 private void beforeAddEffectiveStatementUnsafe(final int toAdd) {
555 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
556 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
557 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
558 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
560 // Initialization guarded by all callers
561 if (effective.isEmpty()) {
562 effective = new ArrayList<>(toAdd);
566 // These two exists only due to memory optimization, should live in AbstractResumedStatement
567 final boolean fullyDefined() {
571 final void setFullyDefined() {
575 // These two exist only due to memory optimization, should live in InferredStatementContext
576 final boolean substatementsInitialized() {
577 return substatementsInitialized;
580 final void setSubstatementsInitialized() {
581 substatementsInitialized = true;
585 public E buildEffective() {
587 return (existing = effectiveInstance) != null ? existing : loadEffective();
590 private E loadEffective() {
591 return effectiveInstance = definition.getFactory().createEffective(this);
595 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
596 * this method does nothing.
598 * @param phase to be executed (completed)
599 * @return true if phase was successfully completed
600 * @throws SourceException when an error occurred in source parsing
602 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
603 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
606 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
607 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
608 if (completeChildren(phase) && finished) {
609 onPhaseCompleted(phase);
615 private boolean completeChildren(final ModelProcessingPhase phase) {
616 boolean finished = true;
617 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
618 finished &= child.tryToCompletePhase(phase);
620 for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
621 finished &= child.tryToCompletePhase(phase);
626 private boolean runMutations(final ModelProcessingPhase phase) {
627 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
628 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
631 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
632 boolean finished = true;
633 final Iterator<ContextMutation> it = openMutations.iterator();
634 while (it.hasNext()) {
635 final ContextMutation current = it.next();
636 if (current.isFinished()) {
643 if (openMutations.isEmpty()) {
644 phaseMutation.removeAll(phase);
645 cleanupPhaseMutation();
650 private void cleanupPhaseMutation() {
651 if (phaseMutation.isEmpty()) {
652 phaseMutation = ImmutableMultimap.of();
657 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
660 * that was to be completed (finished)
661 * @throws SourceException
662 * when an error occurred in source parsing
664 private void onPhaseCompleted(final ModelProcessingPhase phase) {
665 completedPhase = phase;
667 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
668 if (!listeners.isEmpty()) {
669 runPhaseListeners(phase, listeners);
673 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
674 final Iterator<OnPhaseFinished> listener = listeners.iterator();
675 while (listener.hasNext()) {
676 final OnPhaseFinished next = listener.next();
677 if (next.phaseFinished(this, phase)) {
682 if (listeners.isEmpty()) {
683 phaseListeners.removeAll(phase);
684 if (phaseListeners.isEmpty()) {
685 phaseListeners = ImmutableMultimap.of();
691 * Ends declared section of current node.
693 void endDeclared(final ModelProcessingPhase phase) {
694 definition.onDeclarationFinished(this, phase);
698 * Return the context in which this statement was defined.
700 * @return statement definition
702 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
707 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
708 definition.checkNamespaceAllowed(type);
712 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
714 // definition().onNamespaceElementAdded(this, type, key, value);
717 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
718 final OnNamespaceItemAdded listener) {
719 final Object potential = getFromNamespace(type, key);
720 if (potential != null) {
721 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
722 listener.namespaceItemAdded(this, type, key, potential);
726 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
728 void onValueAdded(final Object value) {
729 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
734 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
735 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
736 final OnNamespaceItemAdded listener) {
737 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
738 if (existing.isPresent()) {
739 final Entry<K, V> entry = existing.get();
740 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
741 waitForPhase(entry.getValue(), type, phase, criterion, listener);
745 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
746 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
748 boolean onValueAdded(final K key, final V value) {
749 if (criterion.match(key)) {
750 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
751 waitForPhase(value, type, phase, criterion, listener);
760 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
761 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
762 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
763 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
765 final Entry<K, V> match = optMatch.get();
766 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
769 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
770 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
771 final OnNamespaceItemAdded listener) {
772 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
773 (context, phaseCompleted) -> {
774 selectMatch(type, criterion, listener);
779 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
780 final Class<N> type) {
781 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
782 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
785 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
789 public StatementDefinition getPublicDefinition() {
790 return definition.getPublicView();
794 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
795 return getRoot().getSourceContext().newInferenceAction(phase);
798 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
799 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
803 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
804 * the listener is notified immediately.
806 * @param phase requested completion phase
807 * @param listener listener to invoke
808 * @throws NullPointerException if any of the arguments is null
810 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
811 requireNonNull(phase, "Statement context processing phase cannot be null");
812 requireNonNull(listener, "Statement context phase listener cannot be null");
814 ModelProcessingPhase finishedPhase = completedPhase;
815 while (finishedPhase != null) {
816 if (phase.equals(finishedPhase)) {
817 listener.phaseFinished(this, finishedPhase);
820 finishedPhase = finishedPhase.getPreviousPhase();
822 if (phaseListeners.isEmpty()) {
823 phaseListeners = newMultimap();
826 phaseListeners.put(phase, listener);
830 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
832 * @throws IllegalStateException when the mutation was registered after phase was completed
834 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
835 ModelProcessingPhase finishedPhase = completedPhase;
836 while (finishedPhase != null) {
837 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
838 getStatementSourceReference());
839 finishedPhase = finishedPhase.getPreviousPhase();
842 if (phaseMutation.isEmpty()) {
843 phaseMutation = newMultimap();
845 phaseMutation.put(phase, mutation);
848 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
849 if (!phaseMutation.isEmpty()) {
850 phaseMutation.remove(phase, mutation);
851 cleanupPhaseMutation();
856 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
857 final KT key,final StmtContext<?, ?, ?> stmt) {
858 addContextToNamespace(namespace, key, stmt);
862 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
863 final QNameModule targetModule) {
864 checkEffectiveModelCompleted(this);
866 final StatementSupport<A, D, E> support = definition.support();
867 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
869 case CONTEXT_INDEPENDENT:
870 if (hasEmptySubstatements()) {
871 // This statement is context-independent and has no substatements -- hence it can be freely shared.
872 return Optional.of(this);
874 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
877 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
878 // context, so that we can support building an effective statement without copying
879 // anything -- we will typically end up not being inferred against. In that case,
880 // this slim context should end up dealing with differences at buildContext()
881 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
882 // cannot be shared across instances).
883 return Optional.of(parent.childCopyOf(this, type, targetModule));
885 return Optional.empty();
887 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
889 throw new IllegalStateException("Unhandled policy " + policy);
894 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
895 final QNameModule targetModule) {
896 checkEffectiveModelCompleted(stmt);
897 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
898 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
901 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
902 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
903 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
904 original.getPublicDefinition());
906 final StatementContextBase<X, Y, Z> result;
907 final InferredStatementContext<X, Y, Z> copy;
909 if (implicitParent.isPresent()) {
910 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
911 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
912 original.rawStatementArgument(), original.getStatementArgument(), type);
914 final CopyType childCopyType;
916 case ADDED_BY_AUGMENTATION:
917 childCopyType = CopyType.ORIGINAL;
919 case ADDED_BY_USES_AUGMENTATION:
920 childCopyType = CopyType.ADDED_BY_USES;
925 childCopyType = type;
928 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
929 result.addEffectiveSubstatement(copy);
931 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
934 original.definition.onStatementAdded(copy);
938 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
939 final ModelProcessingPhase phase = stmt.getCompletedPhase();
940 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
941 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
945 public final boolean hasImplicitParentSupport() {
946 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
950 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
951 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
952 original.getPublicDefinition());
953 if (optImplicit.isEmpty()) {
957 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
958 final CopyType type = original.getCopyHistory().getLastOperation();
959 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
960 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
963 result.addEffectiveSubstatement(original.reparent(result));
964 result.setCompletedPhase(original.getCompletedPhase());
968 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
971 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
973 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
975 abstract boolean hasEmptySubstatements();
977 // Dual use method: AbstractResumedStatement does not use 'initialized' and InferredStatementContext ensures
979 // FIXME: 7.0.0: I think this warrants a separate subclasses, as InferredStatementContext wants to manage these
980 // itself. Before we do that, though, we need to analyze size impacts
981 final boolean hasEmptyEffectiveSubstatements() {
982 return effective.isEmpty();
986 * Config statements are not all that common which means we are performing a recursive search towards the root
987 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
988 * for the (usually non-existent) config statement.
991 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
992 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
995 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
996 * {@link #isIgnoringConfig(StatementContextBase)}.
998 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
999 final int fl = flags & SET_CONFIGURATION;
1001 return fl == SET_CONFIGURATION;
1003 if (isIgnoringConfig(parent)) {
1004 // Note: SET_CONFIGURATION has been stored in flags
1008 final boolean isConfig;
1009 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
1010 if (optConfig.isPresent()) {
1011 isConfig = optConfig.orElseThrow();
1013 // Validity check: if parent is config=false this cannot be a config=true
1014 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
1015 "Parent node has config=false, this node must not be specifed as config=true");
1018 // If "config" statement is not specified, the default is the same as the parent's "config" value.
1019 isConfig = parent.isConfiguration();
1022 // Resolved, make sure we cache this return
1023 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
1027 protected abstract boolean isIgnoringConfig();
1030 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
1031 * keep on returning the same result without performing any lookups. Exists only to support
1032 * {@link SubstatementContext#isIgnoringConfig()}.
1035 * Note: use of this method implies that {@link #isConfiguration()} is realized with
1036 * {@link #isConfiguration(StatementContextBase)}.
1038 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
1039 final int fl = flags & SET_IGNORE_CONFIG;
1041 return fl == SET_IGNORE_CONFIG;
1043 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
1044 flags |= SET_IGNORE_CONFIG;
1048 flags |= HAVE_IGNORE_CONFIG;
1052 protected abstract boolean isIgnoringIfFeatures();
1055 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
1056 * keep on returning the same result without performing any lookups. Exists only to support
1057 * {@link SubstatementContext#isIgnoringIfFeatures()}.
1059 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
1060 final int fl = flags & SET_IGNORE_IF_FEATURE;
1062 return fl == SET_IGNORE_IF_FEATURE;
1064 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1065 flags |= SET_IGNORE_IF_FEATURE;
1069 flags |= HAVE_IGNORE_IF_FEATURE;
1073 // Exists only to support {SubstatementContext,InferredStatementContext}.getSchemaPath()
1075 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1076 if (schemaPath == null) {
1077 schemaPath = createSchemaPath(coerceParentContext());
1079 return Optional.ofNullable(schemaPath);
1083 private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
1084 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
1085 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1086 final SchemaPath parentPath = maybeParentPath.get();
1088 if (StmtContextUtils.isUnknownStatement(this)) {
1089 return parentPath.createChild(getPublicDefinition().getStatementName());
1091 final Object argument = getStatementArgument();
1092 if (argument instanceof QName) {
1093 final QName qname = (QName) argument;
1094 if (producesDeclared(UsesStatement.class)) {
1095 return maybeParentPath.orElse(null);
1098 return parentPath.createChild(qname);
1100 if (argument instanceof String) {
1101 // FIXME: This may yield illegal argument exceptions
1102 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
1103 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1104 return parentPath.createChild(qname);
1106 if (argument instanceof SchemaNodeIdentifier
1107 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
1108 || producesDeclared(DeviationStatement.class))) {
1110 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
1113 // FIXME: this does not look right
1114 return maybeParentPath.orElse(null);
1118 public final String toString() {
1119 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1122 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1123 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());