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);
327 private void shrinkEffective() {
328 if (effective.isEmpty()) {
329 effective = ImmutableList.of();
333 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
334 if (effective.isEmpty()) {
338 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
339 while (iterator.hasNext()) {
340 final StmtContext<?, ?, ?> next = iterator.next();
341 if (statementDef.equals(next.getPublicDefinition())) {
350 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
351 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
352 * definition and statement argument match with one of the effective substatements' statement definition
356 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
358 * @param statementDef statement definition of the statement context to remove
359 * @param statementArg statement argument of the statement context to remove
361 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
362 final String statementArg) {
363 if (statementArg == null) {
364 removeStatementFromEffectiveSubstatements(statementDef);
367 if (effective.isEmpty()) {
371 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
372 while (iterator.hasNext()) {
373 final Mutable<?, ?, ?> next = iterator.next();
374 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
382 // YANG example: RPC/action statements always have 'input' and 'output' defined
384 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
385 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
386 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
387 // StatementContextBase subclass.
388 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
389 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
390 support.onStatementAdded(ret);
391 addEffectiveSubstatement(ret);
396 * Adds an effective statement to collection of substatements.
398 * @param substatement substatement
399 * @throws IllegalStateException
400 * if added in declared phase
401 * @throws NullPointerException
402 * if statement parameter is null
404 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
405 beforeAddEffectiveStatement(1);
406 effective.add(substatement);
410 * Adds an effective statement to collection of substatements.
412 * @param statements substatements
413 * @throws IllegalStateException
414 * if added in declared phase
415 * @throws NullPointerException
416 * if statement parameter is null
418 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
419 if (statements.isEmpty()) {
423 statements.forEach(Objects::requireNonNull);
424 beforeAddEffectiveStatement(statements.size());
425 effective.addAll(statements);
428 private void beforeAddEffectiveStatement(final int toAdd) {
429 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
430 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
431 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
432 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
434 if (effective.isEmpty()) {
435 effective = new ArrayList<>(toAdd);
439 // Exists only due to memory optimization
440 final boolean fullyDefined() {
444 // Exists only due to memory optimization, should live in AbstractResumedStatement
445 final void setFullyDefined() {
450 public D buildDeclared() {
451 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
452 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
453 if (declaredInstance == null) {
454 declaredInstance = definition().getFactory().createDeclared(this);
456 return declaredInstance;
460 public E buildEffective() {
461 if (effectiveInstance == null) {
462 effectiveInstance = definition().getFactory().createEffective(this);
464 return effectiveInstance;
468 * tries to execute current {@link ModelProcessingPhase} of source parsing.
471 * to be executed (completed)
472 * @return if phase was successfully completed
473 * @throws SourceException
474 * when an error occurred in source parsing
476 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
478 boolean finished = true;
479 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
480 if (!openMutations.isEmpty()) {
481 final Iterator<ContextMutation> it = openMutations.iterator();
482 while (it.hasNext()) {
483 final ContextMutation current = it.next();
484 if (current.isFinished()) {
491 if (openMutations.isEmpty()) {
492 phaseMutation.removeAll(phase);
493 if (phaseMutation.isEmpty()) {
494 phaseMutation = ImmutableMultimap.of();
499 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
500 finished &= child.tryToCompletePhase(phase);
502 for (final Mutable<?, ?, ?> child : effective) {
503 if (child instanceof StatementContextBase) {
504 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
509 onPhaseCompleted(phase);
516 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
519 * that was to be completed (finished)
520 * @throws SourceException
521 * when an error occurred in source parsing
523 private void onPhaseCompleted(final ModelProcessingPhase phase) {
524 completedPhase = phase;
526 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
527 if (listeners.isEmpty()) {
531 final Iterator<OnPhaseFinished> listener = listeners.iterator();
532 while (listener.hasNext()) {
533 final OnPhaseFinished next = listener.next();
534 if (next.phaseFinished(this, phase)) {
539 if (listeners.isEmpty()) {
540 phaseListeners.removeAll(phase);
541 if (phaseListeners.isEmpty()) {
542 phaseListeners = ImmutableMultimap.of();
548 * Ends declared section of current node.
550 void endDeclared(final ModelProcessingPhase phase) {
551 definition().onDeclarationFinished(this, phase);
555 * Return the context in which this statement was defined.
557 * @return statement definition
559 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
564 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
565 definition().checkNamespaceAllowed(type);
569 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
571 // definition().onNamespaceElementAdded(this, type, key, value);
574 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
575 final OnNamespaceItemAdded listener) {
576 final Object potential = getFromNamespace(type, key);
577 if (potential != null) {
578 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
579 listener.namespaceItemAdded(this, type, key, potential);
583 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
585 void onValueAdded(final Object value) {
586 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
591 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
592 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
593 final OnNamespaceItemAdded listener) {
594 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
595 if (existing.isPresent()) {
596 final Entry<K, V> entry = existing.get();
597 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
598 waitForPhase(entry.getValue(), type, phase, criterion, listener);
602 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
603 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
605 boolean onValueAdded(final K key, final V value) {
606 if (criterion.match(key)) {
607 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
608 waitForPhase(value, type, phase, criterion, listener);
617 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
618 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
619 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
620 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
622 final Entry<K, V> match = optMatch.get();
623 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
626 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
627 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
628 final OnNamespaceItemAdded listener) {
629 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
630 (context, phaseCompleted) -> {
631 selectMatch(type, criterion, listener);
636 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
637 final Class<N> type) {
638 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
639 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
642 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
646 public StatementDefinition getPublicDefinition() {
647 return definition().getPublicView();
651 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
652 return getRoot().getSourceContext().newInferenceAction(phase);
655 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
656 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
660 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
661 * the listener is notified immediately.
663 * @param phase requested completion phase
664 * @param listener listener to invoke
665 * @throws NullPointerException if any of the arguments is null
667 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
668 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
669 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
671 ModelProcessingPhase finishedPhase = completedPhase;
672 while (finishedPhase != null) {
673 if (phase.equals(finishedPhase)) {
674 listener.phaseFinished(this, finishedPhase);
677 finishedPhase = finishedPhase.getPreviousPhase();
679 if (phaseListeners.isEmpty()) {
680 phaseListeners = newMultimap();
683 phaseListeners.put(phase, listener);
687 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
689 * @throws IllegalStateException
690 * when the mutation was registered after phase was completed
692 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
693 ModelProcessingPhase finishedPhase = completedPhase;
694 while (finishedPhase != null) {
695 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
696 getStatementSourceReference());
697 finishedPhase = finishedPhase.getPreviousPhase();
700 if (phaseMutation.isEmpty()) {
701 phaseMutation = newMultimap();
703 phaseMutation.put(phase, mutation);
707 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
708 final KT key,final StmtContext<?, ?, ?> stmt) {
709 addContextToNamespace(namespace, key, stmt);
713 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
714 final QNameModule targetModule) {
715 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
716 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
717 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
718 return childCopyOf((SubstatementContext<?, ?, ?>) stmt, type, targetModule);
721 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
722 final SubstatementContext<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
723 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
724 original.getPublicDefinition());
726 final SubstatementContext<X, Y, Z> result;
727 final SubstatementContext<X, Y, Z> copy;
729 if (implicitParent.isPresent()) {
730 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
731 result = new SubstatementContext(this, def, original.getStatementSourceReference(),
732 original.rawStatementArgument(), original.getStatementArgument(), type);
734 final CopyType childCopyType;
736 case ADDED_BY_AUGMENTATION:
737 childCopyType = CopyType.ORIGINAL;
739 case ADDED_BY_USES_AUGMENTATION:
740 childCopyType = CopyType.ADDED_BY_USES;
745 childCopyType = type;
748 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
749 result.addEffectiveSubstatement(copy);
751 result = copy = new SubstatementContext<>(original, this, type, targetModule);
754 original.definition().onStatementAdded(copy);
755 original.copyTo(copy, type, targetModule);
760 public final boolean hasImplicitParentSupport() {
761 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
765 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
766 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
767 original.getPublicDefinition());
768 if (optImplicit.isEmpty()) {
772 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
773 final CopyType type = original.getCopyHistory().getLastOperation();
774 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
775 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
778 result.addEffectiveSubstatement(original.reparent(result));
779 result.setCompletedPhase(original.getCompletedPhase());
783 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
786 * Config statements are not all that common which means we are performing a recursive search towards the root
787 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
788 * for the (usually non-existent) config statement.
791 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
792 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
795 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
796 * {@link #isIgnoringConfig(StatementContextBase)}.
798 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
799 final int fl = flags & SET_CONFIGURATION;
801 return fl == SET_CONFIGURATION;
803 if (isIgnoringConfig(parent)) {
804 // Note: SET_CONFIGURATION has been stored in flags
808 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
809 ConfigStatement.class);
810 final boolean isConfig;
811 if (configStatement != null) {
812 isConfig = configStatement.coerceStatementArgument();
814 // Validity check: if parent is config=false this cannot be a config=true
815 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
816 "Parent node has config=false, this node must not be specifed as config=true");
819 // If "config" statement is not specified, the default is the same as the parent's "config" value.
820 isConfig = parent.isConfiguration();
823 // Resolved, make sure we cache this return
824 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
828 protected abstract boolean isIgnoringConfig();
831 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
832 * keep on returning the same result without performing any lookups. Exists only to support
833 * {@link SubstatementContext#isIgnoringConfig()}.
836 * Note: use of this method implies that {@link #isConfiguration()} is realized with
837 * {@link #isConfiguration(StatementContextBase)}.
839 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
840 final int fl = flags & SET_IGNORE_CONFIG;
842 return fl == SET_IGNORE_CONFIG;
844 if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
845 flags |= SET_IGNORE_CONFIG;
849 flags |= HAVE_IGNORE_CONFIG;
853 protected abstract boolean isIgnoringIfFeatures();
856 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
857 * keep on returning the same result without performing any lookups. Exists only to support
858 * {@link SubstatementContext#isIgnoringIfFeatures()}.
860 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
861 final int fl = flags & SET_IGNORE_IF_FEATURE;
863 return fl == SET_IGNORE_IF_FEATURE;
865 if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
866 flags |= SET_IGNORE_IF_FEATURE;
870 flags |= HAVE_IGNORE_IF_FEATURE;
874 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
875 @Nullable final QNameModule targetModule) {
876 final Collection<? extends StatementContextBase<?, ?, ?>> declared = mutableDeclaredSubstatements();
877 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
879 for (final Mutable<?, ?, ?> stmtContext : declared) {
880 if (stmtContext.isSupportedByFeatures()) {
881 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
884 for (final Mutable<?, ?, ?> stmtContext : effective) {
885 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
888 target.addEffectiveSubstatements(buffer);
891 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
892 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
893 if (needToCopyByUses(stmtContext)) {
894 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
895 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
897 } else if (isReusedByUses(stmtContext)) {
898 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
899 buffer.add(stmtContext);
901 LOG.debug("Skipping statement {}", stmtContext);
905 // FIXME: revise this, as it seems to be wrong
906 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
907 YangStmtMapping.DESCRIPTION,
908 YangStmtMapping.REFERENCE,
909 YangStmtMapping.STATUS);
910 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
911 YangStmtMapping.TYPE,
912 YangStmtMapping.TYPEDEF,
913 YangStmtMapping.USES);
915 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
916 final StatementDefinition def = stmtContext.getPublicDefinition();
917 if (REUSED_DEF_SET.contains(def)) {
918 LOG.debug("Will reuse {} statement {}", def, stmtContext);
921 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
922 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
925 LOG.debug("Will copy {} statement {}", def, stmtContext);
929 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
930 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
934 public final String toString() {
935 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
938 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
939 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);