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 java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.MoreObjects;
17 import com.google.common.base.MoreObjects.ToStringHelper;
18 import com.google.common.collect.ImmutableCollection;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMultimap;
21 import com.google.common.collect.ImmutableSet;
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.model.api.YangStmtMapping;
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
43 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
44 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
45 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
59 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
62 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
64 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
70 * Core reactor statement implementation of {@link Mutable}.
72 * @param <A> Argument type
73 * @param <D> Declared Statement representation
74 * @param <E> Effective Statement representation
76 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
77 extends NamespaceStorageSupport implements Mutable<A, D, E> {
79 * Event listener when an item is added to model namespace.
81 interface OnNamespaceItemAdded extends EventListener {
83 * Invoked whenever a new item is added to a namespace.
85 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
89 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
91 interface OnPhaseFinished extends EventListener {
93 * Invoked whenever a processing phase has finished.
95 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
99 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
101 interface ContextMutation {
103 boolean isFinished();
106 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
108 // Flag bit assignments
109 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
110 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
111 private static final int IS_IGNORE_IF_FEATURE = 0x04;
112 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
113 // Note: these four are related
114 private static final int IS_IGNORE_CONFIG = 0x10;
115 private static final int HAVE_IGNORE_CONFIG = 0x20;
116 private static final int IS_CONFIGURATION = 0x40;
117 private static final int HAVE_CONFIGURATION = 0x80;
119 // Have-and-set flag constants, also used as masks
120 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
121 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
122 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
123 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
124 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
126 private final @NonNull StatementDefinitionContext<A, D, E> definition;
127 private final @NonNull StatementSourceReference statementDeclSource;
128 private final StmtContext<?, ?, ?> originalCtx;
129 private final StmtContext<?, ?, ?> prevCopyCtx;
130 private final CopyHistory copyHistory;
131 private final String rawArgument;
133 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
134 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
135 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
136 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
138 private @Nullable ModelProcessingPhase completedPhase;
139 private @Nullable D declaredInstance;
140 private @Nullable E effectiveInstance;
142 // Master flag controlling whether this context can yield an effective statement
143 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
144 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
145 private boolean isSupportedToBuildEffective = true;
147 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
148 private boolean fullyDefined;
150 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
151 // hence improve memory layout.
154 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
155 final String rawArgument) {
156 this.definition = requireNonNull(def);
157 this.statementDeclSource = requireNonNull(ref);
158 this.rawArgument = def.internArgument(rawArgument);
159 this.copyHistory = CopyHistory.original();
160 this.originalCtx = null;
161 this.prevCopyCtx = null;
164 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
165 final String rawArgument, final CopyType copyType) {
166 this.definition = requireNonNull(def);
167 this.statementDeclSource = requireNonNull(ref);
168 this.rawArgument = rawArgument;
169 this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
170 this.originalCtx = null;
171 this.prevCopyCtx = null;
174 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
175 this.definition = original.definition;
176 this.statementDeclSource = original.statementDeclSource;
177 this.rawArgument = original.rawArgument;
178 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
179 this.originalCtx = original.getOriginalCtx().orElse(original);
180 this.prevCopyCtx = original;
183 StatementContextBase(final StatementContextBase<A, D, E> original) {
184 this.definition = original.definition;
185 this.statementDeclSource = original.statementDeclSource;
186 this.rawArgument = original.rawArgument;
187 this.copyHistory = original.getCopyHistory();
188 this.originalCtx = original.getOriginalCtx().orElse(original);
189 this.prevCopyCtx = original;
190 this.effective = original.effective;
194 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
195 return effectOfStatement;
199 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
200 if (effectOfStatement.isEmpty()) {
201 effectOfStatement = new ArrayList<>(1);
203 effectOfStatement.add(ctx);
207 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
208 if (ctxs.isEmpty()) {
212 if (effectOfStatement.isEmpty()) {
213 effectOfStatement = new ArrayList<>(ctxs.size());
215 effectOfStatement.addAll(ctxs);
219 public boolean isSupportedByFeatures() {
220 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
222 return fl == SET_SUPPORTED_BY_FEATURES;
224 if (isIgnoringIfFeatures()) {
225 flags |= SET_SUPPORTED_BY_FEATURES;
230 * If parent is supported, we need to check if-features statements of this context.
232 if (isParentSupportedByFeatures()) {
233 // If the set of supported features has not been provided, all features are supported by default.
234 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
235 SupportedFeatures.SUPPORTED_FEATURES);
236 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
237 flags |= SET_SUPPORTED_BY_FEATURES;
242 // Either parent is not supported or this statement is not supported
243 flags |= HAVE_SUPPORTED_BY_FEATURES;
247 protected abstract boolean isParentSupportedByFeatures();
250 public boolean isSupportedToBuildEffective() {
251 return isSupportedToBuildEffective;
255 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
256 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
260 public CopyHistory getCopyHistory() {
265 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
266 return Optional.ofNullable(originalCtx);
270 public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
271 return Optional.ofNullable(prevCopyCtx);
275 public ModelProcessingPhase getCompletedPhase() {
276 return completedPhase;
280 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
281 this.completedPhase = completedPhase;
285 public abstract StatementContextBase<?, ?, ?> getParentContext();
288 * Returns the model root for this statement.
290 * @return root context of statement
293 public abstract RootStatementContext<?, ?, ?> getRoot();
296 public StatementSource getStatementSource() {
297 return statementDeclSource.getStatementSource();
301 public StatementSourceReference getStatementSourceReference() {
302 return statementDeclSource;
306 public final String rawStatementArgument() {
311 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
314 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
315 return mutableEffectiveSubstatements();
319 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
320 if (effective instanceof ImmutableCollection) {
324 return Collections.unmodifiableCollection(effective);
328 * Remove a set of statements from effective statements.
330 * @param statements statements to be removed
331 * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
332 * It is no longer used in that capacity and slated for removal.
334 // FIXME: 5.0.0: remove this method
335 @Deprecated(forRemoval = true)
336 public void removeStatementsFromEffectiveSubstatements(
337 final Collection<? extends StmtContext<?, ?, ?>> statements) {
338 if (!effective.isEmpty()) {
339 effective.removeAll(statements);
344 private void shrinkEffective() {
345 if (effective.isEmpty()) {
346 effective = ImmutableList.of();
350 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
351 if (effective.isEmpty()) {
355 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
356 while (iterator.hasNext()) {
357 final StmtContext<?, ?, ?> next = iterator.next();
358 if (statementDef.equals(next.getPublicDefinition())) {
367 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
368 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
369 * definition and statement argument match with one of the effective substatements' statement definition
373 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
375 * @param statementDef statement definition of the statement context to remove
376 * @param statementArg statement argument of the statement context to remove
378 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
379 final String statementArg) {
380 if (statementArg == null) {
381 removeStatementFromEffectiveSubstatements(statementDef);
384 if (effective.isEmpty()) {
388 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
389 while (iterator.hasNext()) {
390 final Mutable<?, ?, ?> next = iterator.next();
391 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
399 // YANG example: RPC/action statements always have 'input' and 'output' defined
401 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
402 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
403 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
404 // StatementContextBase subclass.
405 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
406 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
407 support.onStatementAdded(ret);
408 addEffectiveSubstatement(ret);
413 * Adds an effective statement to collection of substatements.
415 * @param substatement substatement
416 * @throws IllegalStateException
417 * if added in declared phase
418 * @throws NullPointerException
419 * if statement parameter is null
421 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
422 beforeAddEffectiveStatement(1);
423 effective.add(substatement);
427 * Adds an effective statement to collection of substatements.
429 * @param statements substatements
430 * @throws IllegalStateException
431 * if added in declared phase
432 * @throws NullPointerException
433 * if statement parameter is null
435 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
436 if (statements.isEmpty()) {
440 statements.forEach(Objects::requireNonNull);
441 beforeAddEffectiveStatement(statements.size());
442 effective.addAll(statements);
445 private void beforeAddEffectiveStatement(final int toAdd) {
446 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
447 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
448 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
449 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
451 if (effective.isEmpty()) {
452 effective = new ArrayList<>(toAdd);
456 // Exists only due to memory optimization
457 final boolean fullyDefined() {
461 // Exists only due to memory optimization, should live in AbstractResumedStatement
462 final void setFullyDefined() {
467 public D buildDeclared() {
468 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
469 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
470 if (declaredInstance == null) {
471 declaredInstance = definition().getFactory().createDeclared(this);
473 return declaredInstance;
477 public E buildEffective() {
478 if (effectiveInstance == null) {
479 effectiveInstance = definition().getFactory().createEffective(this);
481 return effectiveInstance;
485 * tries to execute current {@link ModelProcessingPhase} of source parsing.
488 * to be executed (completed)
489 * @return if phase was successfully completed
490 * @throws SourceException
491 * when an error occurred in source parsing
493 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
495 boolean finished = true;
496 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
497 if (!openMutations.isEmpty()) {
498 final Iterator<ContextMutation> it = openMutations.iterator();
499 while (it.hasNext()) {
500 final ContextMutation current = it.next();
501 if (current.isFinished()) {
508 if (openMutations.isEmpty()) {
509 phaseMutation.removeAll(phase);
510 if (phaseMutation.isEmpty()) {
511 phaseMutation = ImmutableMultimap.of();
516 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
517 finished &= child.tryToCompletePhase(phase);
519 for (final Mutable<?, ?, ?> child : effective) {
520 if (child instanceof StatementContextBase) {
521 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
526 onPhaseCompleted(phase);
533 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
536 * that was to be completed (finished)
537 * @throws SourceException
538 * when an error occurred in source parsing
540 private void onPhaseCompleted(final ModelProcessingPhase phase) {
541 completedPhase = phase;
543 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
544 if (listeners.isEmpty()) {
548 final Iterator<OnPhaseFinished> listener = listeners.iterator();
549 while (listener.hasNext()) {
550 final OnPhaseFinished next = listener.next();
551 if (next.phaseFinished(this, phase)) {
556 if (listeners.isEmpty()) {
557 phaseListeners.removeAll(phase);
558 if (phaseListeners.isEmpty()) {
559 phaseListeners = ImmutableMultimap.of();
565 * Ends declared section of current node.
567 void endDeclared(final ModelProcessingPhase phase) {
568 definition().onDeclarationFinished(this, phase);
572 * Return the context in which this statement was defined.
574 * @return statement definition
576 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
581 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
582 definition().checkNamespaceAllowed(type);
586 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
588 // definition().onNamespaceElementAdded(this, type, key, value);
591 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
592 final OnNamespaceItemAdded listener) {
593 final Object potential = getFromNamespace(type, key);
594 if (potential != null) {
595 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
596 listener.namespaceItemAdded(this, type, key, potential);
600 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
602 void onValueAdded(final Object value) {
603 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
608 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
609 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
610 final OnNamespaceItemAdded listener) {
611 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
612 if (existing.isPresent()) {
613 final Entry<K, V> entry = existing.get();
614 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
615 waitForPhase(entry.getValue(), type, phase, criterion, listener);
619 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
620 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
622 boolean onValueAdded(final K key, final V value) {
623 if (criterion.match(key)) {
624 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
625 waitForPhase(value, type, phase, criterion, listener);
634 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
635 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
636 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
637 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
639 final Entry<K, V> match = optMatch.get();
640 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
643 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
644 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
645 final OnNamespaceItemAdded listener) {
646 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
647 (context, phaseCompleted) -> {
648 selectMatch(type, criterion, listener);
653 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
654 final Class<N> type) {
655 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
656 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
659 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
663 public StatementDefinition getPublicDefinition() {
664 return definition().getPublicView();
668 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
669 return getRoot().getSourceContext().newInferenceAction(phase);
672 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
673 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
677 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
678 * the listener is notified immediately.
680 * @param phase requested completion phase
681 * @param listener listener to invoke
682 * @throws NullPointerException if any of the arguments is null
684 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
685 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
686 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
688 ModelProcessingPhase finishedPhase = completedPhase;
689 while (finishedPhase != null) {
690 if (phase.equals(finishedPhase)) {
691 listener.phaseFinished(this, finishedPhase);
694 finishedPhase = finishedPhase.getPreviousPhase();
696 if (phaseListeners.isEmpty()) {
697 phaseListeners = newMultimap();
700 phaseListeners.put(phase, listener);
704 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
706 * @throws IllegalStateException
707 * when the mutation was registered after phase was completed
709 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
710 ModelProcessingPhase finishedPhase = completedPhase;
711 while (finishedPhase != null) {
712 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
713 getStatementSourceReference());
714 finishedPhase = finishedPhase.getPreviousPhase();
717 if (phaseMutation.isEmpty()) {
718 phaseMutation = newMultimap();
720 phaseMutation.put(phase, mutation);
724 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
725 final KT key,final StmtContext<?, ?, ?> stmt) {
726 addContextToNamespace(namespace, key, stmt);
730 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
731 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
732 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
733 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
735 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
737 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
738 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
739 original.getPublicDefinition());
741 final SubstatementContext<X, Y, Z> result;
742 final SubstatementContext<X, Y, Z> copy;
744 if (implicitParent.isPresent()) {
745 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
746 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
747 original.rawStatementArgument(), original.getStatementArgument(), type);
749 final CopyType childCopyType;
751 case ADDED_BY_AUGMENTATION:
752 childCopyType = CopyType.ORIGINAL;
754 case ADDED_BY_USES_AUGMENTATION:
755 childCopyType = CopyType.ADDED_BY_USES;
760 childCopyType = type;
763 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
764 result.addEffectiveSubstatement(copy);
766 result = copy = new SubstatementContext<>(original, this, type, targetModule);
769 original.definition().onStatementAdded(copy);
770 original.copyTo(copy, type, targetModule);
775 public final boolean hasImplicitParentSupport() {
776 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
780 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
781 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
782 original.getPublicDefinition());
783 if (optImplicit.isEmpty()) {
787 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
788 final CopyType type = original.getCopyHistory().getLastOperation();
789 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
790 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
793 result.addEffectiveSubstatement(original.reparent(result));
794 result.setCompletedPhase(original.getCompletedPhase());
798 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
801 * Config statements are not all that common which means we are performing a recursive search towards the root
802 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
803 * for the (usually non-existent) config statement.
806 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
807 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
810 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
811 * {@link #isIgnoringConfig(StatementContextBase)}.
813 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
814 final int fl = flags & SET_CONFIGURATION;
816 return fl == SET_CONFIGURATION;
818 if (isIgnoringConfig(parent)) {
819 // Note: SET_CONFIGURATION has been stored in flags
823 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
824 ConfigStatement.class);
825 final boolean isConfig;
826 if (configStatement != null) {
827 isConfig = configStatement.coerceStatementArgument();
829 // Validity check: if parent is config=false this cannot be a config=true
830 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
831 "Parent node has config=false, this node must not be specifed as config=true");
834 // If "config" statement is not specified, the default is the same as the parent's "config" value.
835 isConfig = parent.isConfiguration();
838 // Resolved, make sure we cache this return
839 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
843 protected abstract boolean isIgnoringConfig();
846 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
847 * keep on returning the same result without performing any lookups. Exists only to support
848 * {@link SubstatementContext#isIgnoringConfig()}.
851 * Note: use of this method implies that {@link #isConfiguration()} is realized with
852 * {@link #isConfiguration(StatementContextBase)}.
854 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
855 final int fl = flags & SET_IGNORE_CONFIG;
857 return fl == SET_IGNORE_CONFIG;
859 if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
860 flags |= SET_IGNORE_CONFIG;
864 flags |= HAVE_IGNORE_CONFIG;
868 protected abstract boolean isIgnoringIfFeatures();
871 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
872 * keep on returning the same result without performing any lookups. Exists only to support
873 * {@link SubstatementContext#isIgnoringIfFeatures()}.
875 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
876 final int fl = flags & SET_IGNORE_IF_FEATURE;
878 return fl == SET_IGNORE_IF_FEATURE;
880 if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
881 flags |= SET_IGNORE_IF_FEATURE;
885 flags |= HAVE_IGNORE_IF_FEATURE;
889 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
890 @Nullable final QNameModule targetModule) {
891 final Collection<? extends StatementContextBase<?, ?, ?>> declared = mutableDeclaredSubstatements();
892 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
894 for (final Mutable<?, ?, ?> stmtContext : declared) {
895 if (stmtContext.isSupportedByFeatures()) {
896 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
899 for (final Mutable<?, ?, ?> stmtContext : effective) {
900 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
903 target.addEffectiveSubstatements(buffer);
906 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
907 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
908 if (needToCopyByUses(stmtContext)) {
909 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
910 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
912 } else if (isReusedByUses(stmtContext)) {
913 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
914 buffer.add(stmtContext);
916 LOG.debug("Skipping statement {}", stmtContext);
920 // FIXME: revise this, as it seems to be wrong
921 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
922 YangStmtMapping.DESCRIPTION,
923 YangStmtMapping.REFERENCE,
924 YangStmtMapping.STATUS);
925 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
926 YangStmtMapping.TYPE,
927 YangStmtMapping.TYPEDEF,
928 YangStmtMapping.USES);
930 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
931 final StatementDefinition def = stmtContext.getPublicDefinition();
932 if (REUSED_DEF_SET.contains(def)) {
933 LOG.debug("Will reuse {} statement {}", def, stmtContext);
936 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
937 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
940 LOG.debug("Will copy {} statement {}", def, stmtContext);
944 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
945 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
949 public final String toString() {
950 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
953 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
954 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);