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;
31 import java.util.Map.Entry;
32 import java.util.Objects;
33 import java.util.Optional;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.common.YangVersion;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
44 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
45 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
46 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
51 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
52 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
68 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
69 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
70 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
72 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
73 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * Core reactor statement implementation of {@link Mutable}.
80 * @param <A> Argument type
81 * @param <D> Declared Statement representation
82 * @param <E> Effective Statement representation
84 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
85 extends NamespaceStorageSupport implements Mutable<A, D, E> {
87 * Event listener when an item is added to model namespace.
89 interface OnNamespaceItemAdded extends EventListener {
91 * Invoked whenever a new item is added to a namespace.
93 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
97 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
99 interface OnPhaseFinished extends EventListener {
101 * Invoked whenever a processing phase has finished.
103 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
107 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
109 interface ContextMutation {
111 boolean isFinished();
114 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
116 // Flag bit assignments
117 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
118 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
119 private static final int IS_IGNORE_IF_FEATURE = 0x04;
120 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
121 // Note: these four are related
122 private static final int IS_IGNORE_CONFIG = 0x10;
123 private static final int HAVE_IGNORE_CONFIG = 0x20;
124 private static final int IS_CONFIGURATION = 0x40;
125 private static final int HAVE_CONFIGURATION = 0x80;
127 // Have-and-set flag constants, also used as masks
128 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
129 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
130 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
131 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
132 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
134 private final CopyHistory copyHistory;
135 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
136 // operations, hence we want to keep it close by.
137 private final @NonNull StatementDefinitionContext<A, D, E> definition;
139 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
140 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
141 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
142 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
144 private @Nullable ModelProcessingPhase completedPhase;
145 private @Nullable D declaredInstance;
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 StatementContextBase(final StatementContextBase<A, D, E> original) {
165 this.copyHistory = original.copyHistory;
166 this.definition = original.definition;
169 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
170 this.definition = requireNonNull(def);
171 this.copyHistory = CopyHistory.original();
174 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
175 this.definition = requireNonNull(def);
176 this.copyHistory = requireNonNull(copyHistory);
180 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
181 return effectOfStatement;
185 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
186 if (effectOfStatement.isEmpty()) {
187 effectOfStatement = new ArrayList<>(1);
189 effectOfStatement.add(ctx);
193 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
194 if (ctxs.isEmpty()) {
198 if (effectOfStatement.isEmpty()) {
199 effectOfStatement = new ArrayList<>(ctxs.size());
201 effectOfStatement.addAll(ctxs);
205 public boolean isSupportedByFeatures() {
206 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
208 return fl == SET_SUPPORTED_BY_FEATURES;
210 if (isIgnoringIfFeatures()) {
211 flags |= SET_SUPPORTED_BY_FEATURES;
216 * If parent is supported, we need to check if-features statements of this context.
218 if (isParentSupportedByFeatures()) {
219 // If the set of supported features has not been provided, all features are supported by default.
220 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
221 SupportedFeatures.SUPPORTED_FEATURES);
222 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
223 flags |= SET_SUPPORTED_BY_FEATURES;
228 // Either parent is not supported or this statement is not supported
229 flags |= HAVE_SUPPORTED_BY_FEATURES;
233 protected abstract boolean isParentSupportedByFeatures();
236 public boolean isSupportedToBuildEffective() {
237 return isSupportedToBuildEffective;
241 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
242 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
246 public CopyHistory getCopyHistory() {
251 public ModelProcessingPhase getCompletedPhase() {
252 return completedPhase;
256 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
257 this.completedPhase = completedPhase;
261 public abstract StatementContextBase<?, ?, ?> getParentContext();
264 * Returns the model root for this statement.
266 * @return root context of statement
269 public abstract RootStatementContext<?, ?, ?> getRoot();
272 public final @NonNull Registry getBehaviourRegistry() {
273 return getRoot().getBehaviourRegistryImpl();
277 public final YangVersion getRootVersion() {
278 return getRoot().getRootVersionImpl();
282 public final void setRootVersion(final YangVersion version) {
283 getRoot().setRootVersionImpl(version);
287 public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
288 getRoot().addMutableStmtToSealImpl(mutableStatement);
292 public final void addRequiredSource(final SourceIdentifier dependency) {
293 getRoot().addRequiredSourceImpl(dependency);
297 public final void setRootIdentifier(final SourceIdentifier identifier) {
298 getRoot().setRootIdentifierImpl(identifier);
302 public final boolean isEnabledSemanticVersioning() {
303 return getRoot().isEnabledSemanticVersioningImpl();
307 public StatementSource getStatementSource() {
308 return getStatementSourceReference().getStatementSource();
312 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
315 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
316 if (effective instanceof ImmutableCollection) {
320 return Collections.unmodifiableCollection(effective);
323 private void shrinkEffective() {
324 if (effective.isEmpty()) {
325 effective = ImmutableList.of();
329 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
330 if (effective.isEmpty()) {
334 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
335 while (iterator.hasNext()) {
336 final StmtContext<?, ?, ?> next = iterator.next();
337 if (statementDef.equals(next.getPublicDefinition())) {
346 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
347 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
348 * definition and statement argument match with one of the effective substatements' statement definition
352 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
354 * @param statementDef statement definition of the statement context to remove
355 * @param statementArg statement argument of the statement context to remove
357 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
358 final String statementArg) {
359 if (statementArg == null) {
360 removeStatementFromEffectiveSubstatements(statementDef);
363 if (effective.isEmpty()) {
367 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
368 while (iterator.hasNext()) {
369 final Mutable<?, ?, ?> next = iterator.next();
370 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
378 // YANG example: RPC/action statements always have 'input' and 'output' defined
380 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
381 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
382 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
383 // StatementContextBase subclass.
384 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
385 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
386 support.onStatementAdded(ret);
387 addEffectiveSubstatement(ret);
392 * Adds an effective statement to collection of substatements.
394 * @param substatement substatement
395 * @throws IllegalStateException
396 * if added in declared phase
397 * @throws NullPointerException
398 * if statement parameter is null
400 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
401 beforeAddEffectiveStatement(1);
402 effective.add(substatement);
406 * Adds an effective statement to collection of substatements.
408 * @param statements substatements
409 * @throws IllegalStateException
410 * if added in declared phase
411 * @throws NullPointerException
412 * if statement parameter is null
414 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
415 if (statements.isEmpty()) {
419 statements.forEach(Objects::requireNonNull);
420 beforeAddEffectiveStatement(statements.size());
421 effective.addAll(statements);
424 private void beforeAddEffectiveStatement(final int toAdd) {
425 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
426 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
427 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
428 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
430 if (effective.isEmpty()) {
431 effective = new ArrayList<>(toAdd);
435 // Exists only due to memory optimization
436 final boolean fullyDefined() {
440 // Exists only due to memory optimization, should live in AbstractResumedStatement
441 final void setFullyDefined() {
446 public D buildDeclared() {
447 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
448 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
449 if (declaredInstance == null) {
450 declaredInstance = definition.getFactory().createDeclared(this);
452 return declaredInstance;
456 public E buildEffective() {
457 if (effectiveInstance == null) {
458 effectiveInstance = definition.getFactory().createEffective(this);
460 return effectiveInstance;
464 * tries to execute current {@link ModelProcessingPhase} of source parsing.
467 * to be executed (completed)
468 * @return if phase was successfully completed
469 * @throws SourceException
470 * when an error occurred in source parsing
472 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
474 boolean finished = true;
475 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
476 if (!openMutations.isEmpty()) {
477 final Iterator<ContextMutation> it = openMutations.iterator();
478 while (it.hasNext()) {
479 final ContextMutation current = it.next();
480 if (current.isFinished()) {
487 if (openMutations.isEmpty()) {
488 phaseMutation.removeAll(phase);
489 if (phaseMutation.isEmpty()) {
490 phaseMutation = ImmutableMultimap.of();
495 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
496 finished &= child.tryToCompletePhase(phase);
498 for (final Mutable<?, ?, ?> child : effective) {
499 if (child instanceof StatementContextBase) {
500 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
505 onPhaseCompleted(phase);
512 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
515 * that was to be completed (finished)
516 * @throws SourceException
517 * when an error occurred in source parsing
519 private void onPhaseCompleted(final ModelProcessingPhase phase) {
520 completedPhase = phase;
522 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
523 if (listeners.isEmpty()) {
527 final Iterator<OnPhaseFinished> listener = listeners.iterator();
528 while (listener.hasNext()) {
529 final OnPhaseFinished next = listener.next();
530 if (next.phaseFinished(this, phase)) {
535 if (listeners.isEmpty()) {
536 phaseListeners.removeAll(phase);
537 if (phaseListeners.isEmpty()) {
538 phaseListeners = ImmutableMultimap.of();
544 * Ends declared section of current node.
546 void endDeclared(final ModelProcessingPhase phase) {
547 definition.onDeclarationFinished(this, phase);
551 * Return the context in which this statement was defined.
553 * @return statement definition
555 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
560 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
561 definition.checkNamespaceAllowed(type);
565 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
567 // definition().onNamespaceElementAdded(this, type, key, value);
570 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
571 final OnNamespaceItemAdded listener) {
572 final Object potential = getFromNamespace(type, key);
573 if (potential != null) {
574 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
575 listener.namespaceItemAdded(this, type, key, potential);
579 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
581 void onValueAdded(final Object value) {
582 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
587 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
588 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
589 final OnNamespaceItemAdded listener) {
590 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
591 if (existing.isPresent()) {
592 final Entry<K, V> entry = existing.get();
593 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
594 waitForPhase(entry.getValue(), type, phase, criterion, listener);
598 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
599 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
601 boolean onValueAdded(final K key, final V value) {
602 if (criterion.match(key)) {
603 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
604 waitForPhase(value, type, phase, criterion, listener);
613 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
614 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
615 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
616 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
618 final Entry<K, V> match = optMatch.get();
619 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
622 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
623 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
624 final OnNamespaceItemAdded listener) {
625 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
626 (context, phaseCompleted) -> {
627 selectMatch(type, criterion, listener);
632 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
633 final Class<N> type) {
634 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
635 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
638 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
642 public StatementDefinition getPublicDefinition() {
643 return definition.getPublicView();
647 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
648 return getRoot().getSourceContext().newInferenceAction(phase);
651 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
652 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
656 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
657 * the listener is notified immediately.
659 * @param phase requested completion phase
660 * @param listener listener to invoke
661 * @throws NullPointerException if any of the arguments is null
663 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
664 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
665 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
667 ModelProcessingPhase finishedPhase = completedPhase;
668 while (finishedPhase != null) {
669 if (phase.equals(finishedPhase)) {
670 listener.phaseFinished(this, finishedPhase);
673 finishedPhase = finishedPhase.getPreviousPhase();
675 if (phaseListeners.isEmpty()) {
676 phaseListeners = newMultimap();
679 phaseListeners.put(phase, listener);
683 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
685 * @throws IllegalStateException
686 * when the mutation was registered after phase was completed
688 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
689 ModelProcessingPhase finishedPhase = completedPhase;
690 while (finishedPhase != null) {
691 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
692 getStatementSourceReference());
693 finishedPhase = finishedPhase.getPreviousPhase();
696 if (phaseMutation.isEmpty()) {
697 phaseMutation = newMultimap();
699 phaseMutation.put(phase, mutation);
703 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
704 final KT key,final StmtContext<?, ?, ?> stmt) {
705 addContextToNamespace(namespace, key, stmt);
709 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
710 final QNameModule targetModule) {
711 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
712 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
713 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
714 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
717 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
718 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
719 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
720 original.getPublicDefinition());
722 final StatementContextBase<X, Y, Z> result;
723 final InferredStatementContext<X, Y, Z> copy;
725 if (implicitParent.isPresent()) {
726 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
727 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
728 original.rawStatementArgument(), original.getStatementArgument(), type);
730 final CopyType childCopyType;
732 case ADDED_BY_AUGMENTATION:
733 childCopyType = CopyType.ORIGINAL;
735 case ADDED_BY_USES_AUGMENTATION:
736 childCopyType = CopyType.ADDED_BY_USES;
741 childCopyType = type;
744 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
745 result.addEffectiveSubstatement(copy);
747 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
750 original.definition.onStatementAdded(copy);
755 public final boolean hasImplicitParentSupport() {
756 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
760 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
761 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
762 original.getPublicDefinition());
763 if (optImplicit.isEmpty()) {
767 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
768 final CopyType type = original.getCopyHistory().getLastOperation();
769 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
770 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
773 result.addEffectiveSubstatement(original.reparent(result));
774 result.setCompletedPhase(original.getCompletedPhase());
778 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
781 * Config statements are not all that common which means we are performing a recursive search towards the root
782 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
783 * for the (usually non-existent) config statement.
786 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
787 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
790 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
791 * {@link #isIgnoringConfig(StatementContextBase)}.
793 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
794 final int fl = flags & SET_CONFIGURATION;
796 return fl == SET_CONFIGURATION;
798 if (isIgnoringConfig(parent)) {
799 // Note: SET_CONFIGURATION has been stored in flags
803 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
804 ConfigStatement.class);
805 final boolean isConfig;
806 if (configStatement != null) {
807 isConfig = configStatement.coerceStatementArgument();
809 // Validity check: if parent is config=false this cannot be a config=true
810 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
811 "Parent node has config=false, this node must not be specifed as config=true");
814 // If "config" statement is not specified, the default is the same as the parent's "config" value.
815 isConfig = parent.isConfiguration();
818 // Resolved, make sure we cache this return
819 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
823 protected abstract boolean isIgnoringConfig();
826 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
827 * keep on returning the same result without performing any lookups. Exists only to support
828 * {@link SubstatementContext#isIgnoringConfig()}.
831 * Note: use of this method implies that {@link #isConfiguration()} is realized with
832 * {@link #isConfiguration(StatementContextBase)}.
834 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
835 final int fl = flags & SET_IGNORE_CONFIG;
837 return fl == SET_IGNORE_CONFIG;
839 if (definition.isIgnoringConfig() || parent.isIgnoringConfig()) {
840 flags |= SET_IGNORE_CONFIG;
844 flags |= HAVE_IGNORE_CONFIG;
848 protected abstract boolean isIgnoringIfFeatures();
851 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
852 * keep on returning the same result without performing any lookups. Exists only to support
853 * {@link SubstatementContext#isIgnoringIfFeatures()}.
855 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
856 final int fl = flags & SET_IGNORE_IF_FEATURE;
858 return fl == SET_IGNORE_IF_FEATURE;
860 if (definition.isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
861 flags |= SET_IGNORE_IF_FEATURE;
865 flags |= HAVE_IGNORE_IF_FEATURE;
869 // Exists only to support SubstatementContext/InferredStatementContext
870 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
871 SchemaPath local = schemaPath;
873 synchronized (this) {
876 local = createSchemaPath(coerceParentContext());
882 return Optional.ofNullable(local);
885 private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
886 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
887 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
888 final SchemaPath parentPath = maybeParentPath.get();
890 if (StmtContextUtils.isUnknownStatement(this)) {
891 return parentPath.createChild(getPublicDefinition().getStatementName());
893 final Object argument = getStatementArgument();
894 if (argument instanceof QName) {
895 final QName qname = (QName) argument;
896 if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
897 return maybeParentPath.orElse(null);
900 return parentPath.createChild(qname);
902 if (argument instanceof String) {
903 // FIXME: This may yield illegal argument exceptions
904 final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
905 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
906 return parentPath.createChild(qname);
908 if (argument instanceof SchemaNodeIdentifier
909 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
910 || StmtContextUtils.producesDeclared(this, RefineStatement.class)
911 || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
913 return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
916 // FIXME: this does not look right
917 return maybeParentPath.orElse(null);
921 public final String toString() {
922 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
925 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
926 return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());