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 java.util.stream.Stream;
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.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.StmtContextUtils;
69 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
70 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
73 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * Core reactor statement implementation of {@link Mutable}.
81 * @param <A> Argument type
82 * @param <D> Declared Statement representation
83 * @param <E> Effective Statement representation
85 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
86 extends ReactorStmtCtx<A, D, E> {
88 * Event listener when an item is added to model namespace.
90 interface OnNamespaceItemAdded extends EventListener {
92 * Invoked whenever a new item is added to a namespace.
94 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
98 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
100 interface OnPhaseFinished extends EventListener {
102 * Invoked whenever a processing phase has finished.
104 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
108 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
110 interface ContextMutation {
112 boolean isFinished();
115 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
117 // Flag bit assignments
118 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
119 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
120 private static final int IS_IGNORE_IF_FEATURE = 0x04;
121 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
122 // Note: these four are related
123 private static final int IS_IGNORE_CONFIG = 0x10;
124 private static final int HAVE_IGNORE_CONFIG = 0x20;
125 private static final int IS_CONFIGURATION = 0x40;
126 private static final int HAVE_CONFIGURATION = 0x80;
128 // Have-and-set flag constants, also used as masks
129 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
130 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
131 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
132 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
133 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
135 private final CopyHistory copyHistory;
136 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
137 // operations, hence we want to keep it close by.
138 private final @NonNull StatementDefinitionContext<A, D, E> definition;
140 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
141 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
143 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
145 private @Nullable ModelProcessingPhase completedPhase;
146 private @Nullable E effectiveInstance;
148 // Master flag controlling whether this context can yield an effective statement
149 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
150 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
151 private boolean isSupportedToBuildEffective = true;
153 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
154 private boolean fullyDefined;
156 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
157 // hence improve memory layout.
160 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
161 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
162 private volatile SchemaPath schemaPath;
164 // Copy constructor used by subclasses to implement reparent()
165 StatementContextBase(final StatementContextBase<A, D, E> original) {
166 this.copyHistory = original.copyHistory;
167 this.definition = original.definition;
169 this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
170 this.fullyDefined = original.fullyDefined;
171 this.completedPhase = original.completedPhase;
172 this.flags = original.flags;
175 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
176 this.definition = requireNonNull(def);
177 this.copyHistory = CopyHistory.original();
180 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
181 this.definition = requireNonNull(def);
182 this.copyHistory = requireNonNull(copyHistory);
186 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
187 return effectOfStatement;
191 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
192 if (effectOfStatement.isEmpty()) {
193 effectOfStatement = new ArrayList<>(1);
195 effectOfStatement.add(ctx);
199 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
200 if (ctxs.isEmpty()) {
204 if (effectOfStatement.isEmpty()) {
205 effectOfStatement = new ArrayList<>(ctxs.size());
207 effectOfStatement.addAll(ctxs);
211 public boolean isSupportedByFeatures() {
212 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
214 return fl == SET_SUPPORTED_BY_FEATURES;
216 if (isIgnoringIfFeatures()) {
217 flags |= SET_SUPPORTED_BY_FEATURES;
222 * If parent is supported, we need to check if-features statements of this context.
224 if (isParentSupportedByFeatures()) {
225 // If the set of supported features has not been provided, all features are supported by default.
226 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
227 SupportedFeatures.SUPPORTED_FEATURES);
228 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
229 flags |= SET_SUPPORTED_BY_FEATURES;
234 // Either parent is not supported or this statement is not supported
235 flags |= HAVE_SUPPORTED_BY_FEATURES;
239 protected abstract boolean isParentSupportedByFeatures();
242 public boolean isSupportedToBuildEffective() {
243 return isSupportedToBuildEffective;
247 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
248 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
252 public CopyHistory getCopyHistory() {
257 public ModelProcessingPhase getCompletedPhase() {
258 return completedPhase;
261 // FIXME: this should be propagated through a correct constructor
263 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
264 this.completedPhase = completedPhase;
268 * Returns the model root for this statement.
270 * @return root context of statement
273 public abstract RootStatementContext<?, ?, ?> getRoot();
276 public final @NonNull Registry getBehaviourRegistry() {
277 return getRoot().getBehaviourRegistryImpl();
281 public final YangVersion getRootVersion() {
282 return getRoot().getRootVersionImpl();
286 public final void setRootVersion(final YangVersion version) {
287 getRoot().setRootVersionImpl(version);
291 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
292 getRoot().addMutableStmtToSealImpl(mutableStatement);
296 public final void addRequiredSource(final SourceIdentifier dependency) {
297 getRoot().addRequiredSourceImpl(dependency);
301 public final void setRootIdentifier(final SourceIdentifier identifier) {
302 getRoot().setRootIdentifierImpl(identifier);
306 public final boolean isEnabledSemanticVersioning() {
307 return getRoot().isEnabledSemanticVersioningImpl();
311 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
312 final Class<N> type) {
313 return getLocalNamespace(type);
317 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
318 return getNamespace(type);
322 * Associate a value with a key within a namespace.
324 * @param type Namespace type
327 * @param <K> namespace key type
328 * @param <V> namespace value type
329 * @param <N> namespace type
330 * @param <T> key type
331 * @param <U> value type
332 * @throws NamespaceNotAvailableException when the namespace is not available.
335 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
336 final Class<@NonNull N> type, final T key, final U value) {
337 addToNamespace(type, key, value);
341 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
344 * Return a value associated with specified key within a namespace.
346 * @param type Namespace type
348 * @param <K> namespace key type
349 * @param <V> namespace value type
350 * @param <N> namespace type
351 * @param <T> key type
352 * @return Value, or null if there is no element
353 * @throws NamespaceNotAvailableException when the namespace is not available.
356 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(
357 final Class<@NonNull N> type, final T key) {
358 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
361 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
362 final List<StatementContextBase<?, ?, ?>> effective) {
363 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
366 private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
367 final List<StatementContextBase<?, ?, ?>> effective) {
368 return effective.isEmpty() ? ImmutableList.of() : effective;
371 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
373 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
374 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef) {
375 if (effective.isEmpty()) {
379 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
380 while (iterator.hasNext()) {
381 final StmtContext<?, ?, ?> next = iterator.next();
382 if (statementDef.equals(next.publicDefinition())) {
387 return shrinkEffective(effective);
391 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
392 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
393 * definition and statement argument match with one of the effective substatements' statement definition
397 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
399 * @param statementDef statement definition of the statement context to remove
400 * @param statementArg statement argument of the statement context to remove
402 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
403 String statementArg);
405 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
406 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef,
407 final String statementArg) {
408 if (statementArg == null) {
409 return removeStatementFromEffectiveSubstatements(effective, statementDef);
412 if (effective.isEmpty()) {
416 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
417 while (iterator.hasNext()) {
418 final Mutable<?, ?, ?> next = iterator.next();
419 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
424 return shrinkEffective(effective);
427 // YANG example: RPC/action statements always have 'input' and 'output' defined
429 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
430 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
431 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
432 // StatementContextBase subclass.
433 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
434 ImplicitSubstatement.of(sourceReference()), rawArg);
435 support.onStatementAdded(ret);
436 addEffectiveSubstatement(ret);
441 * Adds an effective statement to collection of substatements.
443 * @param substatement substatement
444 * @throws IllegalStateException if added in declared phase
445 * @throws NullPointerException if statement parameter is null
447 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
449 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
450 final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
451 verifyStatement(substatement);
453 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
454 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
455 final ModelProcessingPhase phase = completedPhase;
457 ensureCompletedPhase(stmt, phase);
464 * Adds an effective statement to collection of substatements.
466 * @param statements substatements
467 * @throws IllegalStateException
468 * if added in declared phase
469 * @throws NullPointerException
470 * if statement parameter is null
472 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
473 if (!statements.isEmpty()) {
474 statements.forEach(StatementContextBase::verifyStatement);
475 addEffectiveSubstatementsImpl(statements);
479 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
481 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
482 final List<StatementContextBase<?, ?, ?>> effective,
483 final Collection<? extends Mutable<?, ?, ?>> statements) {
484 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
485 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
486 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
487 final ModelProcessingPhase phase = completedPhase;
489 for (StatementContextBase<?, ?, ?> stmt : casted) {
490 ensureCompletedPhase(stmt, phase);
494 resized.addAll(casted);
498 abstract Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete();
500 // exposed for InferredStatementContext only
501 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
502 verifyStatement(stmt);
503 final ModelProcessingPhase phase = completedPhase;
505 ensureCompletedPhase((StatementContextBase<?, ?, ?>) stmt, phase);
509 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
510 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
511 // any statements which did not complete the same phase as the root statement.
512 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
513 final ModelProcessingPhase phase) {
514 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
517 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
518 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
521 private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
522 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
523 // We cannot allow statement to be further mutated
524 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
526 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
529 final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
530 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
531 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
532 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
533 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
534 "Effective statement cannot be added in declared phase at: %s", sourceReference());
536 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
539 // These two exists only due to memory optimization, should live in AbstractResumedStatement
540 final boolean fullyDefined() {
544 final void setFullyDefined() {
549 public E buildEffective() {
551 return (existing = effectiveInstance) != null ? existing : loadEffective();
554 private E loadEffective() {
555 // Creating an effective statement does not strictly require a declared instance -- there are statements like
556 // 'input', which are implicitly defined.
557 // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
558 // we attempt to create effective statement:
561 final E ret = effectiveInstance = createEffective();
562 // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
564 releaseImplicitRef();
568 // Exposed for ReplicaStatementContext
569 E createEffective() {
570 return definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this), streamDeclared(),
574 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
576 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
579 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
580 * this method does nothing.
582 * @param phase to be executed (completed)
583 * @return true if phase was successfully completed
584 * @throws SourceException when an error occurred in source parsing
586 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
587 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
590 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
591 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
592 if (completeChildren(phase) && finished) {
593 onPhaseCompleted(phase);
599 private boolean completeChildren(final ModelProcessingPhase phase) {
600 boolean finished = true;
601 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
602 finished &= child.tryToCompletePhase(phase);
604 for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
605 finished &= child.tryToCompletePhase(phase);
610 private boolean runMutations(final ModelProcessingPhase phase) {
611 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
612 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
615 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
616 boolean finished = true;
617 final Iterator<ContextMutation> it = openMutations.iterator();
618 while (it.hasNext()) {
619 final ContextMutation current = it.next();
620 if (current.isFinished()) {
627 if (openMutations.isEmpty()) {
628 phaseMutation.removeAll(phase);
629 cleanupPhaseMutation();
634 private void cleanupPhaseMutation() {
635 if (phaseMutation.isEmpty()) {
636 phaseMutation = ImmutableMultimap.of();
641 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
644 * that was to be completed (finished)
645 * @throws SourceException
646 * when an error occurred in source parsing
648 private void onPhaseCompleted(final ModelProcessingPhase phase) {
649 completedPhase = phase;
651 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
652 if (!listeners.isEmpty()) {
653 runPhaseListeners(phase, listeners);
657 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
658 final Iterator<OnPhaseFinished> listener = listeners.iterator();
659 while (listener.hasNext()) {
660 final OnPhaseFinished next = listener.next();
661 if (next.phaseFinished(this, phase)) {
666 if (listeners.isEmpty()) {
667 phaseListeners.removeAll(phase);
668 if (phaseListeners.isEmpty()) {
669 phaseListeners = ImmutableMultimap.of();
675 * Ends declared section of current node.
677 void endDeclared(final ModelProcessingPhase phase) {
678 definition.onDeclarationFinished(this, phase);
682 * Return the context in which this statement was defined.
684 * @return statement definition
686 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
691 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
692 definition.checkNamespaceAllowed(type);
696 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
698 // definition().onNamespaceElementAdded(this, type, key, value);
701 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
702 final OnNamespaceItemAdded listener) {
703 final Object potential = getFromNamespace(type, key);
704 if (potential != null) {
705 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
706 listener.namespaceItemAdded(this, type, key, potential);
710 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
712 void onValueAdded(final Object value) {
713 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
718 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
719 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
720 final OnNamespaceItemAdded listener) {
721 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
722 if (existing.isPresent()) {
723 final Entry<K, V> entry = existing.get();
724 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
725 waitForPhase(entry.getValue(), type, phase, criterion, listener);
729 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
730 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
732 boolean onValueAdded(final K key, final V value) {
733 if (criterion.match(key)) {
734 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
735 waitForPhase(value, type, phase, criterion, listener);
744 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
745 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
746 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
747 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
749 final Entry<K, V> match = optMatch.get();
750 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
753 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
754 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
755 final OnNamespaceItemAdded listener) {
756 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
757 (context, phaseCompleted) -> {
758 selectMatch(type, criterion, listener);
763 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
764 final Class<N> type) {
765 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
766 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
769 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
773 public final StatementDefinition publicDefinition() {
774 return definition.getPublicView();
778 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
779 return getRoot().getSourceContext().newInferenceAction(phase);
782 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
783 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
787 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
788 * the listener is notified immediately.
790 * @param phase requested completion phase
791 * @param listener listener to invoke
792 * @throws NullPointerException if any of the arguments is null
794 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
795 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
796 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
798 ModelProcessingPhase finishedPhase = completedPhase;
799 while (finishedPhase != null) {
800 if (phase.equals(finishedPhase)) {
801 listener.phaseFinished(this, finishedPhase);
804 finishedPhase = finishedPhase.getPreviousPhase();
806 if (phaseListeners.isEmpty()) {
807 phaseListeners = newMultimap();
810 phaseListeners.put(phase, listener);
814 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
816 * @throws IllegalStateException when the mutation was registered after phase was completed
818 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
819 ModelProcessingPhase finishedPhase = completedPhase;
820 while (finishedPhase != null) {
821 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
823 finishedPhase = finishedPhase.getPreviousPhase();
826 if (phaseMutation.isEmpty()) {
827 phaseMutation = newMultimap();
829 phaseMutation.put(phase, mutation);
832 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
833 if (!phaseMutation.isEmpty()) {
834 phaseMutation.remove(phase, mutation);
835 cleanupPhaseMutation();
840 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
841 final KT key,final StmtContext<?, ?, ?> stmt) {
842 addContextToNamespace(namespace, key, stmt);
846 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
847 final QNameModule targetModule) {
848 checkEffectiveModelCompleted(this);
850 final StatementSupport<A, D, E> support = definition.support();
851 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
853 case CONTEXT_INDEPENDENT:
854 if (hasEmptySubstatements()) {
855 // This statement is context-independent and has no substatements -- hence it can be freely shared.
856 return Optional.of(replicaAsChildOf(parent));
858 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
861 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
862 // context, so that we can support building an effective statement without copying
863 // anything -- we will typically end up not being inferred against. In that case,
864 // this slim context should end up dealing with differences at buildContext()
865 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
866 // cannot be shared across instances).
867 return Optional.of(parent.childCopyOf(this, type, targetModule));
869 return Optional.empty();
871 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
873 throw new IllegalStateException("Unhandled policy " + policy);
878 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
879 final QNameModule targetModule) {
880 checkEffectiveModelCompleted(stmt);
881 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
882 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
885 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
886 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
887 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
888 original.publicDefinition());
890 final StatementContextBase<X, Y, Z> result;
891 final InferredStatementContext<X, Y, Z> copy;
893 if (implicitParent.isPresent()) {
894 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
895 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
896 original.argument(), type);
898 final CopyType childCopyType;
900 case ADDED_BY_AUGMENTATION:
901 childCopyType = CopyType.ORIGINAL;
903 case ADDED_BY_USES_AUGMENTATION:
904 childCopyType = CopyType.ADDED_BY_USES;
909 childCopyType = type;
912 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
913 result.addEffectiveSubstatement(copy);
915 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
918 original.definition.onStatementAdded(copy);
923 public final StatementContextBase<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
924 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
925 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
928 final @NonNull StatementContextBase<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
929 return new ReplicaStatementContext<>(stmt, this);
932 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
933 final ModelProcessingPhase phase = stmt.getCompletedPhase();
934 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
935 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
939 public final boolean hasImplicitParentSupport() {
940 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
944 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
945 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
946 original.publicDefinition());
947 if (optImplicit.isEmpty()) {
951 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
952 final CopyType type = original.getCopyHistory().getLastOperation();
953 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
954 original.sourceReference(), original.rawArgument(), original.argument(), type);
956 result.addEffectiveSubstatement(original.reparent(result));
957 result.setCompletedPhase(original.getCompletedPhase());
961 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
964 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
966 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
968 abstract boolean hasEmptySubstatements();
971 final boolean noImplictRef() {
972 return effectiveInstance != null || !isSupportedToBuildEffective();
976 * Config statements are not all that common which means we are performing a recursive search towards the root
977 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
978 * for the (usually non-existent) config statement.
981 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
982 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
985 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
986 * {@link #isIgnoringConfig(StatementContextBase)}.
988 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
989 final int fl = flags & SET_CONFIGURATION;
991 return fl == SET_CONFIGURATION;
993 if (isIgnoringConfig(parent)) {
994 // Note: SET_CONFIGURATION has been stored in flags
998 final boolean isConfig;
999 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
1000 if (optConfig.isPresent()) {
1001 isConfig = optConfig.orElseThrow();
1003 // Validity check: if parent is config=false this cannot be a config=true
1004 InferenceException.throwIf(!parent.isConfiguration(), sourceReference(),
1005 "Parent node has config=false, this node must not be specifed as config=true");
1008 // If "config" statement is not specified, the default is the same as the parent's "config" value.
1009 isConfig = parent.isConfiguration();
1012 // Resolved, make sure we cache this return
1013 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
1017 protected abstract boolean isIgnoringConfig();
1020 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
1021 * keep on returning the same result without performing any lookups. Exists only to support
1022 * {@link SubstatementContext#isIgnoringConfig()}.
1025 * Note: use of this method implies that {@link #isConfiguration()} is realized with
1026 * {@link #isConfiguration(StatementContextBase)}.
1028 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
1029 final int fl = flags & SET_IGNORE_CONFIG;
1031 return fl == SET_IGNORE_CONFIG;
1033 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
1034 flags |= SET_IGNORE_CONFIG;
1038 flags |= HAVE_IGNORE_CONFIG;
1042 protected abstract boolean isIgnoringIfFeatures();
1045 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
1046 * keep on returning the same result without performing any lookups. Exists only to support
1047 * {@link SubstatementContext#isIgnoringIfFeatures()}.
1049 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
1050 final int fl = flags & SET_IGNORE_IF_FEATURE;
1052 return fl == SET_IGNORE_IF_FEATURE;
1054 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1055 flags |= SET_IGNORE_IF_FEATURE;
1059 flags |= HAVE_IGNORE_IF_FEATURE;
1063 abstract @NonNull Optional<SchemaPath> schemaPath();
1065 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
1067 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1068 SchemaPath local = schemaPath;
1069 if (local == null) {
1070 synchronized (this) {
1072 if (local == null) {
1073 schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
1078 return Optional.ofNullable(local);
1082 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
1083 final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
1084 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1085 final SchemaPath parentPath = maybeParentPath.get();
1087 if (StmtContextUtils.isUnknownStatement(this)) {
1088 return parentPath.createChild(publicDefinition().getStatementName());
1090 final Object argument = argument();
1091 if (argument instanceof QName) {
1092 final QName qname = (QName) argument;
1093 if (producesDeclared(UsesStatement.class)) {
1094 return maybeParentPath.orElse(null);
1097 return parentPath.createChild(qname);
1099 if (argument instanceof String) {
1100 // FIXME: This may yield illegal argument exceptions
1101 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
1102 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1103 return parentPath.createChild(qname);
1105 if (argument instanceof SchemaNodeIdentifier
1106 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
1107 || producesDeclared(DeviationStatement.class))) {
1109 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
1112 // FIXME: this does not look right
1113 return maybeParentPath.orElse(null);
1117 public final String toString() {
1118 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1121 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1122 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument());