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.StmtContext.Mutable;
69 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
70 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
73 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
75 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
80 * Core reactor statement implementation of {@link Mutable}.
82 * @param <A> Argument type
83 * @param <D> Declared Statement representation
84 * @param <E> Effective Statement representation
86 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
87 extends NamespaceStorageSupport implements Mutable<A, D, E> {
89 * Event listener when an item is added to model namespace.
91 interface OnNamespaceItemAdded extends EventListener {
93 * Invoked whenever a new item is added to a namespace.
95 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
99 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
101 interface OnPhaseFinished extends EventListener {
103 * Invoked whenever a processing phase has finished.
105 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
109 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
111 interface ContextMutation {
113 boolean isFinished();
116 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
118 // Flag bit assignments
119 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
120 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
121 private static final int IS_IGNORE_IF_FEATURE = 0x04;
122 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
123 // Note: these four are related
124 private static final int IS_IGNORE_CONFIG = 0x10;
125 private static final int HAVE_IGNORE_CONFIG = 0x20;
126 private static final int IS_CONFIGURATION = 0x40;
127 private static final int HAVE_CONFIGURATION = 0x80;
129 // Have-and-set flag constants, also used as masks
130 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
131 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
132 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
133 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
134 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
136 private final CopyHistory copyHistory;
137 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
138 // operations, hence we want to keep it close by.
139 private final @NonNull StatementDefinitionContext<A, D, E> definition;
141 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
142 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
144 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
146 private @Nullable ModelProcessingPhase completedPhase;
147 private @Nullable E effectiveInstance;
149 // Master flag controlling whether this context can yield an effective statement
150 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
151 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
152 private boolean isSupportedToBuildEffective = true;
154 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
155 private boolean fullyDefined;
157 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
158 // hence improve memory layout.
161 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
162 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
163 private volatile SchemaPath schemaPath;
165 // Copy constructor used by subclasses to implement reparent()
166 StatementContextBase(final StatementContextBase<A, D, E> original) {
167 this.copyHistory = original.copyHistory;
168 this.definition = original.definition;
170 this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
171 this.fullyDefined = original.fullyDefined;
172 this.completedPhase = original.completedPhase;
173 this.flags = original.flags;
176 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
177 this.definition = requireNonNull(def);
178 this.copyHistory = CopyHistory.original();
181 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
182 this.definition = requireNonNull(def);
183 this.copyHistory = requireNonNull(copyHistory);
187 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
188 return effectOfStatement;
192 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
193 if (effectOfStatement.isEmpty()) {
194 effectOfStatement = new ArrayList<>(1);
196 effectOfStatement.add(ctx);
200 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
201 if (ctxs.isEmpty()) {
205 if (effectOfStatement.isEmpty()) {
206 effectOfStatement = new ArrayList<>(ctxs.size());
208 effectOfStatement.addAll(ctxs);
212 public boolean isSupportedByFeatures() {
213 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
215 return fl == SET_SUPPORTED_BY_FEATURES;
217 if (isIgnoringIfFeatures()) {
218 flags |= SET_SUPPORTED_BY_FEATURES;
223 * If parent is supported, we need to check if-features statements of this context.
225 if (isParentSupportedByFeatures()) {
226 // If the set of supported features has not been provided, all features are supported by default.
227 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
228 SupportedFeatures.SUPPORTED_FEATURES);
229 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
230 flags |= SET_SUPPORTED_BY_FEATURES;
235 // Either parent is not supported or this statement is not supported
236 flags |= HAVE_SUPPORTED_BY_FEATURES;
240 protected abstract boolean isParentSupportedByFeatures();
243 public boolean isSupportedToBuildEffective() {
244 return isSupportedToBuildEffective;
248 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
249 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
253 public CopyHistory getCopyHistory() {
258 public ModelProcessingPhase getCompletedPhase() {
259 return completedPhase;
262 // FIXME: this should be propagated through a correct constructor
264 final 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 final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
316 final Class<N> type) {
317 return getLocalNamespace(type);
321 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
322 return getNamespace(type);
326 * Associate a value with a key within a namespace.
328 * @param type Namespace type
331 * @param <K> namespace key type
332 * @param <V> namespace value type
333 * @param <N> namespace type
334 * @param <T> key type
335 * @param <U> value type
336 * @throws NamespaceNotAvailableException when the namespace is not available.
339 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
340 final Class<@NonNull N> type, final T key, final U value) {
341 addToNamespace(type, key, value);
345 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
348 * Return a value associated with specified key within a namespace.
350 * @param type Namespace type
352 * @param <K> namespace key type
353 * @param <V> namespace value type
354 * @param <N> namespace type
355 * @param <T> key type
356 * @return Value, or null if there is no element
357 * @throws NamespaceNotAvailableException when the namespace is not available.
360 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(
361 final Class<@NonNull N> type, final T key) {
362 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
365 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
366 final List<StatementContextBase<?, ?, ?>> effective) {
367 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
370 private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
371 final List<StatementContextBase<?, ?, ?>> effective) {
372 return effective.isEmpty() ? ImmutableList.of() : effective;
375 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
377 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
378 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef) {
379 if (effective.isEmpty()) {
383 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
384 while (iterator.hasNext()) {
385 final StmtContext<?, ?, ?> next = iterator.next();
386 if (statementDef.equals(next.publicDefinition())) {
391 return shrinkEffective(effective);
395 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
396 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
397 * definition and statement argument match with one of the effective substatements' statement definition
401 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
403 * @param statementDef statement definition of the statement context to remove
404 * @param statementArg statement argument of the statement context to remove
406 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
407 String statementArg);
409 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
410 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef,
411 final String statementArg) {
412 if (statementArg == null) {
413 return removeStatementFromEffectiveSubstatements(effective, statementDef);
416 if (effective.isEmpty()) {
420 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
421 while (iterator.hasNext()) {
422 final Mutable<?, ?, ?> next = iterator.next();
423 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
428 return shrinkEffective(effective);
431 // YANG example: RPC/action statements always have 'input' and 'output' defined
433 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
434 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
435 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
436 // StatementContextBase subclass.
437 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
438 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
439 support.onStatementAdded(ret);
440 addEffectiveSubstatement(ret);
445 * Adds an effective statement to collection of substatements.
447 * @param substatement substatement
448 * @throws IllegalStateException if added in declared phase
449 * @throws NullPointerException if statement parameter is null
451 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
453 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
454 final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
455 verifyStatement(substatement);
457 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
458 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
459 final ModelProcessingPhase phase = completedPhase;
461 ensureCompletedPhase(stmt, phase);
468 * Adds an effective statement to collection of substatements.
470 * @param statements substatements
471 * @throws IllegalStateException
472 * if added in declared phase
473 * @throws NullPointerException
474 * if statement parameter is null
476 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
477 if (!statements.isEmpty()) {
478 statements.forEach(StatementContextBase::verifyStatement);
479 addEffectiveSubstatementsImpl(statements);
483 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
485 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
486 final List<StatementContextBase<?, ?, ?>> effective,
487 final Collection<? extends Mutable<?, ?, ?>> statements) {
488 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
489 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
490 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
491 final ModelProcessingPhase phase = completedPhase;
493 for (StatementContextBase<?, ?, ?> stmt : casted) {
494 ensureCompletedPhase(stmt, phase);
498 resized.addAll(casted);
502 abstract Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete();
504 // exposed for InferredStatementContext only
505 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
506 verifyStatement(stmt);
507 final ModelProcessingPhase phase = completedPhase;
509 ensureCompletedPhase((StatementContextBase<?, ?, ?>) stmt, phase);
513 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
514 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
515 // any statements which did not complete the same phase as the root statement.
516 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
517 final ModelProcessingPhase phase) {
518 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
521 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
522 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
525 private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
526 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
527 // We cannot allow statement to be further mutated
528 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
529 getStatementSourceReference());
530 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
533 final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
534 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
535 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
536 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
537 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
538 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
540 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
543 // These two exists only due to memory optimization, should live in AbstractResumedStatement
544 final boolean fullyDefined() {
548 final void setFullyDefined() {
553 public E buildEffective() {
555 return (existing = effectiveInstance) != null ? existing : loadEffective();
558 private E loadEffective() {
559 return effectiveInstance = definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this),
560 streamDeclared(), streamEffective());
563 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
565 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
568 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
569 * this method does nothing.
571 * @param phase to be executed (completed)
572 * @return true if phase was successfully completed
573 * @throws SourceException when an error occurred in source parsing
575 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
576 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
579 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
580 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
581 if (completeChildren(phase) && finished) {
582 onPhaseCompleted(phase);
588 private boolean completeChildren(final ModelProcessingPhase phase) {
589 boolean finished = true;
590 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
591 finished &= child.tryToCompletePhase(phase);
593 for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
594 finished &= child.tryToCompletePhase(phase);
599 private boolean runMutations(final ModelProcessingPhase phase) {
600 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
601 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
604 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
605 boolean finished = true;
606 final Iterator<ContextMutation> it = openMutations.iterator();
607 while (it.hasNext()) {
608 final ContextMutation current = it.next();
609 if (current.isFinished()) {
616 if (openMutations.isEmpty()) {
617 phaseMutation.removeAll(phase);
618 cleanupPhaseMutation();
623 private void cleanupPhaseMutation() {
624 if (phaseMutation.isEmpty()) {
625 phaseMutation = ImmutableMultimap.of();
630 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
633 * that was to be completed (finished)
634 * @throws SourceException
635 * when an error occurred in source parsing
637 private void onPhaseCompleted(final ModelProcessingPhase phase) {
638 completedPhase = phase;
640 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
641 if (!listeners.isEmpty()) {
642 runPhaseListeners(phase, listeners);
646 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
647 final Iterator<OnPhaseFinished> listener = listeners.iterator();
648 while (listener.hasNext()) {
649 final OnPhaseFinished next = listener.next();
650 if (next.phaseFinished(this, phase)) {
655 if (listeners.isEmpty()) {
656 phaseListeners.removeAll(phase);
657 if (phaseListeners.isEmpty()) {
658 phaseListeners = ImmutableMultimap.of();
664 * Ends declared section of current node.
666 void endDeclared(final ModelProcessingPhase phase) {
667 definition.onDeclarationFinished(this, phase);
671 * Return the context in which this statement was defined.
673 * @return statement definition
675 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
680 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
681 definition.checkNamespaceAllowed(type);
685 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
687 // definition().onNamespaceElementAdded(this, type, key, value);
690 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
691 final OnNamespaceItemAdded listener) {
692 final Object potential = getFromNamespace(type, key);
693 if (potential != null) {
694 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
695 listener.namespaceItemAdded(this, type, key, potential);
699 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
701 void onValueAdded(final Object value) {
702 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
707 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
708 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
709 final OnNamespaceItemAdded listener) {
710 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
711 if (existing.isPresent()) {
712 final Entry<K, V> entry = existing.get();
713 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
714 waitForPhase(entry.getValue(), type, phase, criterion, listener);
718 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
719 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
721 boolean onValueAdded(final K key, final V value) {
722 if (criterion.match(key)) {
723 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
724 waitForPhase(value, type, phase, criterion, listener);
733 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
734 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
735 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
736 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
738 final Entry<K, V> match = optMatch.get();
739 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
742 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
743 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
744 final OnNamespaceItemAdded listener) {
745 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
746 (context, phaseCompleted) -> {
747 selectMatch(type, criterion, listener);
752 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
753 final Class<N> type) {
754 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
755 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
758 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
762 public final StatementDefinition publicDefinition() {
763 return definition.getPublicView();
767 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
768 return getRoot().getSourceContext().newInferenceAction(phase);
771 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
772 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
776 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
777 * the listener is notified immediately.
779 * @param phase requested completion phase
780 * @param listener listener to invoke
781 * @throws NullPointerException if any of the arguments is null
783 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
784 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
785 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
787 ModelProcessingPhase finishedPhase = completedPhase;
788 while (finishedPhase != null) {
789 if (phase.equals(finishedPhase)) {
790 listener.phaseFinished(this, finishedPhase);
793 finishedPhase = finishedPhase.getPreviousPhase();
795 if (phaseListeners.isEmpty()) {
796 phaseListeners = newMultimap();
799 phaseListeners.put(phase, listener);
803 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
805 * @throws IllegalStateException when the mutation was registered after phase was completed
807 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
808 ModelProcessingPhase finishedPhase = completedPhase;
809 while (finishedPhase != null) {
810 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
811 getStatementSourceReference());
812 finishedPhase = finishedPhase.getPreviousPhase();
815 if (phaseMutation.isEmpty()) {
816 phaseMutation = newMultimap();
818 phaseMutation.put(phase, mutation);
821 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
822 if (!phaseMutation.isEmpty()) {
823 phaseMutation.remove(phase, mutation);
824 cleanupPhaseMutation();
829 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
830 final KT key,final StmtContext<?, ?, ?> stmt) {
831 addContextToNamespace(namespace, key, stmt);
835 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
836 final QNameModule targetModule) {
837 checkEffectiveModelCompleted(this);
839 final StatementSupport<A, D, E> support = definition.support();
840 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
842 case CONTEXT_INDEPENDENT:
843 if (hasEmptySubstatements()) {
844 // This statement is context-independent and has no substatements -- hence it can be freely shared.
845 return Optional.of(this);
847 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
850 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
851 // context, so that we can support building an effective statement without copying
852 // anything -- we will typically end up not being inferred against. In that case,
853 // this slim context should end up dealing with differences at buildContext()
854 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
855 // cannot be shared across instances).
856 return Optional.of(parent.childCopyOf(this, type, targetModule));
858 return Optional.empty();
860 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
862 throw new IllegalStateException("Unhandled policy " + policy);
867 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
868 final QNameModule targetModule) {
869 checkEffectiveModelCompleted(stmt);
870 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
871 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
874 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
875 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
876 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
877 original.publicDefinition());
879 final StatementContextBase<X, Y, Z> result;
880 final InferredStatementContext<X, Y, Z> copy;
882 if (implicitParent.isPresent()) {
883 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
884 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
885 original.rawStatementArgument(), original.getStatementArgument(), type);
887 final CopyType childCopyType;
889 case ADDED_BY_AUGMENTATION:
890 childCopyType = CopyType.ORIGINAL;
892 case ADDED_BY_USES_AUGMENTATION:
893 childCopyType = CopyType.ADDED_BY_USES;
898 childCopyType = type;
901 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
902 result.addEffectiveSubstatement(copy);
904 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
907 original.definition.onStatementAdded(copy);
911 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
912 final ModelProcessingPhase phase = stmt.getCompletedPhase();
913 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
914 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
918 public final boolean hasImplicitParentSupport() {
919 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
923 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
924 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
925 original.publicDefinition());
926 if (optImplicit.isEmpty()) {
930 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
931 final CopyType type = original.getCopyHistory().getLastOperation();
932 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
933 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
936 result.addEffectiveSubstatement(original.reparent(result));
937 result.setCompletedPhase(original.getCompletedPhase());
941 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
944 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
946 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
948 abstract boolean hasEmptySubstatements();
951 * Config statements are not all that common which means we are performing a recursive search towards the root
952 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
953 * for the (usually non-existent) config statement.
956 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
957 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
960 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
961 * {@link #isIgnoringConfig(StatementContextBase)}.
963 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
964 final int fl = flags & SET_CONFIGURATION;
966 return fl == SET_CONFIGURATION;
968 if (isIgnoringConfig(parent)) {
969 // Note: SET_CONFIGURATION has been stored in flags
973 final boolean isConfig;
974 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
975 if (optConfig.isPresent()) {
976 isConfig = optConfig.orElseThrow();
978 // Validity check: if parent is config=false this cannot be a config=true
979 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
980 "Parent node has config=false, this node must not be specifed as config=true");
983 // If "config" statement is not specified, the default is the same as the parent's "config" value.
984 isConfig = parent.isConfiguration();
987 // Resolved, make sure we cache this return
988 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
992 protected abstract boolean isIgnoringConfig();
995 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
996 * keep on returning the same result without performing any lookups. Exists only to support
997 * {@link SubstatementContext#isIgnoringConfig()}.
1000 * Note: use of this method implies that {@link #isConfiguration()} is realized with
1001 * {@link #isConfiguration(StatementContextBase)}.
1003 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
1004 final int fl = flags & SET_IGNORE_CONFIG;
1006 return fl == SET_IGNORE_CONFIG;
1008 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
1009 flags |= SET_IGNORE_CONFIG;
1013 flags |= HAVE_IGNORE_CONFIG;
1017 protected abstract boolean isIgnoringIfFeatures();
1020 * This method maintains a resolution cache for ignore if-feature, 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#isIgnoringIfFeatures()}.
1024 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
1025 final int fl = flags & SET_IGNORE_IF_FEATURE;
1027 return fl == SET_IGNORE_IF_FEATURE;
1029 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1030 flags |= SET_IGNORE_IF_FEATURE;
1034 flags |= HAVE_IGNORE_IF_FEATURE;
1038 abstract @NonNull Optional<SchemaPath> schemaPath();
1040 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
1042 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1043 SchemaPath local = schemaPath;
1044 if (local == null) {
1045 synchronized (this) {
1047 if (local == null) {
1048 schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
1053 return Optional.ofNullable(local);
1057 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
1058 final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
1059 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1060 final SchemaPath parentPath = maybeParentPath.get();
1062 if (StmtContextUtils.isUnknownStatement(this)) {
1063 return parentPath.createChild(publicDefinition().getStatementName());
1065 final Object argument = getStatementArgument();
1066 if (argument instanceof QName) {
1067 final QName qname = (QName) argument;
1068 if (producesDeclared(UsesStatement.class)) {
1069 return maybeParentPath.orElse(null);
1072 return parentPath.createChild(qname);
1074 if (argument instanceof String) {
1075 // FIXME: This may yield illegal argument exceptions
1076 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
1077 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1078 return parentPath.createChild(qname);
1080 if (argument instanceof SchemaNodeIdentifier
1081 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
1082 || producesDeclared(DeviationStatement.class))) {
1084 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
1087 // FIXME: this does not look right
1088 return maybeParentPath.orElse(null);
1092 public final String toString() {
1093 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1096 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1097 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());