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.ConfigStatement;
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.StatementSourceReference;
73 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
74 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
75 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
76 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * Core reactor statement implementation of {@link Mutable}.
83 * @param <A> Argument type
84 * @param <D> Declared Statement representation
85 * @param <E> Effective Statement representation
87 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
88 extends NamespaceStorageSupport implements Mutable<A, D, E> {
90 * Event listener when an item is added to model namespace.
92 interface OnNamespaceItemAdded extends EventListener {
94 * Invoked whenever a new item is added to a namespace.
96 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
100 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
102 interface OnPhaseFinished extends EventListener {
104 * Invoked whenever a processing phase has finished.
106 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
110 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
112 interface ContextMutation {
114 boolean isFinished();
117 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
119 // Flag bit assignments
120 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
121 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
122 private static final int IS_IGNORE_IF_FEATURE = 0x04;
123 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
124 // Note: these four are related
125 private static final int IS_IGNORE_CONFIG = 0x10;
126 private static final int HAVE_IGNORE_CONFIG = 0x20;
127 private static final int IS_CONFIGURATION = 0x40;
128 private static final int HAVE_CONFIGURATION = 0x80;
130 // Have-and-set flag constants, also used as masks
131 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
132 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
133 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
134 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
135 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
137 private final CopyHistory copyHistory;
138 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
139 // operations, hence we want to keep it close by.
140 private final @NonNull StatementDefinitionContext<A, D, E> definition;
142 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
143 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
144 private List<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
145 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
147 private @Nullable ModelProcessingPhase completedPhase;
148 private @Nullable E effectiveInstance;
150 // Master flag controlling whether this context can yield an effective statement
151 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
152 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
153 private boolean isSupportedToBuildEffective = true;
155 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
156 private boolean fullyDefined;
158 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
159 // hence improve memory layout.
162 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
163 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
164 private volatile SchemaPath schemaPath;
166 // Copy constructor used by subclasses to implement reparent()
167 StatementContextBase(final StatementContextBase<A, D, E> original) {
168 this.copyHistory = original.copyHistory;
169 this.definition = original.definition;
171 this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
172 this.fullyDefined = original.fullyDefined;
173 this.completedPhase = original.completedPhase;
174 this.flags = original.flags;
177 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
178 this.definition = requireNonNull(def);
179 this.copyHistory = CopyHistory.original();
182 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
183 this.definition = requireNonNull(def);
184 this.copyHistory = requireNonNull(copyHistory);
188 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
189 return effectOfStatement;
193 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
194 if (effectOfStatement.isEmpty()) {
195 effectOfStatement = new ArrayList<>(1);
197 effectOfStatement.add(ctx);
201 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
202 if (ctxs.isEmpty()) {
206 if (effectOfStatement.isEmpty()) {
207 effectOfStatement = new ArrayList<>(ctxs.size());
209 effectOfStatement.addAll(ctxs);
213 public boolean isSupportedByFeatures() {
214 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
216 return fl == SET_SUPPORTED_BY_FEATURES;
218 if (isIgnoringIfFeatures()) {
219 flags |= SET_SUPPORTED_BY_FEATURES;
224 * If parent is supported, we need to check if-features statements of this context.
226 if (isParentSupportedByFeatures()) {
227 // If the set of supported features has not been provided, all features are supported by default.
228 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
229 SupportedFeatures.SUPPORTED_FEATURES);
230 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
231 flags |= SET_SUPPORTED_BY_FEATURES;
236 // Either parent is not supported or this statement is not supported
237 flags |= HAVE_SUPPORTED_BY_FEATURES;
241 protected abstract boolean isParentSupportedByFeatures();
244 public boolean isSupportedToBuildEffective() {
245 return isSupportedToBuildEffective;
249 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
250 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
254 public CopyHistory getCopyHistory() {
259 public ModelProcessingPhase getCompletedPhase() {
260 return completedPhase;
263 // FIXME: this should be propagated through a correct constructor
265 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
266 this.completedPhase = completedPhase;
270 public abstract StatementContextBase<?, ?, ?> getParentContext();
273 * Returns the model root for this statement.
275 * @return root context of statement
278 public abstract RootStatementContext<?, ?, ?> getRoot();
281 public final @NonNull Registry getBehaviourRegistry() {
282 return getRoot().getBehaviourRegistryImpl();
286 public final YangVersion getRootVersion() {
287 return getRoot().getRootVersionImpl();
291 public final void setRootVersion(final YangVersion version) {
292 getRoot().setRootVersionImpl(version);
296 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
297 getRoot().addMutableStmtToSealImpl(mutableStatement);
301 public final void addRequiredSource(final SourceIdentifier dependency) {
302 getRoot().addRequiredSourceImpl(dependency);
306 public final void setRootIdentifier(final SourceIdentifier identifier) {
307 getRoot().setRootIdentifierImpl(identifier);
311 public final boolean isEnabledSemanticVersioning() {
312 return getRoot().isEnabledSemanticVersioningImpl();
316 public StatementSource getStatementSource() {
317 return getStatementSourceReference().getStatementSource();
321 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
322 final Class<N> type) {
323 return getLocalNamespace(type);
327 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
328 return getNamespace(type);
332 * Associate a value with a key within a namespace.
334 * @param type Namespace type
337 * @param <K> namespace key type
338 * @param <V> namespace value type
339 * @param <N> namespace type
340 * @param <T> key type
341 * @param <U> value type
342 * @throws NamespaceNotAvailableException when the namespace is not available.
345 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
346 final Class<@NonNull N> type, final T key, final U value) {
347 addToNamespace(type, key, value);
351 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
354 * Return a value associated with specified key within a namespace.
356 * @param type Namespace type
358 * @param <K> namespace key type
359 * @param <V> namespace value type
360 * @param <N> namespace type
361 * @param <T> key type
362 * @return Value, or null if there is no element
363 * @throws NamespaceNotAvailableException when the namespace is not available.
366 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(
367 final Class<@NonNull N> type, final T key) {
368 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
372 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
373 if (effective instanceof ImmutableCollection) {
377 return Collections.unmodifiableCollection(effective);
380 private void shrinkEffective() {
381 if (effective.isEmpty()) {
382 effective = ImmutableList.of();
386 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
387 if (effective.isEmpty()) {
391 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
392 while (iterator.hasNext()) {
393 final StmtContext<?, ?, ?> next = iterator.next();
394 if (statementDef.equals(next.getPublicDefinition())) {
403 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
404 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
405 * definition and statement argument match with one of the effective substatements' statement definition
409 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
411 * @param statementDef statement definition of the statement context to remove
412 * @param statementArg statement argument of the statement context to remove
414 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
415 final String statementArg) {
416 if (statementArg == null) {
417 removeStatementFromEffectiveSubstatements(statementDef);
420 if (effective.isEmpty()) {
424 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
425 while (iterator.hasNext()) {
426 final Mutable<?, ?, ?> next = iterator.next();
427 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
435 // YANG example: RPC/action statements always have 'input' and 'output' defined
437 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
438 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
439 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
440 // StatementContextBase subclass.
441 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
442 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
443 support.onStatementAdded(ret);
444 addEffectiveSubstatement(ret);
449 * Adds an effective statement to collection of substatements.
451 * @param substatement substatement
452 * @throws IllegalStateException
453 * if added in declared phase
454 * @throws NullPointerException
455 * if statement parameter is null
457 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
458 verifyStatement(substatement);
459 beforeAddEffectiveStatement(1);
461 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
462 final ModelProcessingPhase phase = completedPhase;
464 ensureCompletedPhase(stmt, phase);
470 * Adds an effective statement to collection of substatements.
472 * @param statements substatements
473 * @throws IllegalStateException
474 * if added in declared phase
475 * @throws NullPointerException
476 * if statement parameter is null
478 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
479 if (!statements.isEmpty()) {
480 statements.forEach(StatementContextBase::verifyStatement);
481 beforeAddEffectiveStatement(statements.size());
483 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
484 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
485 final ModelProcessingPhase phase = completedPhase;
487 for (StatementContextBase<?, ?, ?> stmt : casted) {
488 ensureCompletedPhase(stmt, phase);
492 effective.addAll(casted);
496 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
497 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
498 // any statements which did not complete the same phase as the root statement.
499 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
500 final ModelProcessingPhase phase) {
501 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
504 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
505 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
508 private void beforeAddEffectiveStatement(final int toAdd) {
509 // We cannot allow statement to be further mutated
510 final StatementSourceReference ref = getStatementSourceReference();
511 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s", ref);
513 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
514 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
515 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
516 "Effective statement cannot be added in declared phase at: %s", ref);
518 if (effective.isEmpty()) {
519 effective = new ArrayList<>(toAdd);
523 // Exists only due to memory optimization
524 final boolean fullyDefined() {
528 // Exists only due to memory optimization, should live in AbstractResumedStatement
529 final void setFullyDefined() {
534 public E buildEffective() {
536 return (existing = effectiveInstance) != null ? existing : loadEffective();
539 private E loadEffective() {
540 return effectiveInstance = definition.getFactory().createEffective(this);
544 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
545 * this method does nothing.
547 * @param phase to be executed (completed)
548 * @return true if phase was successfully completed
549 * @throws SourceException when an error occurred in source parsing
551 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
552 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
555 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
556 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
557 if (completeChildren(phase) && finished) {
558 onPhaseCompleted(phase);
564 private boolean completeChildren(final ModelProcessingPhase phase) {
565 boolean finished = true;
566 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
567 finished &= child.tryToCompletePhase(phase);
569 for (final StatementContextBase<?, ?, ?> child : effective) {
570 finished &= child.tryToCompletePhase(phase);
575 private boolean runMutations(final ModelProcessingPhase phase) {
576 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
577 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
580 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
581 boolean finished = true;
582 final Iterator<ContextMutation> it = openMutations.iterator();
583 while (it.hasNext()) {
584 final ContextMutation current = it.next();
585 if (current.isFinished()) {
592 if (openMutations.isEmpty()) {
593 phaseMutation.removeAll(phase);
594 if (phaseMutation.isEmpty()) {
595 phaseMutation = ImmutableMultimap.of();
602 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
605 * that was to be completed (finished)
606 * @throws SourceException
607 * when an error occurred in source parsing
609 private void onPhaseCompleted(final ModelProcessingPhase phase) {
610 completedPhase = phase;
612 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
613 if (!listeners.isEmpty()) {
614 runPhaseListeners(phase, listeners);
618 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
619 final Iterator<OnPhaseFinished> listener = listeners.iterator();
620 while (listener.hasNext()) {
621 final OnPhaseFinished next = listener.next();
622 if (next.phaseFinished(this, phase)) {
627 if (listeners.isEmpty()) {
628 phaseListeners.removeAll(phase);
629 if (phaseListeners.isEmpty()) {
630 phaseListeners = ImmutableMultimap.of();
636 * Ends declared section of current node.
638 void endDeclared(final ModelProcessingPhase phase) {
639 definition.onDeclarationFinished(this, phase);
643 * Return the context in which this statement was defined.
645 * @return statement definition
647 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
652 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
653 definition.checkNamespaceAllowed(type);
657 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
659 // definition().onNamespaceElementAdded(this, type, key, value);
662 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
663 final OnNamespaceItemAdded listener) {
664 final Object potential = getFromNamespace(type, key);
665 if (potential != null) {
666 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
667 listener.namespaceItemAdded(this, type, key, potential);
671 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
673 void onValueAdded(final Object value) {
674 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
679 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
680 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
681 final OnNamespaceItemAdded listener) {
682 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
683 if (existing.isPresent()) {
684 final Entry<K, V> entry = existing.get();
685 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
686 waitForPhase(entry.getValue(), type, phase, criterion, listener);
690 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
691 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
693 boolean onValueAdded(final K key, final V value) {
694 if (criterion.match(key)) {
695 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
696 waitForPhase(value, type, phase, criterion, listener);
705 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
706 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
707 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
708 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
710 final Entry<K, V> match = optMatch.get();
711 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
714 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
715 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
716 final OnNamespaceItemAdded listener) {
717 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
718 (context, phaseCompleted) -> {
719 selectMatch(type, criterion, listener);
724 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
725 final Class<N> type) {
726 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
727 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
730 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
734 public StatementDefinition getPublicDefinition() {
735 return definition.getPublicView();
739 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
740 return getRoot().getSourceContext().newInferenceAction(phase);
743 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
744 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
748 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
749 * the listener is notified immediately.
751 * @param phase requested completion phase
752 * @param listener listener to invoke
753 * @throws NullPointerException if any of the arguments is null
755 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
756 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
757 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
759 ModelProcessingPhase finishedPhase = completedPhase;
760 while (finishedPhase != null) {
761 if (phase.equals(finishedPhase)) {
762 listener.phaseFinished(this, finishedPhase);
765 finishedPhase = finishedPhase.getPreviousPhase();
767 if (phaseListeners.isEmpty()) {
768 phaseListeners = newMultimap();
771 phaseListeners.put(phase, listener);
775 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
777 * @throws IllegalStateException
778 * when the mutation was registered after phase was completed
780 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
781 ModelProcessingPhase finishedPhase = completedPhase;
782 while (finishedPhase != null) {
783 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
784 getStatementSourceReference());
785 finishedPhase = finishedPhase.getPreviousPhase();
788 if (phaseMutation.isEmpty()) {
789 phaseMutation = newMultimap();
791 phaseMutation.put(phase, mutation);
795 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
796 final KT key,final StmtContext<?, ?, ?> stmt) {
797 addContextToNamespace(namespace, key, stmt);
801 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
802 final QNameModule targetModule) {
803 checkEffectiveModelCompleted(this);
805 final StatementSupport<A, D, E> support = definition.support();
806 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
808 case CONTEXT_INDEPENDENT:
809 if (hasEmptySubstatements()) {
810 // This statement is context-independent and has no substatements -- hence it can be freely shared.
811 return Optional.of(this);
813 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
816 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
817 // context, so that we can support building an effective statement without copying
818 // anything -- we will typically end up not being inferred against. In that case,
819 // this slim context should end up dealing with differences at buildContext()
820 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
821 // cannot be shared across instances).
822 return Optional.of(parent.childCopyOf(this, type, targetModule));
824 return Optional.empty();
826 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
828 throw new IllegalStateException("Unhandled policy " + policy);
833 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
834 final QNameModule targetModule) {
835 checkEffectiveModelCompleted(stmt);
836 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
837 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
840 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
841 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
842 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
843 original.getPublicDefinition());
845 final StatementContextBase<X, Y, Z> result;
846 final InferredStatementContext<X, Y, Z> copy;
848 if (implicitParent.isPresent()) {
849 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
850 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
851 original.rawStatementArgument(), original.getStatementArgument(), type);
853 final CopyType childCopyType;
855 case ADDED_BY_AUGMENTATION:
856 childCopyType = CopyType.ORIGINAL;
858 case ADDED_BY_USES_AUGMENTATION:
859 childCopyType = CopyType.ADDED_BY_USES;
864 childCopyType = type;
867 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
868 result.addEffectiveSubstatement(copy);
870 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
873 original.definition.onStatementAdded(copy);
877 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
878 final ModelProcessingPhase phase = stmt.getCompletedPhase();
879 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
880 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
884 public final boolean hasImplicitParentSupport() {
885 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
889 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
890 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
891 original.getPublicDefinition());
892 if (optImplicit.isEmpty()) {
896 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
897 final CopyType type = original.getCopyHistory().getLastOperation();
898 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
899 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
902 result.addEffectiveSubstatement(original.reparent(result));
903 result.setCompletedPhase(original.getCompletedPhase());
907 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
910 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
912 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
914 abstract boolean hasEmptySubstatements();
916 final boolean hasEmptyEffectiveSubstatements() {
917 return effective.isEmpty();
921 * Config statements are not all that common which means we are performing a recursive search towards the root
922 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
923 * for the (usually non-existent) config statement.
926 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
927 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
930 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
931 * {@link #isIgnoringConfig(StatementContextBase)}.
933 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
934 final int fl = flags & SET_CONFIGURATION;
936 return fl == SET_CONFIGURATION;
938 if (isIgnoringConfig(parent)) {
939 // Note: SET_CONFIGURATION has been stored in flags
943 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
944 ConfigStatement.class);
945 final boolean isConfig;
946 if (configStatement != null) {
947 isConfig = configStatement.coerceStatementArgument();
949 // Validity check: if parent is config=false this cannot be a config=true
950 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
951 "Parent node has config=false, this node must not be specifed as config=true");
954 // If "config" statement is not specified, the default is the same as the parent's "config" value.
955 isConfig = parent.isConfiguration();
958 // Resolved, make sure we cache this return
959 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
963 protected abstract boolean isIgnoringConfig();
966 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
967 * keep on returning the same result without performing any lookups. Exists only to support
968 * {@link SubstatementContext#isIgnoringConfig()}.
971 * Note: use of this method implies that {@link #isConfiguration()} is realized with
972 * {@link #isConfiguration(StatementContextBase)}.
974 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
975 final int fl = flags & SET_IGNORE_CONFIG;
977 return fl == SET_IGNORE_CONFIG;
979 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
980 flags |= SET_IGNORE_CONFIG;
984 flags |= HAVE_IGNORE_CONFIG;
988 protected abstract boolean isIgnoringIfFeatures();
991 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
992 * keep on returning the same result without performing any lookups. Exists only to support
993 * {@link SubstatementContext#isIgnoringIfFeatures()}.
995 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
996 final int fl = flags & SET_IGNORE_IF_FEATURE;
998 return fl == SET_IGNORE_IF_FEATURE;
1000 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1001 flags |= SET_IGNORE_IF_FEATURE;
1005 flags |= HAVE_IGNORE_IF_FEATURE;
1009 // Exists only to support {SubstatementContext,InferredStatementContext}.getSchemaPath()
1011 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1012 SchemaPath local = schemaPath;
1013 if (local == null) {
1014 synchronized (this) {
1016 if (local == null) {
1017 schemaPath = local = createSchemaPath(coerceParentContext());
1022 return Optional.ofNullable(local);
1026 private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
1027 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
1028 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1029 final SchemaPath parentPath = maybeParentPath.get();
1031 if (StmtContextUtils.isUnknownStatement(this)) {
1032 return parentPath.createChild(getPublicDefinition().getStatementName());
1034 final Object argument = getStatementArgument();
1035 if (argument instanceof QName) {
1036 final QName qname = (QName) argument;
1037 if (producesDeclared(UsesStatement.class)) {
1038 return maybeParentPath.orElse(null);
1041 return parentPath.createChild(qname);
1043 if (argument instanceof String) {
1044 // FIXME: This may yield illegal argument exceptions
1045 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
1046 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1047 return parentPath.createChild(qname);
1049 if (argument instanceof SchemaNodeIdentifier
1050 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
1051 || producesDeclared(DeviationStatement.class))) {
1053 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
1056 // FIXME: this does not look right
1057 return maybeParentPath.orElse(null);
1061 public final String toString() {
1062 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1065 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1066 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());