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.base.MoreObjects;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import com.google.common.collect.ImmutableCollection;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMultimap;
22 import com.google.common.collect.Multimap;
23 import com.google.common.collect.Multimaps;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.EnumMap;
28 import java.util.EventListener;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.Optional;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.common.YangVersion;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
44 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
45 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
46 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
51 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
52 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
69 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
70 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
73 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
75 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
80 * Core reactor statement implementation of {@link Mutable}.
82 * @param <A> Argument type
83 * @param <D> Declared Statement representation
84 * @param <E> Effective Statement representation
86 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
87 extends NamespaceStorageSupport implements Mutable<A, D, E> {
89 * Event listener when an item is added to model namespace.
91 interface OnNamespaceItemAdded extends EventListener {
93 * Invoked whenever a new item is added to a namespace.
95 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
99 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
101 interface OnPhaseFinished extends EventListener {
103 * Invoked whenever a processing phase has finished.
105 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
109 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
111 interface ContextMutation {
113 boolean isFinished();
116 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
118 // Flag bit assignments
119 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
120 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
121 private static final int IS_IGNORE_IF_FEATURE = 0x04;
122 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
123 // Note: these four are related
124 private static final int IS_IGNORE_CONFIG = 0x10;
125 private static final int HAVE_IGNORE_CONFIG = 0x20;
126 private static final int IS_CONFIGURATION = 0x40;
127 private static final int HAVE_CONFIGURATION = 0x80;
129 // Have-and-set flag constants, also used as masks
130 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
131 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
132 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
133 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
134 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
136 private final CopyHistory copyHistory;
137 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
138 // operations, hence we want to keep it close by.
139 private final @NonNull StatementDefinitionContext<A, D, E> definition;
141 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
142 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
143 private List<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
144 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
146 private @Nullable ModelProcessingPhase completedPhase;
147 private @Nullable E effectiveInstance;
149 // Master flag controlling whether this context can yield an effective statement
150 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
151 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
152 private boolean isSupportedToBuildEffective = true;
154 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
155 private boolean fullyDefined;
157 // Flag for InferredStatementContext. This is hiding in the alignment shadow created by above boolean.
158 private boolean substatementsInitialized;
160 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
161 // hence improve memory layout.
164 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
165 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
166 private volatile SchemaPath schemaPath;
168 // Copy constructor used by subclasses to implement reparent()
169 StatementContextBase(final StatementContextBase<A, D, E> original) {
170 this.copyHistory = original.copyHistory;
171 this.definition = original.definition;
173 this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
174 this.fullyDefined = original.fullyDefined;
175 this.completedPhase = original.completedPhase;
176 this.flags = original.flags;
179 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
180 this.definition = requireNonNull(def);
181 this.copyHistory = CopyHistory.original();
184 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
185 this.definition = requireNonNull(def);
186 this.copyHistory = requireNonNull(copyHistory);
190 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
191 return effectOfStatement;
195 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
196 if (effectOfStatement.isEmpty()) {
197 effectOfStatement = new ArrayList<>(1);
199 effectOfStatement.add(ctx);
203 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
204 if (ctxs.isEmpty()) {
208 if (effectOfStatement.isEmpty()) {
209 effectOfStatement = new ArrayList<>(ctxs.size());
211 effectOfStatement.addAll(ctxs);
215 public boolean isSupportedByFeatures() {
216 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
218 return fl == SET_SUPPORTED_BY_FEATURES;
220 if (isIgnoringIfFeatures()) {
221 flags |= SET_SUPPORTED_BY_FEATURES;
226 * If parent is supported, we need to check if-features statements of this context.
228 if (isParentSupportedByFeatures()) {
229 // If the set of supported features has not been provided, all features are supported by default.
230 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
231 SupportedFeatures.SUPPORTED_FEATURES);
232 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
233 flags |= SET_SUPPORTED_BY_FEATURES;
238 // Either parent is not supported or this statement is not supported
239 flags |= HAVE_SUPPORTED_BY_FEATURES;
243 protected abstract boolean isParentSupportedByFeatures();
246 public boolean isSupportedToBuildEffective() {
247 return isSupportedToBuildEffective;
251 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
252 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
256 public CopyHistory getCopyHistory() {
261 public ModelProcessingPhase getCompletedPhase() {
262 return completedPhase;
265 // FIXME: this should be propagated through a correct constructor
267 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
268 this.completedPhase = completedPhase;
272 public abstract StatementContextBase<?, ?, ?> getParentContext();
275 * Returns the model root for this statement.
277 * @return root context of statement
280 public abstract RootStatementContext<?, ?, ?> getRoot();
283 public final @NonNull Registry getBehaviourRegistry() {
284 return getRoot().getBehaviourRegistryImpl();
288 public final YangVersion getRootVersion() {
289 return getRoot().getRootVersionImpl();
293 public final void setRootVersion(final YangVersion version) {
294 getRoot().setRootVersionImpl(version);
298 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
299 getRoot().addMutableStmtToSealImpl(mutableStatement);
303 public final void addRequiredSource(final SourceIdentifier dependency) {
304 getRoot().addRequiredSourceImpl(dependency);
308 public final void setRootIdentifier(final SourceIdentifier identifier) {
309 getRoot().setRootIdentifierImpl(identifier);
313 public final boolean isEnabledSemanticVersioning() {
314 return getRoot().isEnabledSemanticVersioningImpl();
318 public StatementSource getStatementSource() {
319 return getStatementSourceReference().getStatementSource();
323 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
324 final Class<N> type) {
325 return getLocalNamespace(type);
329 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
330 return getNamespace(type);
334 * Associate a value with a key within a namespace.
336 * @param type Namespace type
339 * @param <K> namespace key type
340 * @param <V> namespace value type
341 * @param <N> namespace type
342 * @param <T> key type
343 * @param <U> value type
344 * @throws NamespaceNotAvailableException when the namespace is not available.
347 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
348 final Class<@NonNull N> type, final T key, final U value) {
349 addToNamespace(type, key, value);
353 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
356 * Return a value associated with specified key within a namespace.
358 * @param type Namespace type
360 * @param <K> namespace key type
361 * @param <V> namespace value type
362 * @param <N> namespace type
363 * @param <T> key type
364 * @return Value, or null if there is no element
365 * @throws NamespaceNotAvailableException when the namespace is not available.
368 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(
369 final Class<@NonNull N> type, final T key) {
370 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
374 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
375 if (effective instanceof ImmutableCollection) {
379 return Collections.unmodifiableCollection(effective);
382 private void shrinkEffective() {
383 if (effective.isEmpty()) {
384 effective = ImmutableList.of();
388 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
389 if (effective.isEmpty()) {
393 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
394 while (iterator.hasNext()) {
395 final StmtContext<?, ?, ?> next = iterator.next();
396 if (statementDef.equals(next.getPublicDefinition())) {
405 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
406 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
407 * definition and statement argument match with one of the effective substatements' statement definition
411 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
413 * @param statementDef statement definition of the statement context to remove
414 * @param statementArg statement argument of the statement context to remove
416 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
417 final String statementArg) {
418 if (statementArg == null) {
419 removeStatementFromEffectiveSubstatements(statementDef);
422 if (effective.isEmpty()) {
426 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
427 while (iterator.hasNext()) {
428 final Mutable<?, ?, ?> next = iterator.next();
429 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
437 // YANG example: RPC/action statements always have 'input' and 'output' defined
439 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
440 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
441 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
442 // StatementContextBase subclass.
443 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
444 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
445 support.onStatementAdded(ret);
446 addEffectiveSubstatement(ret);
451 * Adds an effective statement to collection of substatements.
453 * @param substatement substatement
454 * @throws IllegalStateException
455 * if added in declared phase
456 * @throws NullPointerException
457 * if statement parameter is null
459 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
460 verifyStatement(substatement);
461 beforeAddEffectiveStatement(1);
463 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
464 final ModelProcessingPhase phase = completedPhase;
466 ensureCompletedPhase(stmt, phase);
472 * Adds an effective statement to collection of substatements.
474 * @param statements substatements
475 * @throws IllegalStateException
476 * if added in declared phase
477 * @throws NullPointerException
478 * if statement parameter is null
480 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
481 if (!statements.isEmpty()) {
482 statements.forEach(StatementContextBase::verifyStatement);
483 beforeAddEffectiveStatement(statements.size());
484 doAddEffectiveSubstatements(statements);
488 // exposed for InferredStatementContext only
489 final void addInitialEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
490 verify(!substatementsInitialized, "Attempted to re-initialized statement {} with {}", this, statements);
491 substatementsInitialized = true;
493 if (!statements.isEmpty()) {
494 statements.forEach(StatementContextBase::verifyStatement);
495 beforeAddEffectiveStatementUnsafe(statements.size());
496 doAddEffectiveSubstatements(statements);
500 private void doAddEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
501 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
502 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
503 final ModelProcessingPhase phase = completedPhase;
505 for (StatementContextBase<?, ?, ?> stmt : casted) {
506 ensureCompletedPhase(stmt, phase);
510 effective.addAll(casted);
513 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
514 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
515 // any statements which did not complete the same phase as the root statement.
516 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
517 final ModelProcessingPhase phase) {
518 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
521 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
522 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
525 private void beforeAddEffectiveStatement(final int toAdd) {
526 // We cannot allow statement to be further mutated
527 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
528 getStatementSourceReference());
529 beforeAddEffectiveStatementUnsafe(toAdd);
532 private void beforeAddEffectiveStatementUnsafe(final int toAdd) {
533 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
534 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
535 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
536 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
538 if (effective.isEmpty()) {
539 effective = new ArrayList<>(toAdd);
543 // These two exists only due to memory optimization, should live in AbstractResumedStatement
544 final boolean fullyDefined() {
548 final void setFullyDefined() {
552 // These two exist only due to memory optimization, should live in InferredStatementContext
553 final boolean substatementsInitialized() {
554 return substatementsInitialized;
557 final void setSubstatementsInitialized() {
558 substatementsInitialized = true;
562 public E buildEffective() {
564 return (existing = effectiveInstance) != null ? existing : loadEffective();
567 private E loadEffective() {
568 return effectiveInstance = definition.getFactory().createEffective(this);
572 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
573 * this method does nothing.
575 * @param phase to be executed (completed)
576 * @return true if phase was successfully completed
577 * @throws SourceException when an error occurred in source parsing
579 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
580 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
583 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
584 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
585 if (completeChildren(phase) && finished) {
586 onPhaseCompleted(phase);
592 private boolean completeChildren(final ModelProcessingPhase phase) {
593 boolean finished = true;
594 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
595 finished &= child.tryToCompletePhase(phase);
597 for (final StatementContextBase<?, ?, ?> child : effective) {
598 finished &= child.tryToCompletePhase(phase);
603 private boolean runMutations(final ModelProcessingPhase phase) {
604 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
605 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
608 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
609 boolean finished = true;
610 final Iterator<ContextMutation> it = openMutations.iterator();
611 while (it.hasNext()) {
612 final ContextMutation current = it.next();
613 if (current.isFinished()) {
620 if (openMutations.isEmpty()) {
621 phaseMutation.removeAll(phase);
622 if (phaseMutation.isEmpty()) {
623 phaseMutation = ImmutableMultimap.of();
630 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
633 * that was to be completed (finished)
634 * @throws SourceException
635 * when an error occurred in source parsing
637 private void onPhaseCompleted(final ModelProcessingPhase phase) {
638 completedPhase = phase;
640 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
641 if (!listeners.isEmpty()) {
642 runPhaseListeners(phase, listeners);
646 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
647 final Iterator<OnPhaseFinished> listener = listeners.iterator();
648 while (listener.hasNext()) {
649 final OnPhaseFinished next = listener.next();
650 if (next.phaseFinished(this, phase)) {
655 if (listeners.isEmpty()) {
656 phaseListeners.removeAll(phase);
657 if (phaseListeners.isEmpty()) {
658 phaseListeners = ImmutableMultimap.of();
664 * Ends declared section of current node.
666 void endDeclared(final ModelProcessingPhase phase) {
667 definition.onDeclarationFinished(this, phase);
671 * Return the context in which this statement was defined.
673 * @return statement definition
675 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
680 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
681 definition.checkNamespaceAllowed(type);
685 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
687 // definition().onNamespaceElementAdded(this, type, key, value);
690 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
691 final OnNamespaceItemAdded listener) {
692 final Object potential = getFromNamespace(type, key);
693 if (potential != null) {
694 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
695 listener.namespaceItemAdded(this, type, key, potential);
699 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
701 void onValueAdded(final Object value) {
702 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
707 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
708 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
709 final OnNamespaceItemAdded listener) {
710 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
711 if (existing.isPresent()) {
712 final Entry<K, V> entry = existing.get();
713 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
714 waitForPhase(entry.getValue(), type, phase, criterion, listener);
718 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
719 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
721 boolean onValueAdded(final K key, final V value) {
722 if (criterion.match(key)) {
723 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
724 waitForPhase(value, type, phase, criterion, listener);
733 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
734 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
735 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
736 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
738 final Entry<K, V> match = optMatch.get();
739 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
742 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
743 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
744 final OnNamespaceItemAdded listener) {
745 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
746 (context, phaseCompleted) -> {
747 selectMatch(type, criterion, listener);
752 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
753 final Class<N> type) {
754 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
755 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
758 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
762 public StatementDefinition getPublicDefinition() {
763 return definition.getPublicView();
767 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
768 return getRoot().getSourceContext().newInferenceAction(phase);
771 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
772 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
776 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
777 * the listener is notified immediately.
779 * @param phase requested completion phase
780 * @param listener listener to invoke
781 * @throws NullPointerException if any of the arguments is null
783 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
784 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
785 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
787 ModelProcessingPhase finishedPhase = completedPhase;
788 while (finishedPhase != null) {
789 if (phase.equals(finishedPhase)) {
790 listener.phaseFinished(this, finishedPhase);
793 finishedPhase = finishedPhase.getPreviousPhase();
795 if (phaseListeners.isEmpty()) {
796 phaseListeners = newMultimap();
799 phaseListeners.put(phase, listener);
803 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
805 * @throws IllegalStateException
806 * when the mutation was registered after phase was completed
808 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
809 ModelProcessingPhase finishedPhase = completedPhase;
810 while (finishedPhase != null) {
811 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
812 getStatementSourceReference());
813 finishedPhase = finishedPhase.getPreviousPhase();
816 if (phaseMutation.isEmpty()) {
817 phaseMutation = newMultimap();
819 phaseMutation.put(phase, mutation);
823 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
824 final KT key,final StmtContext<?, ?, ?> stmt) {
825 addContextToNamespace(namespace, key, stmt);
829 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
830 final QNameModule targetModule) {
831 checkEffectiveModelCompleted(this);
833 final StatementSupport<A, D, E> support = definition.support();
834 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
836 case CONTEXT_INDEPENDENT:
837 if (hasEmptySubstatements()) {
838 // This statement is context-independent and has no substatements -- hence it can be freely shared.
839 return Optional.of(this);
841 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
844 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
845 // context, so that we can support building an effective statement without copying
846 // anything -- we will typically end up not being inferred against. In that case,
847 // this slim context should end up dealing with differences at buildContext()
848 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
849 // cannot be shared across instances).
850 return Optional.of(parent.childCopyOf(this, type, targetModule));
852 return Optional.empty();
854 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
856 throw new IllegalStateException("Unhandled policy " + policy);
861 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
862 final QNameModule targetModule) {
863 checkEffectiveModelCompleted(stmt);
864 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
865 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
868 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
869 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
870 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
871 original.getPublicDefinition());
873 final StatementContextBase<X, Y, Z> result;
874 final InferredStatementContext<X, Y, Z> copy;
876 if (implicitParent.isPresent()) {
877 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
878 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
879 original.rawStatementArgument(), original.getStatementArgument(), type);
881 final CopyType childCopyType;
883 case ADDED_BY_AUGMENTATION:
884 childCopyType = CopyType.ORIGINAL;
886 case ADDED_BY_USES_AUGMENTATION:
887 childCopyType = CopyType.ADDED_BY_USES;
892 childCopyType = type;
895 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
896 result.addEffectiveSubstatement(copy);
898 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
901 original.definition.onStatementAdded(copy);
905 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
906 final ModelProcessingPhase phase = stmt.getCompletedPhase();
907 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
908 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
912 public final boolean hasImplicitParentSupport() {
913 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
917 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
918 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
919 original.getPublicDefinition());
920 if (optImplicit.isEmpty()) {
924 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
925 final CopyType type = original.getCopyHistory().getLastOperation();
926 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
927 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
930 result.addEffectiveSubstatement(original.reparent(result));
931 result.setCompletedPhase(original.getCompletedPhase());
935 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
938 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
940 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
942 abstract boolean hasEmptySubstatements();
944 final boolean hasEmptyEffectiveSubstatements() {
945 return effective.isEmpty();
949 * Config statements are not all that common which means we are performing a recursive search towards the root
950 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
951 * for the (usually non-existent) config statement.
954 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
955 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
958 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
959 * {@link #isIgnoringConfig(StatementContextBase)}.
961 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
962 final int fl = flags & SET_CONFIGURATION;
964 return fl == SET_CONFIGURATION;
966 if (isIgnoringConfig(parent)) {
967 // Note: SET_CONFIGURATION has been stored in flags
971 final boolean isConfig;
972 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
973 if (optConfig.isPresent()) {
974 isConfig = optConfig.orElseThrow();
976 // Validity check: if parent is config=false this cannot be a config=true
977 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
978 "Parent node has config=false, this node must not be specifed as config=true");
981 // If "config" statement is not specified, the default is the same as the parent's "config" value.
982 isConfig = parent.isConfiguration();
985 // Resolved, make sure we cache this return
986 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
990 protected abstract boolean isIgnoringConfig();
993 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
994 * keep on returning the same result without performing any lookups. Exists only to support
995 * {@link SubstatementContext#isIgnoringConfig()}.
998 * Note: use of this method implies that {@link #isConfiguration()} is realized with
999 * {@link #isConfiguration(StatementContextBase)}.
1001 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
1002 final int fl = flags & SET_IGNORE_CONFIG;
1004 return fl == SET_IGNORE_CONFIG;
1006 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
1007 flags |= SET_IGNORE_CONFIG;
1011 flags |= HAVE_IGNORE_CONFIG;
1015 protected abstract boolean isIgnoringIfFeatures();
1018 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
1019 * keep on returning the same result without performing any lookups. Exists only to support
1020 * {@link SubstatementContext#isIgnoringIfFeatures()}.
1022 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
1023 final int fl = flags & SET_IGNORE_IF_FEATURE;
1025 return fl == SET_IGNORE_IF_FEATURE;
1027 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1028 flags |= SET_IGNORE_IF_FEATURE;
1032 flags |= HAVE_IGNORE_IF_FEATURE;
1036 // Exists only to support {SubstatementContext,InferredStatementContext}.getSchemaPath()
1038 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1039 SchemaPath local = schemaPath;
1040 if (local == null) {
1041 synchronized (this) {
1043 if (local == null) {
1044 schemaPath = local = createSchemaPath(coerceParentContext());
1049 return Optional.ofNullable(local);
1053 private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
1054 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
1055 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1056 final SchemaPath parentPath = maybeParentPath.get();
1058 if (StmtContextUtils.isUnknownStatement(this)) {
1059 return parentPath.createChild(getPublicDefinition().getStatementName());
1061 final Object argument = getStatementArgument();
1062 if (argument instanceof QName) {
1063 final QName qname = (QName) argument;
1064 if (producesDeclared(UsesStatement.class)) {
1065 return maybeParentPath.orElse(null);
1068 return parentPath.createChild(qname);
1070 if (argument instanceof String) {
1071 // FIXME: This may yield illegal argument exceptions
1072 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
1073 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1074 return parentPath.createChild(qname);
1076 if (argument instanceof SchemaNodeIdentifier
1077 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
1078 || producesDeclared(DeviationStatement.class))) {
1080 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
1083 // FIXME: this does not look right
1084 return maybeParentPath.orElse(null);
1088 public final String toString() {
1089 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1092 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1093 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());