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.Objects;
34 import java.util.Optional;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.common.YangVersion;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
43 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
45 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
46 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
47 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
51 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
52 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
53 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
69 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
70 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
71 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
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<Mutable<?, ?, ?>> 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;
264 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
265 this.completedPhase = completedPhase;
269 public abstract StatementContextBase<?, ?, ?> getParentContext();
272 * Returns the model root for this statement.
274 * @return root context of statement
277 public abstract RootStatementContext<?, ?, ?> getRoot();
280 public final @NonNull Registry getBehaviourRegistry() {
281 return getRoot().getBehaviourRegistryImpl();
285 public final YangVersion getRootVersion() {
286 return getRoot().getRootVersionImpl();
290 public final void setRootVersion(final YangVersion version) {
291 getRoot().setRootVersionImpl(version);
295 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
296 getRoot().addMutableStmtToSealImpl(mutableStatement);
300 public final void addRequiredSource(final SourceIdentifier dependency) {
301 getRoot().addRequiredSourceImpl(dependency);
305 public final void setRootIdentifier(final SourceIdentifier identifier) {
306 getRoot().setRootIdentifierImpl(identifier);
310 public final boolean isEnabledSemanticVersioning() {
311 return getRoot().isEnabledSemanticVersioningImpl();
315 public StatementSource getStatementSource() {
316 return getStatementSourceReference().getStatementSource();
320 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
321 final Class<N> type) {
322 return getLocalNamespace(type);
326 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
327 return getNamespace(type);
331 * Associate a value with a key within a namespace.
333 * @param type Namespace type
336 * @param <K> namespace key type
337 * @param <V> namespace value type
338 * @param <N> namespace type
339 * @param <T> key type
340 * @param <U> value type
341 * @throws NamespaceNotAvailableException when the namespace is not available.
344 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
345 final Class<N> type, final T key, final U value) {
346 addToNamespace(type, key, value);
350 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
353 * Return a value associated with specified key within a namespace.
355 * @param type Namespace type
357 * @param <K> namespace key type
358 * @param <V> namespace value type
359 * @param <N> namespace type
360 * @param <T> key type
361 * @return Value, or null if there is no element
362 * @throws NamespaceNotAvailableException when the namespace is not available.
365 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(final Class<N> type,
367 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
371 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
372 if (effective instanceof ImmutableCollection) {
376 return Collections.unmodifiableCollection(effective);
380 * Remove a set of statements from effective statements.
382 * @param statements statements to be removed
383 * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
384 * It is no longer used in that capacity and slated for removal.
386 // FIXME: 5.0.0: remove this method
387 @Deprecated(forRemoval = true)
388 public void removeStatementsFromEffectiveSubstatements(
389 final Collection<? extends StmtContext<?, ?, ?>> statements) {
390 if (!effective.isEmpty()) {
391 effective.removeAll(statements);
396 private void shrinkEffective() {
397 if (effective.isEmpty()) {
398 effective = ImmutableList.of();
402 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
403 if (effective.isEmpty()) {
407 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
408 while (iterator.hasNext()) {
409 final StmtContext<?, ?, ?> next = iterator.next();
410 if (statementDef.equals(next.getPublicDefinition())) {
419 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
420 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
421 * definition and statement argument match with one of the effective substatements' statement definition
425 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
427 * @param statementDef statement definition of the statement context to remove
428 * @param statementArg statement argument of the statement context to remove
430 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
431 final String statementArg) {
432 if (statementArg == null) {
433 removeStatementFromEffectiveSubstatements(statementDef);
436 if (effective.isEmpty()) {
440 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
441 while (iterator.hasNext()) {
442 final Mutable<?, ?, ?> next = iterator.next();
443 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
451 // YANG example: RPC/action statements always have 'input' and 'output' defined
453 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
454 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
455 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
456 // StatementContextBase subclass.
457 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
458 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
459 support.onStatementAdded(ret);
460 addEffectiveSubstatement(ret);
465 * Adds an effective statement to collection of substatements.
467 * @param substatement substatement
468 * @throws IllegalStateException
469 * if added in declared phase
470 * @throws NullPointerException
471 * if statement parameter is null
473 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
474 beforeAddEffectiveStatement(1);
475 effective.add(substatement);
479 * Adds an effective statement to collection of substatements.
481 * @param statements substatements
482 * @throws IllegalStateException
483 * if added in declared phase
484 * @throws NullPointerException
485 * if statement parameter is null
487 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
488 if (statements.isEmpty()) {
492 statements.forEach(Objects::requireNonNull);
493 beforeAddEffectiveStatement(statements.size());
494 effective.addAll(statements);
497 private void beforeAddEffectiveStatement(final int toAdd) {
498 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
499 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
500 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
501 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
503 if (effective.isEmpty()) {
504 effective = new ArrayList<>(toAdd);
508 // Exists only due to memory optimization
509 final boolean fullyDefined() {
513 // Exists only due to memory optimization, should live in AbstractResumedStatement
514 final void setFullyDefined() {
519 public E buildEffective() {
520 final E existing = effectiveInstance;
521 return existing != null ? existing : (effectiveInstance = definition.getFactory().createEffective(this));
525 * Try to execute current {@link ModelProcessingPhase} of source parsing.
527 * @param phase to be executed (completed)
528 * @return if phase was successfully completed
529 * @throws SourceException when an error occurred in source parsing
531 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
532 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
533 if (completeChildren(phase) && finished) {
534 onPhaseCompleted(phase);
540 private boolean completeChildren(final ModelProcessingPhase phase) {
541 boolean finished = true;
542 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
543 finished &= child.tryToCompletePhase(phase);
545 for (final Mutable<?, ?, ?> child : effective) {
546 if (child instanceof StatementContextBase) {
547 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
553 private boolean runMutations(final ModelProcessingPhase phase) {
554 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
555 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
558 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
559 boolean finished = true;
560 final Iterator<ContextMutation> it = openMutations.iterator();
561 while (it.hasNext()) {
562 final ContextMutation current = it.next();
563 if (current.isFinished()) {
570 if (openMutations.isEmpty()) {
571 phaseMutation.removeAll(phase);
572 if (phaseMutation.isEmpty()) {
573 phaseMutation = ImmutableMultimap.of();
580 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
583 * that was to be completed (finished)
584 * @throws SourceException
585 * when an error occurred in source parsing
587 private void onPhaseCompleted(final ModelProcessingPhase phase) {
588 completedPhase = phase;
590 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
591 if (listeners.isEmpty()) {
595 final Iterator<OnPhaseFinished> listener = listeners.iterator();
596 while (listener.hasNext()) {
597 final OnPhaseFinished next = listener.next();
598 if (next.phaseFinished(this, phase)) {
603 if (listeners.isEmpty()) {
604 phaseListeners.removeAll(phase);
605 if (phaseListeners.isEmpty()) {
606 phaseListeners = ImmutableMultimap.of();
612 * Ends declared section of current node.
614 void endDeclared(final ModelProcessingPhase phase) {
615 definition.onDeclarationFinished(this, phase);
619 * Return the context in which this statement was defined.
621 * @return statement definition
623 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
628 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
629 definition.checkNamespaceAllowed(type);
633 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
635 // definition().onNamespaceElementAdded(this, type, key, value);
638 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
639 final OnNamespaceItemAdded listener) {
640 final Object potential = getFromNamespace(type, key);
641 if (potential != null) {
642 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
643 listener.namespaceItemAdded(this, type, key, potential);
647 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
649 void onValueAdded(final Object value) {
650 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
655 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
656 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
657 final OnNamespaceItemAdded listener) {
658 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
659 if (existing.isPresent()) {
660 final Entry<K, V> entry = existing.get();
661 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
662 waitForPhase(entry.getValue(), type, phase, criterion, listener);
666 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
667 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
669 boolean onValueAdded(final K key, final V value) {
670 if (criterion.match(key)) {
671 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
672 waitForPhase(value, type, phase, criterion, listener);
681 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
682 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
683 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
684 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
686 final Entry<K, V> match = optMatch.get();
687 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
690 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
691 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
692 final OnNamespaceItemAdded listener) {
693 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
694 (context, phaseCompleted) -> {
695 selectMatch(type, criterion, listener);
700 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
701 final Class<N> type) {
702 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
703 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
706 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
710 public StatementDefinition getPublicDefinition() {
711 return definition.getPublicView();
715 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
716 return getRoot().getSourceContext().newInferenceAction(phase);
719 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
720 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
724 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
725 * the listener is notified immediately.
727 * @param phase requested completion phase
728 * @param listener listener to invoke
729 * @throws NullPointerException if any of the arguments is null
731 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
732 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
733 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
735 ModelProcessingPhase finishedPhase = completedPhase;
736 while (finishedPhase != null) {
737 if (phase.equals(finishedPhase)) {
738 listener.phaseFinished(this, finishedPhase);
741 finishedPhase = finishedPhase.getPreviousPhase();
743 if (phaseListeners.isEmpty()) {
744 phaseListeners = newMultimap();
747 phaseListeners.put(phase, listener);
751 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
753 * @throws IllegalStateException
754 * when the mutation was registered after phase was completed
756 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
757 ModelProcessingPhase finishedPhase = completedPhase;
758 while (finishedPhase != null) {
759 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
760 getStatementSourceReference());
761 finishedPhase = finishedPhase.getPreviousPhase();
764 if (phaseMutation.isEmpty()) {
765 phaseMutation = newMultimap();
767 phaseMutation.put(phase, mutation);
771 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
772 final KT key,final StmtContext<?, ?, ?> stmt) {
773 addContextToNamespace(namespace, key, stmt);
777 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
778 final QNameModule targetModule) {
779 checkEffectiveModelCompleted(this);
781 final StatementSupport<A, D, E> support = definition.support();
782 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
784 case CONTEXT_INDEPENDENT:
785 if (hasEmptySubstatements()) {
786 // This statement is context-independent and has no substatements -- hence it can be freely shared.
787 return Optional.of(this);
789 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
792 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
793 // context, so that we can support building an effective statement without copying
794 // anything -- we will typically end up not being inferred against. In that case,
795 // this slim context should end up dealing with differences at buildContext()
796 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
797 // cannot be shared across instances).
798 return Optional.of(parent.childCopyOf(this, type, targetModule));
800 return Optional.empty();
802 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
804 throw new IllegalStateException("Unhandled policy " + policy);
809 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
810 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
811 checkEffectiveModelCompleted(stmt);
812 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
813 return childCopyOf((StatementContextBase<X, Y, Z>)stmt, type, targetModule);
816 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
817 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
818 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
819 original.getPublicDefinition());
821 final StatementContextBase<X, Y, Z> result;
822 final InferredStatementContext<X, Y, Z> copy;
824 if (implicitParent.isPresent()) {
825 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
826 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
827 original.rawStatementArgument(), original.getStatementArgument(), type);
829 final CopyType childCopyType;
831 case ADDED_BY_AUGMENTATION:
832 childCopyType = CopyType.ORIGINAL;
834 case ADDED_BY_USES_AUGMENTATION:
835 childCopyType = CopyType.ADDED_BY_USES;
840 childCopyType = type;
843 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
844 result.addEffectiveSubstatement(copy);
846 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
849 original.definition.onStatementAdded(copy);
853 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
854 final ModelProcessingPhase phase = stmt.getCompletedPhase();
855 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
856 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
860 public final boolean hasImplicitParentSupport() {
861 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
865 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
866 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
867 original.getPublicDefinition());
868 if (optImplicit.isEmpty()) {
872 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
873 final CopyType type = original.getCopyHistory().getLastOperation();
874 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
875 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
878 result.addEffectiveSubstatement(original.reparent(result));
879 result.setCompletedPhase(original.getCompletedPhase());
883 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
886 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
888 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
890 abstract boolean hasEmptySubstatements();
892 final boolean hasEmptyEffectiveSubstatements() {
893 return effective.isEmpty();
897 * Config statements are not all that common which means we are performing a recursive search towards the root
898 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
899 * for the (usually non-existent) config statement.
902 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
903 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
906 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
907 * {@link #isIgnoringConfig(StatementContextBase)}.
909 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
910 final int fl = flags & SET_CONFIGURATION;
912 return fl == SET_CONFIGURATION;
914 if (isIgnoringConfig(parent)) {
915 // Note: SET_CONFIGURATION has been stored in flags
919 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
920 ConfigStatement.class);
921 final boolean isConfig;
922 if (configStatement != null) {
923 isConfig = configStatement.coerceStatementArgument();
925 // Validity check: if parent is config=false this cannot be a config=true
926 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
927 "Parent node has config=false, this node must not be specifed as config=true");
930 // If "config" statement is not specified, the default is the same as the parent's "config" value.
931 isConfig = parent.isConfiguration();
934 // Resolved, make sure we cache this return
935 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
939 protected abstract boolean isIgnoringConfig();
942 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
943 * keep on returning the same result without performing any lookups. Exists only to support
944 * {@link SubstatementContext#isIgnoringConfig()}.
947 * Note: use of this method implies that {@link #isConfiguration()} is realized with
948 * {@link #isConfiguration(StatementContextBase)}.
950 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
951 final int fl = flags & SET_IGNORE_CONFIG;
953 return fl == SET_IGNORE_CONFIG;
955 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
956 flags |= SET_IGNORE_CONFIG;
960 flags |= HAVE_IGNORE_CONFIG;
964 protected abstract boolean isIgnoringIfFeatures();
967 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
968 * keep on returning the same result without performing any lookups. Exists only to support
969 * {@link SubstatementContext#isIgnoringIfFeatures()}.
971 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
972 final int fl = flags & SET_IGNORE_IF_FEATURE;
974 return fl == SET_IGNORE_IF_FEATURE;
976 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
977 flags |= SET_IGNORE_IF_FEATURE;
981 flags |= HAVE_IGNORE_IF_FEATURE;
985 // Exists only to support SubstatementContext/InferredStatementContext
986 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
987 SchemaPath local = schemaPath;
989 synchronized (this) {
992 local = createSchemaPath(coerceParentContext());
998 return Optional.ofNullable(local);
1001 private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
1002 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
1003 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1004 final SchemaPath parentPath = maybeParentPath.get();
1006 if (StmtContextUtils.isUnknownStatement(this)) {
1007 return parentPath.createChild(getPublicDefinition().getStatementName());
1009 final Object argument = getStatementArgument();
1010 if (argument instanceof QName) {
1011 final QName qname = (QName) argument;
1012 if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
1013 return maybeParentPath.orElse(null);
1016 return parentPath.createChild(qname);
1018 if (argument instanceof String) {
1019 // FIXME: This may yield illegal argument exceptions
1020 final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
1021 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1022 return parentPath.createChild(qname);
1024 if (argument instanceof SchemaNodeIdentifier
1025 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
1026 || StmtContextUtils.producesDeclared(this, RefineStatement.class)
1027 || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
1029 return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
1032 // FIXME: this does not look right
1033 return maybeParentPath.orElse(null);
1037 public final String toString() {
1038 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1041 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1042 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());