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.util.OptionalBoolean;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
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.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.ModelActionBuilder;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
60 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter.ResumedStatement;
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;
69 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
70 extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
72 * Event listener when an item is added to model namespace.
74 interface OnNamespaceItemAdded extends EventListener {
76 * Invoked whenever a new item is added to a namespace.
78 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
82 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
84 interface OnPhaseFinished extends EventListener {
86 * Invoked whenever a processing phase has finished.
88 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
92 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
94 interface ContextMutation {
99 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
101 private final @NonNull StatementDefinitionContext<A, D, E> definition;
102 private final @NonNull StatementSourceReference statementDeclSource;
103 private final StmtContext<?, ?, ?> originalCtx;
104 private final CopyHistory copyHistory;
105 private final String rawArgument;
107 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
108 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
109 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
110 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
111 private StatementMap substatements = StatementMap.empty();
113 private boolean isSupportedToBuildEffective = true;
114 private @Nullable ModelProcessingPhase completedPhase;
115 private @Nullable D declaredInstance;
116 private @Nullable E effectiveInstance;
118 // BooleanFields value
119 private byte supportedByFeatures;
121 private boolean fullyDefined;
123 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
124 final String rawArgument) {
125 this.definition = requireNonNull(def);
126 this.statementDeclSource = requireNonNull(ref);
127 this.rawArgument = def.internArgument(rawArgument);
128 this.copyHistory = CopyHistory.original();
129 this.originalCtx = null;
132 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
133 final String rawArgument, final CopyType copyType) {
134 this.definition = requireNonNull(def);
135 this.statementDeclSource = requireNonNull(ref);
136 this.rawArgument = rawArgument;
137 this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
138 this.originalCtx = null;
141 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
142 this.definition = original.definition;
143 this.statementDeclSource = original.statementDeclSource;
144 this.rawArgument = original.rawArgument;
145 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
146 this.originalCtx = original.getOriginalCtx().orElse(original);
149 StatementContextBase(final StatementContextBase<A, D, E> original) {
150 this.definition = original.definition;
151 this.statementDeclSource = original.statementDeclSource;
152 this.rawArgument = original.rawArgument;
153 this.copyHistory = original.getCopyHistory();
154 this.originalCtx = original.getOriginalCtx().orElse(original);
155 this.substatements = original.substatements;
156 this.effective = original.effective;
160 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
161 return effectOfStatement;
165 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
166 if (effectOfStatement.isEmpty()) {
167 effectOfStatement = new ArrayList<>(1);
169 effectOfStatement.add(ctx);
173 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
174 if (ctxs.isEmpty()) {
178 if (effectOfStatement.isEmpty()) {
179 effectOfStatement = new ArrayList<>(ctxs.size());
181 effectOfStatement.addAll(ctxs);
185 public boolean isSupportedByFeatures() {
186 if (OptionalBoolean.isPresent(supportedByFeatures)) {
187 return OptionalBoolean.get(supportedByFeatures);
190 if (isIgnoringIfFeatures()) {
191 supportedByFeatures = OptionalBoolean.of(true);
195 final boolean isParentSupported = isParentSupportedByFeatures();
197 * If parent is not supported, then this context is also not supported.
198 * So we do not need to check if-features statements of this context and
199 * we can return false immediately.
201 if (!isParentSupported) {
202 supportedByFeatures = OptionalBoolean.of(false);
207 * If parent is supported, we need to check if-features statements of
210 // If the set of supported features has not been provided, all features are supported by default.
211 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
212 SupportedFeatures.SUPPORTED_FEATURES);
213 final boolean ret = supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
214 supportedByFeatures = OptionalBoolean.of(ret);
218 protected abstract boolean isParentSupportedByFeatures();
220 protected abstract boolean isIgnoringIfFeatures();
222 protected abstract boolean isIgnoringConfig();
225 public boolean isSupportedToBuildEffective() {
226 return isSupportedToBuildEffective;
230 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
231 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
235 public CopyHistory getCopyHistory() {
240 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
241 return Optional.ofNullable(originalCtx);
245 public ModelProcessingPhase getCompletedPhase() {
246 return completedPhase;
250 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
251 this.completedPhase = completedPhase;
255 public abstract StatementContextBase<?, ?, ?> getParentContext();
258 * Returns the model root for this statement.
260 * @return root context of statement
263 public abstract RootStatementContext<?, ?, ?> getRoot();
266 * Returns the origin of the statement.
268 * @return origin of statement
271 public StatementSource getStatementSource() {
272 return statementDeclSource.getStatementSource();
276 * Returns a reference to statement source.
278 * @return reference of statement source
281 public StatementSourceReference getStatementSourceReference() {
282 return statementDeclSource;
286 public final String rawStatementArgument() {
291 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
292 return substatements.values();
296 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
297 return substatements.values();
301 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
302 return mutableEffectiveSubstatements();
306 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
307 if (effective instanceof ImmutableCollection) {
311 return Collections.unmodifiableCollection(effective);
314 public void removeStatementsFromEffectiveSubstatements(
315 final Collection<? extends StmtContext<?, ?, ?>> statements) {
316 if (!effective.isEmpty()) {
317 effective.removeAll(statements);
322 private void shrinkEffective() {
323 if (effective.isEmpty()) {
324 effective = ImmutableList.of();
328 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
329 if (effective.isEmpty()) {
333 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
334 while (iterator.hasNext()) {
335 final StmtContext<?, ?, ?> next = iterator.next();
336 if (statementDef.equals(next.getPublicDefinition())) {
345 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
346 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
347 * definition and statement argument match with one of the effective substatements' statement definition
351 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
353 * @param statementDef statement definition of the statement context to remove
354 * @param statementArg statement argument of the statement context to remove
356 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
357 final String statementArg) {
358 if (statementArg == null) {
359 removeStatementFromEffectiveSubstatements(statementDef);
362 if (effective.isEmpty()) {
366 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
367 while (iterator.hasNext()) {
368 final Mutable<?, ?, ?> next = iterator.next();
369 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
378 * Adds an effective statement to collection of substatements.
380 * @param substatement substatement
381 * @throws IllegalStateException
382 * if added in declared phase
383 * @throws NullPointerException
384 * if statement parameter is null
386 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
387 beforeAddEffectiveStatement(1);
388 effective.add(substatement);
392 * Adds an effective statement to collection of substatements.
394 * @param statements substatements
395 * @throws IllegalStateException
396 * if added in declared phase
397 * @throws NullPointerException
398 * if statement parameter is null
400 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
401 if (statements.isEmpty()) {
405 statements.forEach(Objects::requireNonNull);
406 beforeAddEffectiveStatement(statements.size());
407 effective.addAll(statements);
410 private void beforeAddEffectiveStatement(final int toAdd) {
411 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
412 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
413 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
414 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
416 if (effective.isEmpty()) {
417 effective = new ArrayList<>(toAdd);
422 * Create a new substatement at the specified offset.
424 * @param offset Substatement offset
425 * @param def definition context
426 * @param ref source reference
427 * @param argument statement argument
428 * @param <X> new substatement argument type
429 * @param <Y> new substatement declared type
430 * @param <Z> new substatement effective type
431 * @return A new substatement
433 @SuppressWarnings("checkstyle:methodTypeParameterName")
434 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
435 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
436 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
437 final String argument) {
438 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
439 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
440 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
442 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
443 if (implicitParent.isPresent()) {
444 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
448 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
449 substatements = substatements.put(offset, ret);
450 def.onStatementAdded(ret);
454 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
455 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
456 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
457 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
460 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
461 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
462 ImplicitSubstatement.of(getStatementSourceReference()), null);
466 * Lookup substatement by its offset in this statement.
468 * @param offset Substatement offset
469 * @return Substatement, or null if substatement does not exist.
471 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
472 return substatements.get(offset);
475 final void setFullyDefined() {
476 this.fullyDefined = true;
479 final void resizeSubstatements(final int expectedSize) {
480 substatements = substatements.ensureCapacity(expectedSize);
483 final void walkChildren(final ModelProcessingPhase phase) {
484 checkState(fullyDefined);
485 substatements.values().forEach(stmt -> {
486 stmt.walkChildren(phase);
487 stmt.endDeclared(phase);
492 public D buildDeclared() {
493 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
494 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
495 if (declaredInstance == null) {
496 declaredInstance = definition().getFactory().createDeclared(this);
498 return declaredInstance;
502 public E buildEffective() {
503 if (effectiveInstance == null) {
504 effectiveInstance = definition().getFactory().createEffective(this);
506 return effectiveInstance;
510 * tries to execute current {@link ModelProcessingPhase} of source parsing.
513 * to be executed (completed)
514 * @return if phase was successfully completed
515 * @throws SourceException
516 * when an error occurred in source parsing
518 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
520 boolean finished = true;
521 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
522 if (!openMutations.isEmpty()) {
523 final Iterator<ContextMutation> it = openMutations.iterator();
524 while (it.hasNext()) {
525 final ContextMutation current = it.next();
526 if (current.isFinished()) {
533 if (openMutations.isEmpty()) {
534 phaseMutation.removeAll(phase);
535 if (phaseMutation.isEmpty()) {
536 phaseMutation = ImmutableMultimap.of();
541 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
542 finished &= child.tryToCompletePhase(phase);
544 for (final Mutable<?, ?, ?> child : effective) {
545 if (child instanceof StatementContextBase) {
546 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
551 onPhaseCompleted(phase);
558 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
561 * that was to be completed (finished)
562 * @throws SourceException
563 * when an error occurred in source parsing
565 private void onPhaseCompleted(final ModelProcessingPhase phase) {
566 completedPhase = phase;
568 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
569 if (listeners.isEmpty()) {
573 final Iterator<OnPhaseFinished> listener = listeners.iterator();
574 while (listener.hasNext()) {
575 final OnPhaseFinished next = listener.next();
576 if (next.phaseFinished(this, phase)) {
581 if (listeners.isEmpty()) {
582 phaseListeners.removeAll(phase);
583 if (phaseListeners.isEmpty()) {
584 phaseListeners = ImmutableMultimap.of();
590 * Ends declared section of current node.
592 void endDeclared(final ModelProcessingPhase phase) {
593 definition().onDeclarationFinished(this, phase);
597 * Return the context in which this statement was defined.
599 * @return statement definition
601 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
606 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
607 definition().checkNamespaceAllowed(type);
611 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
613 // definition().onNamespaceElementAdded(this, type, key, value);
616 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
617 final OnNamespaceItemAdded listener) {
618 final Object potential = getFromNamespace(type, key);
619 if (potential != null) {
620 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
621 listener.namespaceItemAdded(this, type, key, potential);
625 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
627 void onValueAdded(final Object value) {
628 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
633 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
634 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
635 final OnNamespaceItemAdded listener) {
636 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
637 if (existing.isPresent()) {
638 final Entry<K, V> entry = existing.get();
639 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
640 waitForPhase(entry.getValue(), type, phase, criterion, listener);
644 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
645 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
647 boolean onValueAdded(final K key, final V value) {
648 if (criterion.match(key)) {
649 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
650 waitForPhase(value, type, phase, criterion, listener);
659 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
660 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
661 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
662 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
664 final Entry<K, V> match = optMatch.get();
665 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
668 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
669 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
670 final OnNamespaceItemAdded listener) {
671 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
672 (context, phaseCompleted) -> {
673 selectMatch(type, criterion, listener);
678 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
679 final Class<N> type) {
680 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
681 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
684 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
688 * See {@link StatementSupport#getPublicView()}.
691 public StatementDefinition getPublicDefinition() {
692 return definition().getPublicView();
696 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
697 return getRoot().getSourceContext().newInferenceAction(phase);
700 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
701 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
705 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
706 * the listener is notified immediately.
708 * @param phase requested completion phase
709 * @param listener listener to invoke
710 * @throws NullPointerException if any of the arguments is null
712 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
713 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
714 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
716 ModelProcessingPhase finishedPhase = completedPhase;
717 while (finishedPhase != null) {
718 if (phase.equals(finishedPhase)) {
719 listener.phaseFinished(this, finishedPhase);
722 finishedPhase = finishedPhase.getPreviousPhase();
724 if (phaseListeners.isEmpty()) {
725 phaseListeners = newMultimap();
728 phaseListeners.put(phase, listener);
732 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
734 * @throws IllegalStateException
735 * when the mutation was registered after phase was completed
737 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
738 ModelProcessingPhase finishedPhase = completedPhase;
739 while (finishedPhase != null) {
740 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
741 getStatementSourceReference());
742 finishedPhase = finishedPhase.getPreviousPhase();
745 if (phaseMutation.isEmpty()) {
746 phaseMutation = newMultimap();
748 phaseMutation.put(phase, mutation);
752 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
753 final KT key,final StmtContext<?, ?, ?> stmt) {
754 addContextToNamespace(namespace, key, stmt);
758 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
759 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
760 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
761 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
763 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
765 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
766 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
767 original.getPublicDefinition());
769 final SubstatementContext<X, Y, Z> result;
770 final SubstatementContext<X, Y, Z> copy;
772 if (implicitParent.isPresent()) {
773 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
774 result = new SubstatementContext(this, def, original.getSourceReference(),
775 original.rawStatementArgument(), original.getStatementArgument(), type);
777 final CopyType childCopyType;
779 case ADDED_BY_AUGMENTATION:
780 childCopyType = CopyType.ORIGINAL;
782 case ADDED_BY_USES_AUGMENTATION:
783 childCopyType = CopyType.ADDED_BY_USES;
788 childCopyType = type;
791 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
792 result.addEffectiveSubstatement(copy);
793 original.definition().onStatementAdded(copy);
795 result = copy = new SubstatementContext<>(original, this, type, targetModule);
796 original.definition().onStatementAdded(copy);
799 original.copyTo(copy, type, targetModule);
804 public @NonNull StatementDefinition getDefinition() {
805 return getPublicDefinition();
809 public @NonNull StatementSourceReference getSourceReference() {
810 return getStatementSourceReference();
814 public boolean isFullyDefined() {
819 public final boolean hasImplicitParentSupport() {
820 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
824 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
825 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
826 original.getPublicDefinition());
827 if (optImplicit.isEmpty()) {
831 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
832 final CopyType type = original.getCopyHistory().getLastOperation();
833 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
834 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
837 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
838 result.setCompletedPhase(original.getCompletedPhase());
842 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
843 @Nullable final QNameModule targetModule) {
844 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
846 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
847 if (stmtContext.isSupportedByFeatures()) {
848 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
852 for (final Mutable<?, ?, ?> stmtContext : effective) {
853 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
856 target.addEffectiveSubstatements(buffer);
859 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
860 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
861 if (needToCopyByUses(stmtContext)) {
862 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
863 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
865 } else if (isReusedByUses(stmtContext)) {
866 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
867 buffer.add(stmtContext);
869 LOG.debug("Skipping statement {}", stmtContext);
873 // FIXME: revise this, as it seems to be wrong
874 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
875 YangStmtMapping.DESCRIPTION,
876 YangStmtMapping.REFERENCE,
877 YangStmtMapping.STATUS);
878 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
879 YangStmtMapping.TYPE,
880 YangStmtMapping.TYPEDEF,
881 YangStmtMapping.USES);
883 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
884 final StatementDefinition def = stmtContext.getPublicDefinition();
885 if (REUSED_DEF_SET.contains(def)) {
886 LOG.debug("Will reuse {} statement {}", def, stmtContext);
889 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
890 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
893 LOG.debug("Will copy {} statement {}", def, stmtContext);
897 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
898 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
902 public final String toString() {
903 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
906 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
907 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);