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 ? true
214 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
216 supportedByFeatures = OptionalBoolean.of(ret);
220 protected abstract boolean isParentSupportedByFeatures();
222 protected abstract boolean isIgnoringIfFeatures();
224 protected abstract boolean isIgnoringConfig();
227 public boolean isSupportedToBuildEffective() {
228 return isSupportedToBuildEffective;
232 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
233 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
237 public CopyHistory getCopyHistory() {
242 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
243 return Optional.ofNullable(originalCtx);
247 public ModelProcessingPhase getCompletedPhase() {
248 return completedPhase;
252 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
253 this.completedPhase = completedPhase;
257 public abstract StatementContextBase<?, ?, ?> getParentContext();
260 * Returns the model root for this statement.
262 * @return root context of statement
265 public abstract RootStatementContext<?, ?, ?> getRoot();
268 * Returns the origin of the statement.
270 * @return origin of statement
273 public StatementSource getStatementSource() {
274 return statementDeclSource.getStatementSource();
278 * Returns a reference to statement source.
280 * @return reference of statement source
283 public StatementSourceReference getStatementSourceReference() {
284 return statementDeclSource;
288 public final String rawStatementArgument() {
293 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
294 return substatements.values();
298 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
299 return substatements.values();
303 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
304 return mutableEffectiveSubstatements();
308 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
309 if (effective instanceof ImmutableCollection) {
313 return Collections.unmodifiableCollection(effective);
316 public void removeStatementsFromEffectiveSubstatements(
317 final Collection<? extends StmtContext<?, ?, ?>> statements) {
318 if (!effective.isEmpty()) {
319 effective.removeAll(statements);
324 private void shrinkEffective() {
325 if (effective.isEmpty()) {
326 effective = ImmutableList.of();
330 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
331 if (effective.isEmpty()) {
335 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
336 while (iterator.hasNext()) {
337 final StmtContext<?, ?, ?> next = iterator.next();
338 if (statementDef.equals(next.getPublicDefinition())) {
347 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
348 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
349 * definition and statement argument match with one of the effective substatements' statement definition
353 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
355 * @param statementDef statement definition of the statement context to remove
356 * @param statementArg statement argument of the statement context to remove
358 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
359 final String statementArg) {
360 if (statementArg == null) {
361 removeStatementFromEffectiveSubstatements(statementDef);
364 if (effective.isEmpty()) {
368 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
369 while (iterator.hasNext()) {
370 final Mutable<?, ?, ?> next = iterator.next();
371 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
380 * Adds an effective statement to collection of substatements.
382 * @param substatement substatement
383 * @throws IllegalStateException
384 * if added in declared phase
385 * @throws NullPointerException
386 * if statement parameter is null
388 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
389 beforeAddEffectiveStatement(1);
390 effective.add(substatement);
394 * Adds an effective statement to collection of substatements.
396 * @param statements substatements
397 * @throws IllegalStateException
398 * if added in declared phase
399 * @throws NullPointerException
400 * if statement parameter is null
402 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
403 if (statements.isEmpty()) {
407 statements.forEach(Objects::requireNonNull);
408 beforeAddEffectiveStatement(statements.size());
409 effective.addAll(statements);
412 private void beforeAddEffectiveStatement(final int toAdd) {
413 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
414 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
415 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
416 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
418 if (effective.isEmpty()) {
419 effective = new ArrayList<>(toAdd);
424 * Create a new substatement at the specified offset.
426 * @param offset Substatement offset
427 * @param def definition context
428 * @param ref source reference
429 * @param argument statement argument
430 * @param <X> new substatement argument type
431 * @param <Y> new substatement declared type
432 * @param <Z> new substatement effective type
433 * @return A new substatement
435 @SuppressWarnings("checkstyle:methodTypeParameterName")
436 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
437 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
438 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
439 final String argument) {
440 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
441 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
442 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
444 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
445 if (implicitParent.isPresent()) {
446 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
450 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
451 substatements = substatements.put(offset, ret);
452 def.onStatementAdded(ret);
456 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
457 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
458 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
459 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
462 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
463 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
464 ImplicitSubstatement.of(getStatementSourceReference()), null);
468 * Lookup substatement by its offset in this statement.
470 * @param offset Substatement offset
471 * @return Substatement, or null if substatement does not exist.
473 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
474 return substatements.get(offset);
477 final void setFullyDefined() {
478 this.fullyDefined = true;
481 final void resizeSubstatements(final int expectedSize) {
482 substatements = substatements.ensureCapacity(expectedSize);
485 final void walkChildren(final ModelProcessingPhase phase) {
486 checkState(fullyDefined);
487 substatements.values().forEach(stmt -> {
488 stmt.walkChildren(phase);
489 stmt.endDeclared(phase);
494 public D buildDeclared() {
495 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
496 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
497 if (declaredInstance == null) {
498 declaredInstance = definition().getFactory().createDeclared(this);
500 return declaredInstance;
504 public E buildEffective() {
505 if (effectiveInstance == null) {
506 effectiveInstance = definition().getFactory().createEffective(this);
508 return effectiveInstance;
512 * tries to execute current {@link ModelProcessingPhase} of source parsing.
515 * to be executed (completed)
516 * @return if phase was successfully completed
517 * @throws SourceException
518 * when an error occurred in source parsing
520 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
522 boolean finished = true;
523 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
524 if (!openMutations.isEmpty()) {
525 final Iterator<ContextMutation> it = openMutations.iterator();
526 while (it.hasNext()) {
527 final ContextMutation current = it.next();
528 if (current.isFinished()) {
535 if (openMutations.isEmpty()) {
536 phaseMutation.removeAll(phase);
537 if (phaseMutation.isEmpty()) {
538 phaseMutation = ImmutableMultimap.of();
543 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
544 finished &= child.tryToCompletePhase(phase);
546 for (final Mutable<?, ?, ?> child : effective) {
547 if (child instanceof StatementContextBase) {
548 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
553 onPhaseCompleted(phase);
560 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
563 * that was to be completed (finished)
564 * @throws SourceException
565 * when an error occurred in source parsing
567 private void onPhaseCompleted(final ModelProcessingPhase phase) {
568 completedPhase = phase;
570 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
571 if (listeners.isEmpty()) {
575 final Iterator<OnPhaseFinished> listener = listeners.iterator();
576 while (listener.hasNext()) {
577 final OnPhaseFinished next = listener.next();
578 if (next.phaseFinished(this, phase)) {
583 if (listeners.isEmpty()) {
584 phaseListeners.removeAll(phase);
585 if (phaseListeners.isEmpty()) {
586 phaseListeners = ImmutableMultimap.of();
592 * Ends declared section of current node.
594 void endDeclared(final ModelProcessingPhase phase) {
595 definition().onDeclarationFinished(this, phase);
599 * Return the context in which this statement was defined.
601 * @return statement definition
603 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
608 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
609 definition().checkNamespaceAllowed(type);
613 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
615 // definition().onNamespaceElementAdded(this, type, key, value);
618 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
619 final OnNamespaceItemAdded listener) {
620 final Object potential = getFromNamespace(type, key);
621 if (potential != null) {
622 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
623 listener.namespaceItemAdded(this, type, key, potential);
627 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
629 void onValueAdded(final Object value) {
630 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
635 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
636 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
637 final OnNamespaceItemAdded listener) {
638 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
639 if (existing.isPresent()) {
640 final Entry<K, V> entry = existing.get();
641 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
642 waitForPhase(entry.getValue(), type, phase, criterion, listener);
646 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
647 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
649 boolean onValueAdded(final K key, final V value) {
650 if (criterion.match(key)) {
651 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
652 waitForPhase(value, type, phase, criterion, listener);
661 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
662 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
663 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
664 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
666 final Entry<K, V> match = optMatch.get();
667 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
670 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
671 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
672 final OnNamespaceItemAdded listener) {
673 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
674 (context, phaseCompleted) -> {
675 selectMatch(type, criterion, listener);
680 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
681 final Class<N> type) {
682 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
683 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
686 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
690 * See {@link StatementSupport#getPublicView()}.
693 public StatementDefinition getPublicDefinition() {
694 return definition().getPublicView();
698 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
699 return getRoot().getSourceContext().newInferenceAction(phase);
702 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
703 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
707 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
708 * the listener is notified immediately.
710 * @param phase requested completion phase
711 * @param listener listener to invoke
712 * @throws NullPointerException if any of the arguments is null
714 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
715 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
716 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
718 ModelProcessingPhase finishedPhase = completedPhase;
719 while (finishedPhase != null) {
720 if (phase.equals(finishedPhase)) {
721 listener.phaseFinished(this, finishedPhase);
724 finishedPhase = finishedPhase.getPreviousPhase();
726 if (phaseListeners.isEmpty()) {
727 phaseListeners = newMultimap();
730 phaseListeners.put(phase, listener);
734 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
736 * @throws IllegalStateException
737 * when the mutation was registered after phase was completed
739 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
740 ModelProcessingPhase finishedPhase = completedPhase;
741 while (finishedPhase != null) {
742 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
743 getStatementSourceReference());
744 finishedPhase = finishedPhase.getPreviousPhase();
747 if (phaseMutation.isEmpty()) {
748 phaseMutation = newMultimap();
750 phaseMutation.put(phase, mutation);
754 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
755 final KT key,final StmtContext<?, ?, ?> stmt) {
756 addContextToNamespace(namespace, key, stmt);
760 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
761 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
762 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
763 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
765 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
767 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
768 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
769 original.getPublicDefinition());
771 final SubstatementContext<X, Y, Z> result;
772 final SubstatementContext<X, Y, Z> copy;
774 if (implicitParent.isPresent()) {
775 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
776 result = new SubstatementContext(this, def, original.getSourceReference(),
777 original.rawStatementArgument(), original.getStatementArgument(), type);
779 final CopyType childCopyType;
781 case ADDED_BY_AUGMENTATION:
782 childCopyType = CopyType.ORIGINAL;
784 case ADDED_BY_USES_AUGMENTATION:
785 childCopyType = CopyType.ADDED_BY_USES;
790 childCopyType = type;
793 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
794 result.addEffectiveSubstatement(copy);
795 original.definition().onStatementAdded(copy);
797 result = copy = new SubstatementContext<>(original, this, type, targetModule);
798 original.definition().onStatementAdded(copy);
801 original.copyTo(copy, type, targetModule);
806 public @NonNull StatementDefinition getDefinition() {
807 return getPublicDefinition();
811 public @NonNull StatementSourceReference getSourceReference() {
812 return getStatementSourceReference();
816 public boolean isFullyDefined() {
821 public final boolean hasImplicitParentSupport() {
822 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
826 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
827 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
828 original.getPublicDefinition());
829 if (!optImplicit.isPresent()) {
833 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
834 final CopyType type = original.getCopyHistory().getLastOperation();
835 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
836 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
839 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
840 result.setCompletedPhase(original.getCompletedPhase());
844 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
845 @Nullable final QNameModule targetModule) {
846 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
848 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
849 if (stmtContext.isSupportedByFeatures()) {
850 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
854 for (final Mutable<?, ?, ?> stmtContext : effective) {
855 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
858 target.addEffectiveSubstatements(buffer);
861 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
862 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
863 if (needToCopyByUses(stmtContext)) {
864 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
865 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
867 } else if (isReusedByUses(stmtContext)) {
868 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
869 buffer.add(stmtContext);
871 LOG.debug("Skipping statement {}", stmtContext);
875 // FIXME: revise this, as it seems to be wrong
876 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
877 YangStmtMapping.DESCRIPTION,
878 YangStmtMapping.REFERENCE,
879 YangStmtMapping.STATUS);
880 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
881 YangStmtMapping.TYPE,
882 YangStmtMapping.TYPEDEF,
883 YangStmtMapping.USES);
885 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
886 final StatementDefinition def = stmtContext.getPublicDefinition();
887 if (REUSED_DEF_SET.contains(def)) {
888 LOG.debug("Will reuse {} statement {}", def, stmtContext);
891 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
892 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
895 LOG.debug("Will copy {} statement {}", def, stmtContext);
899 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
900 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
904 public final String toString() {
905 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
908 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
909 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);