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.StmtContext;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
69 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
70 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
73 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
75 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
80 * Core reactor statement implementation of {@link Mutable}.
82 * @param <A> Argument type
83 * @param <D> Declared Statement representation
84 * @param <E> Effective Statement representation
86 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
87 extends NamespaceStorageSupport implements Mutable<A, D, E> {
89 * Event listener when an item is added to model namespace.
91 interface OnNamespaceItemAdded extends EventListener {
93 * Invoked whenever a new item is added to a namespace.
95 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
99 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
101 interface OnPhaseFinished extends EventListener {
103 * Invoked whenever a processing phase has finished.
105 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
109 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
111 interface ContextMutation {
113 boolean isFinished();
116 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
118 // Flag bit assignments
119 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
120 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
121 private static final int IS_IGNORE_IF_FEATURE = 0x04;
122 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
123 // Note: these four are related
124 private static final int IS_IGNORE_CONFIG = 0x10;
125 private static final int HAVE_IGNORE_CONFIG = 0x20;
126 private static final int IS_CONFIGURATION = 0x40;
127 private static final int HAVE_CONFIGURATION = 0x80;
129 // Have-and-set flag constants, also used as masks
130 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
131 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
132 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
133 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
134 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
136 private final CopyHistory copyHistory;
137 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
138 // operations, hence we want to keep it close by.
139 private final @NonNull StatementDefinitionContext<A, D, E> definition;
141 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
142 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
143 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
144 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
146 private @Nullable ModelProcessingPhase completedPhase;
147 private @Nullable E effectiveInstance;
149 // Master flag controlling whether this context can yield an effective statement
150 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
151 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
152 private boolean isSupportedToBuildEffective = true;
154 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
155 private boolean fullyDefined;
157 // 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;
263 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
264 this.completedPhase = completedPhase;
268 public abstract StatementContextBase<?, ?, ?> getParentContext();
271 * Returns the model root for this statement.
273 * @return root context of statement
276 public abstract RootStatementContext<?, ?, ?> getRoot();
279 public final @NonNull Registry getBehaviourRegistry() {
280 return getRoot().getBehaviourRegistryImpl();
284 public final YangVersion getRootVersion() {
285 return getRoot().getRootVersionImpl();
289 public final void setRootVersion(final YangVersion version) {
290 getRoot().setRootVersionImpl(version);
294 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
295 getRoot().addMutableStmtToSealImpl(mutableStatement);
299 public final void addRequiredSource(final SourceIdentifier dependency) {
300 getRoot().addRequiredSourceImpl(dependency);
304 public final void setRootIdentifier(final SourceIdentifier identifier) {
305 getRoot().setRootIdentifierImpl(identifier);
309 public final boolean isEnabledSemanticVersioning() {
310 return getRoot().isEnabledSemanticVersioningImpl();
314 public StatementSource getStatementSource() {
315 return getStatementSourceReference().getStatementSource();
319 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
320 final Class<N> type) {
321 return getLocalNamespace(type);
325 public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
326 return getNamespace(type);
330 * Associate a value with a key within a namespace.
332 * @param type Namespace type
335 * @param <K> namespace key type
336 * @param <V> namespace value type
337 * @param <N> namespace type
338 * @param <T> key type
339 * @param <U> value type
340 * @throws NamespaceNotAvailableException when the namespace is not available.
343 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
344 final Class<N> type, final T key, final U value) {
345 addToNamespace(type, key, value);
349 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
352 * Return a value associated with specified key within a namespace.
354 * @param type Namespace type
356 * @param <K> namespace key type
357 * @param <V> namespace value type
358 * @param <N> namespace type
359 * @param <T> key type
360 * @return Value, or null if there is no element
361 * @throws NamespaceNotAvailableException when the namespace is not available.
364 public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(final Class<N> type,
366 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
370 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
371 if (effective instanceof ImmutableCollection) {
375 return Collections.unmodifiableCollection(effective);
379 * Remove a set of statements from effective statements.
381 * @param statements statements to be removed
382 * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
383 * It is no longer used in that capacity and slated for removal.
385 // FIXME: 5.0.0: remove this method
386 @Deprecated(forRemoval = true)
387 public void removeStatementsFromEffectiveSubstatements(
388 final Collection<? extends StmtContext<?, ?, ?>> statements) {
389 if (!effective.isEmpty()) {
390 effective.removeAll(statements);
395 private void shrinkEffective() {
396 if (effective.isEmpty()) {
397 effective = ImmutableList.of();
401 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
402 if (effective.isEmpty()) {
406 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
407 while (iterator.hasNext()) {
408 final StmtContext<?, ?, ?> next = iterator.next();
409 if (statementDef.equals(next.getPublicDefinition())) {
418 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
419 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
420 * definition and statement argument match with one of the effective substatements' statement definition
424 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
426 * @param statementDef statement definition of the statement context to remove
427 * @param statementArg statement argument of the statement context to remove
429 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
430 final String statementArg) {
431 if (statementArg == null) {
432 removeStatementFromEffectiveSubstatements(statementDef);
435 if (effective.isEmpty()) {
439 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
440 while (iterator.hasNext()) {
441 final Mutable<?, ?, ?> next = iterator.next();
442 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
450 // YANG example: RPC/action statements always have 'input' and 'output' defined
452 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
453 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
454 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
455 // StatementContextBase subclass.
456 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
457 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
458 support.onStatementAdded(ret);
459 addEffectiveSubstatement(ret);
464 * Adds an effective statement to collection of substatements.
466 * @param substatement substatement
467 * @throws IllegalStateException
468 * if added in declared phase
469 * @throws NullPointerException
470 * if statement parameter is null
472 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
473 beforeAddEffectiveStatement(1);
474 effective.add(substatement);
478 * Adds an effective statement to collection of substatements.
480 * @param statements substatements
481 * @throws IllegalStateException
482 * if added in declared phase
483 * @throws NullPointerException
484 * if statement parameter is null
486 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
487 if (statements.isEmpty()) {
491 statements.forEach(Objects::requireNonNull);
492 beforeAddEffectiveStatement(statements.size());
493 effective.addAll(statements);
496 private void beforeAddEffectiveStatement(final int toAdd) {
497 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
498 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
499 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
500 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
502 if (effective.isEmpty()) {
503 effective = new ArrayList<>(toAdd);
507 // Exists only due to memory optimization
508 final boolean fullyDefined() {
512 // Exists only due to memory optimization, should live in AbstractResumedStatement
513 final void setFullyDefined() {
518 public E buildEffective() {
519 final E existing = effectiveInstance;
520 return existing != null ? existing : (effectiveInstance = definition.getFactory().createEffective(this));
524 * tries to execute current {@link ModelProcessingPhase} of source parsing.
527 * to be executed (completed)
528 * @return if phase was successfully completed
529 * @throws SourceException
530 * when an error occurred in source parsing
532 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
534 boolean finished = true;
535 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
536 if (!openMutations.isEmpty()) {
537 final Iterator<ContextMutation> it = openMutations.iterator();
538 while (it.hasNext()) {
539 final ContextMutation current = it.next();
540 if (current.isFinished()) {
547 if (openMutations.isEmpty()) {
548 phaseMutation.removeAll(phase);
549 if (phaseMutation.isEmpty()) {
550 phaseMutation = ImmutableMultimap.of();
555 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
556 finished &= child.tryToCompletePhase(phase);
558 for (final Mutable<?, ?, ?> child : effective) {
559 if (child instanceof StatementContextBase) {
560 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
565 onPhaseCompleted(phase);
572 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
575 * that was to be completed (finished)
576 * @throws SourceException
577 * when an error occurred in source parsing
579 private void onPhaseCompleted(final ModelProcessingPhase phase) {
580 completedPhase = phase;
582 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
583 if (listeners.isEmpty()) {
587 final Iterator<OnPhaseFinished> listener = listeners.iterator();
588 while (listener.hasNext()) {
589 final OnPhaseFinished next = listener.next();
590 if (next.phaseFinished(this, phase)) {
595 if (listeners.isEmpty()) {
596 phaseListeners.removeAll(phase);
597 if (phaseListeners.isEmpty()) {
598 phaseListeners = ImmutableMultimap.of();
604 * Ends declared section of current node.
606 void endDeclared(final ModelProcessingPhase phase) {
607 definition.onDeclarationFinished(this, phase);
611 * Return the context in which this statement was defined.
613 * @return statement definition
615 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
620 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
621 definition.checkNamespaceAllowed(type);
625 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
627 // definition().onNamespaceElementAdded(this, type, key, value);
630 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
631 final OnNamespaceItemAdded listener) {
632 final Object potential = getFromNamespace(type, key);
633 if (potential != null) {
634 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
635 listener.namespaceItemAdded(this, type, key, potential);
639 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
641 void onValueAdded(final Object value) {
642 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
647 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
648 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
649 final OnNamespaceItemAdded listener) {
650 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
651 if (existing.isPresent()) {
652 final Entry<K, V> entry = existing.get();
653 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
654 waitForPhase(entry.getValue(), type, phase, criterion, listener);
658 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
659 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
661 boolean onValueAdded(final K key, final V value) {
662 if (criterion.match(key)) {
663 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
664 waitForPhase(value, type, phase, criterion, listener);
673 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
674 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
675 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
676 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
678 final Entry<K, V> match = optMatch.get();
679 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
682 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
683 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
684 final OnNamespaceItemAdded listener) {
685 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
686 (context, phaseCompleted) -> {
687 selectMatch(type, criterion, listener);
692 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
693 final Class<N> type) {
694 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
695 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
698 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
702 public StatementDefinition getPublicDefinition() {
703 return definition.getPublicView();
707 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
708 return getRoot().getSourceContext().newInferenceAction(phase);
711 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
712 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
716 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
717 * the listener is notified immediately.
719 * @param phase requested completion phase
720 * @param listener listener to invoke
721 * @throws NullPointerException if any of the arguments is null
723 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
724 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
725 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
727 ModelProcessingPhase finishedPhase = completedPhase;
728 while (finishedPhase != null) {
729 if (phase.equals(finishedPhase)) {
730 listener.phaseFinished(this, finishedPhase);
733 finishedPhase = finishedPhase.getPreviousPhase();
735 if (phaseListeners.isEmpty()) {
736 phaseListeners = newMultimap();
739 phaseListeners.put(phase, listener);
743 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
745 * @throws IllegalStateException
746 * when the mutation was registered after phase was completed
748 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
749 ModelProcessingPhase finishedPhase = completedPhase;
750 while (finishedPhase != null) {
751 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
752 getStatementSourceReference());
753 finishedPhase = finishedPhase.getPreviousPhase();
756 if (phaseMutation.isEmpty()) {
757 phaseMutation = newMultimap();
759 phaseMutation.put(phase, mutation);
763 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
764 final KT key,final StmtContext<?, ?, ?> stmt) {
765 addContextToNamespace(namespace, key, stmt);
769 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
770 final QNameModule targetModule) {
771 checkEffectiveModelCompleted(this);
772 return definition.support().copyAsChildOf(this, parent, type, targetModule);
776 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
777 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
778 checkEffectiveModelCompleted(stmt);
779 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
780 return childCopyOf((StatementContextBase<X, Y, Z>)stmt, type, targetModule);
783 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
784 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
785 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
786 original.getPublicDefinition());
788 final StatementContextBase<X, Y, Z> result;
789 final InferredStatementContext<X, Y, Z> copy;
791 if (implicitParent.isPresent()) {
792 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
793 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
794 original.rawStatementArgument(), original.getStatementArgument(), type);
796 final CopyType childCopyType;
798 case ADDED_BY_AUGMENTATION:
799 childCopyType = CopyType.ORIGINAL;
801 case ADDED_BY_USES_AUGMENTATION:
802 childCopyType = CopyType.ADDED_BY_USES;
807 childCopyType = type;
810 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
811 result.addEffectiveSubstatement(copy);
813 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
816 original.definition.onStatementAdded(copy);
820 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
821 final ModelProcessingPhase phase = stmt.getCompletedPhase();
822 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
823 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
827 public final boolean hasImplicitParentSupport() {
828 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
832 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
833 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
834 original.getPublicDefinition());
835 if (optImplicit.isEmpty()) {
839 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
840 final CopyType type = original.getCopyHistory().getLastOperation();
841 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
842 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
845 result.addEffectiveSubstatement(original.reparent(result));
846 result.setCompletedPhase(original.getCompletedPhase());
850 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
853 * Config statements are not all that common which means we are performing a recursive search towards the root
854 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
855 * for the (usually non-existent) config statement.
858 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
859 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
862 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
863 * {@link #isIgnoringConfig(StatementContextBase)}.
865 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
866 final int fl = flags & SET_CONFIGURATION;
868 return fl == SET_CONFIGURATION;
870 if (isIgnoringConfig(parent)) {
871 // Note: SET_CONFIGURATION has been stored in flags
875 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
876 ConfigStatement.class);
877 final boolean isConfig;
878 if (configStatement != null) {
879 isConfig = configStatement.coerceStatementArgument();
881 // Validity check: if parent is config=false this cannot be a config=true
882 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
883 "Parent node has config=false, this node must not be specifed as config=true");
886 // If "config" statement is not specified, the default is the same as the parent's "config" value.
887 isConfig = parent.isConfiguration();
890 // Resolved, make sure we cache this return
891 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
895 protected abstract boolean isIgnoringConfig();
898 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
899 * keep on returning the same result without performing any lookups. Exists only to support
900 * {@link SubstatementContext#isIgnoringConfig()}.
903 * Note: use of this method implies that {@link #isConfiguration()} is realized with
904 * {@link #isConfiguration(StatementContextBase)}.
906 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
907 final int fl = flags & SET_IGNORE_CONFIG;
909 return fl == SET_IGNORE_CONFIG;
911 if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
912 flags |= SET_IGNORE_CONFIG;
916 flags |= HAVE_IGNORE_CONFIG;
920 protected abstract boolean isIgnoringIfFeatures();
923 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
924 * keep on returning the same result without performing any lookups. Exists only to support
925 * {@link SubstatementContext#isIgnoringIfFeatures()}.
927 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
928 final int fl = flags & SET_IGNORE_IF_FEATURE;
930 return fl == SET_IGNORE_IF_FEATURE;
932 if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
933 flags |= SET_IGNORE_IF_FEATURE;
937 flags |= HAVE_IGNORE_IF_FEATURE;
941 // Exists only to support SubstatementContext/InferredStatementContext
942 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
943 SchemaPath local = schemaPath;
945 synchronized (this) {
948 local = createSchemaPath(coerceParentContext());
954 return Optional.ofNullable(local);
957 private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
958 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
959 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
960 final SchemaPath parentPath = maybeParentPath.get();
962 if (StmtContextUtils.isUnknownStatement(this)) {
963 return parentPath.createChild(getPublicDefinition().getStatementName());
965 final Object argument = getStatementArgument();
966 if (argument instanceof QName) {
967 final QName qname = (QName) argument;
968 if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
969 return maybeParentPath.orElse(null);
972 return parentPath.createChild(qname);
974 if (argument instanceof String) {
975 // FIXME: This may yield illegal argument exceptions
976 final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
977 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
978 return parentPath.createChild(qname);
980 if (argument instanceof SchemaNodeIdentifier
981 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
982 || StmtContextUtils.producesDeclared(this, RefineStatement.class)
983 || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
985 return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
988 // FIXME: this does not look right
989 return maybeParentPath.orElse(null);
993 public final String toString() {
994 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
997 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
998 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());