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.base.MoreObjects;
16 import com.google.common.base.MoreObjects.ToStringHelper;
17 import com.google.common.collect.ImmutableCollection;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMultimap;
20 import com.google.common.collect.ImmutableSet;
21 import com.google.common.collect.Multimap;
22 import com.google.common.collect.Multimaps;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.EventListener;
28 import java.util.Iterator;
29 import java.util.Map.Entry;
30 import java.util.Objects;
31 import java.util.Optional;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.util.OptionalBoolean;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
39 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
40 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
42 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
43 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
56 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter.ResumedStatement;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
61 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
62 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
67 extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
69 * Event listener when an item is added to model namespace.
71 interface OnNamespaceItemAdded extends EventListener {
73 * Invoked whenever a new item is added to a namespace.
75 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
79 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
81 interface OnPhaseFinished extends EventListener {
83 * Invoked whenever a processing phase has finished.
85 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
89 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
91 interface ContextMutation {
96 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
98 private final @NonNull StatementDefinitionContext<A, D, E> definition;
99 private final @NonNull StatementSourceReference statementDeclSource;
100 private final StmtContext<?, ?, ?> originalCtx;
101 private final CopyHistory copyHistory;
102 private final String rawArgument;
104 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
105 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
106 private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
107 private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
108 private StatementMap substatements = StatementMap.empty();
110 private boolean isSupportedToBuildEffective = true;
111 private @Nullable ModelProcessingPhase completedPhase;
112 private @Nullable D declaredInstance;
113 private @Nullable E effectiveInstance;
115 // BooleanFields value
116 private byte supportedByFeatures;
118 private boolean fullyDefined;
120 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
121 final String rawArgument) {
122 this.definition = requireNonNull(def);
123 this.statementDeclSource = requireNonNull(ref);
124 this.rawArgument = def.internArgument(rawArgument);
125 this.copyHistory = CopyHistory.original();
126 this.originalCtx = null;
129 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
130 this.definition = original.definition;
131 this.statementDeclSource = original.statementDeclSource;
132 this.rawArgument = original.rawArgument;
133 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
134 this.originalCtx = original.getOriginalCtx().orElse(original);
138 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
139 return effectOfStatement;
143 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
144 if (effectOfStatement.isEmpty()) {
145 effectOfStatement = new ArrayList<>(1);
147 effectOfStatement.add(ctx);
151 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
152 if (ctxs.isEmpty()) {
156 if (effectOfStatement.isEmpty()) {
157 effectOfStatement = new ArrayList<>(ctxs.size());
159 effectOfStatement.addAll(ctxs);
163 public boolean isSupportedByFeatures() {
164 if (OptionalBoolean.isPresent(supportedByFeatures)) {
165 return OptionalBoolean.get(supportedByFeatures);
168 if (isIgnoringIfFeatures()) {
169 supportedByFeatures = OptionalBoolean.of(true);
173 final boolean isParentSupported = isParentSupportedByFeatures();
175 * If parent is not supported, then this context is also not supported.
176 * So we do not need to check if-features statements of this context and
177 * we can return false immediately.
179 if (!isParentSupported) {
180 supportedByFeatures = OptionalBoolean.of(false);
185 * If parent is supported, we need to check if-features statements of
188 // If the set of supported features has not been provided, all features are supported by default.
189 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
190 SupportedFeatures.SUPPORTED_FEATURES);
191 final boolean ret = supportedFeatures == null ? true
192 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
194 supportedByFeatures = OptionalBoolean.of(ret);
198 protected abstract boolean isParentSupportedByFeatures();
200 protected abstract boolean isIgnoringIfFeatures();
202 protected abstract boolean isIgnoringConfig();
205 public boolean isSupportedToBuildEffective() {
206 return isSupportedToBuildEffective;
210 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
211 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
215 public CopyHistory getCopyHistory() {
220 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
221 return Optional.ofNullable(originalCtx);
225 public ModelProcessingPhase getCompletedPhase() {
226 return completedPhase;
230 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
231 this.completedPhase = completedPhase;
235 public abstract StatementContextBase<?, ?, ?> getParentContext();
238 * Returns the model root for this statement.
240 * @return root context of statement
243 public abstract RootStatementContext<?, ?, ?> getRoot();
246 * Returns the origin of the statement.
248 * @return origin of statement
251 public StatementSource getStatementSource() {
252 return statementDeclSource.getStatementSource();
256 * Returns a reference to statement source.
258 * @return reference of statement source
261 public StatementSourceReference getStatementSourceReference() {
262 return statementDeclSource;
266 public final String rawStatementArgument() {
271 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
272 return substatements.values();
276 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
277 return substatements.values();
281 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
282 return mutableEffectiveSubstatements();
286 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
287 if (effective instanceof ImmutableCollection) {
291 return Collections.unmodifiableCollection(effective);
294 public void removeStatementsFromEffectiveSubstatements(
295 final Collection<? extends StmtContext<?, ?, ?>> statements) {
296 if (!effective.isEmpty()) {
297 effective.removeAll(statements);
302 private void shrinkEffective() {
303 if (effective.isEmpty()) {
304 effective = ImmutableList.of();
308 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
309 if (effective.isEmpty()) {
313 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
314 while (iterator.hasNext()) {
315 final StmtContext<?, ?, ?> next = iterator.next();
316 if (statementDef.equals(next.getPublicDefinition())) {
325 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
326 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
327 * definition and statement argument match with one of the effective substatements' statement definition
331 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
333 * @param statementDef statement definition of the statement context to remove
334 * @param statementArg statement argument of the statement context to remove
336 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
337 final String statementArg) {
338 if (statementArg == null) {
339 removeStatementFromEffectiveSubstatements(statementDef);
342 if (effective.isEmpty()) {
346 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
347 while (iterator.hasNext()) {
348 final Mutable<?, ?, ?> next = iterator.next();
349 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
358 * Adds an effective statement to collection of substatements.
360 * @param substatement substatement
361 * @throws IllegalStateException
362 * if added in declared phase
363 * @throws NullPointerException
364 * if statement parameter is null
366 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
367 beforeAddEffectiveStatement(1);
368 effective.add(substatement);
372 * Adds an effective statement to collection of substatements.
374 * @param statements substatements
375 * @throws IllegalStateException
376 * if added in declared phase
377 * @throws NullPointerException
378 * if statement parameter is null
380 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
381 if (statements.isEmpty()) {
385 statements.forEach(Objects::requireNonNull);
386 beforeAddEffectiveStatement(statements.size());
387 effective.addAll(statements);
390 private void beforeAddEffectiveStatement(final int toAdd) {
391 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
392 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
393 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
394 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
396 if (effective.isEmpty()) {
397 effective = new ArrayList<>(toAdd);
402 * Create a new substatement at the specified offset.
404 * @param offset Substatement offset
405 * @param def definition context
406 * @param ref source reference
407 * @param argument statement argument
408 * @param <X> new substatement argument type
409 * @param <Y> new substatement declared type
410 * @param <Z> new substatement effective type
411 * @return A new substatement
413 @SuppressWarnings("checkstyle:methodTypeParameterName")
414 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
415 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
416 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
417 final String argument) {
418 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
419 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
420 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
422 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
423 if (implicitParent.isPresent()) {
424 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
428 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
429 substatements = substatements.put(offset, ret);
430 def.onStatementAdded(ret);
434 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
435 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
436 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
437 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
440 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
441 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
442 ImplicitSubstatement.of(getStatementSourceReference()), null);
446 * Lookup substatement by its offset in this statement.
448 * @param offset Substatement offset
449 * @return Substatement, or null if substatement does not exist.
451 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
452 return substatements.get(offset);
455 final void setFullyDefined() {
456 this.fullyDefined = true;
459 final void resizeSubstatements(final int expectedSize) {
460 substatements = substatements.ensureCapacity(expectedSize);
463 final void walkChildren(final ModelProcessingPhase phase) {
464 checkState(fullyDefined);
465 substatements.values().forEach(stmt -> {
466 stmt.walkChildren(phase);
467 stmt.endDeclared(phase);
472 public D buildDeclared() {
473 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
474 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
475 if (declaredInstance == null) {
476 declaredInstance = definition().getFactory().createDeclared(this);
478 return declaredInstance;
482 public E buildEffective() {
483 if (effectiveInstance == null) {
484 effectiveInstance = definition().getFactory().createEffective(this);
486 return effectiveInstance;
490 * tries to execute current {@link ModelProcessingPhase} of source parsing.
493 * to be executed (completed)
494 * @return if phase was successfully completed
495 * @throws SourceException
496 * when an error occurred in source parsing
498 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
500 boolean finished = true;
501 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
502 if (!openMutations.isEmpty()) {
503 final Iterator<ContextMutation> it = openMutations.iterator();
504 while (it.hasNext()) {
505 final ContextMutation current = it.next();
506 if (current.isFinished()) {
513 if (openMutations.isEmpty()) {
514 phaseMutation.removeAll(phase);
515 if (phaseMutation.isEmpty()) {
516 phaseMutation = ImmutableMultimap.of();
521 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
522 finished &= child.tryToCompletePhase(phase);
524 for (final Mutable<?, ?, ?> child : effective) {
525 if (child instanceof StatementContextBase) {
526 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
531 onPhaseCompleted(phase);
538 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
541 * that was to be completed (finished)
542 * @throws SourceException
543 * when an error occurred in source parsing
545 private void onPhaseCompleted(final ModelProcessingPhase phase) {
546 completedPhase = phase;
548 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
549 if (listeners.isEmpty()) {
553 final Iterator<OnPhaseFinished> listener = listeners.iterator();
554 while (listener.hasNext()) {
555 final OnPhaseFinished next = listener.next();
556 if (next.phaseFinished(this, phase)) {
561 if (listeners.isEmpty()) {
562 phaseListeners.removeAll(phase);
563 if (phaseListeners.isEmpty()) {
564 phaseListeners = ImmutableMultimap.of();
570 * Ends declared section of current node.
572 void endDeclared(final ModelProcessingPhase phase) {
573 definition().onDeclarationFinished(this, phase);
577 * Return the context in which this statement was defined.
579 * @return statement definition
581 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
586 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
587 definition().checkNamespaceAllowed(type);
591 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
593 // definition().onNamespaceElementAdded(this, type, key, value);
596 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
597 final OnNamespaceItemAdded listener) {
598 final Object potential = getFromNamespace(type, key);
599 if (potential != null) {
600 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
601 listener.namespaceItemAdded(this, type, key, potential);
605 getBehaviour(type).addListener(new KeyedValueAddedListener<K>(this, key) {
607 void onValueAdded(final Object value) {
608 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
613 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
614 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
615 final OnNamespaceItemAdded listener) {
616 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
617 if (existing.isPresent()) {
618 final Entry<K, V> entry = existing.get();
619 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
620 waitForPhase(entry.getValue(), type, phase, criterion, listener);
624 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
625 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
627 boolean onValueAdded(final K key, final V value) {
628 if (criterion.match(key)) {
629 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
630 waitForPhase(value, type, phase, criterion, listener);
639 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
640 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
641 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
642 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
644 final Entry<K, V> match = optMatch.get();
645 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
648 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
649 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
650 final OnNamespaceItemAdded listener) {
651 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
652 (context, phaseCompleted) -> {
653 selectMatch(type, criterion, listener);
658 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
659 final Class<N> type) {
660 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
661 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
664 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
668 * See {@link StatementSupport#getPublicView()}.
671 public StatementDefinition getPublicDefinition() {
672 return definition().getPublicView();
676 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
677 return getRoot().getSourceContext().newInferenceAction(phase);
680 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
681 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
685 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
686 * the listener is notified immediately.
688 * @param phase requested completion phase
689 * @param listener listener to invoke
690 * @throws NullPointerException if any of the arguments is null
692 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
693 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
694 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
696 ModelProcessingPhase finishedPhase = completedPhase;
697 while (finishedPhase != null) {
698 if (phase.equals(finishedPhase)) {
699 listener.phaseFinished(this, finishedPhase);
702 finishedPhase = finishedPhase.getPreviousPhase();
704 if (phaseListeners.isEmpty()) {
705 phaseListeners = newMultimap();
708 phaseListeners.put(phase, listener);
712 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
714 * @throws IllegalStateException
715 * when the mutation was registered after phase was completed
717 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
718 ModelProcessingPhase finishedPhase = completedPhase;
719 while (finishedPhase != null) {
720 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
721 getStatementSourceReference());
722 finishedPhase = finishedPhase.getPreviousPhase();
725 if (phaseMutation.isEmpty()) {
726 phaseMutation = newMultimap();
728 phaseMutation.put(phase, mutation);
732 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
733 final KT key,final StmtContext<?, ?, ?> stmt) {
734 addContextToNamespace(namespace, key, stmt);
738 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
739 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
740 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
741 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
743 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
745 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
746 final SubstatementContext<X, Y, Z> copy = new SubstatementContext<>(original, this, type, targetModule);
748 original.definition().onStatementAdded(copy);
749 original.copyTo(copy, type, targetModule);
756 public @NonNull StatementDefinition getDefinition() {
757 return getPublicDefinition();
761 public @NonNull StatementSourceReference getSourceReference() {
762 return getStatementSourceReference();
766 public boolean isFullyDefined() {
770 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
771 @Nullable final QNameModule targetModule) {
772 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
774 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
775 if (stmtContext.isSupportedByFeatures()) {
776 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
780 for (final Mutable<?, ?, ?> stmtContext : effective) {
781 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
784 target.addEffectiveSubstatements(buffer);
787 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
788 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
789 if (needToCopyByUses(stmtContext)) {
790 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
791 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
793 } else if (isReusedByUses(stmtContext)) {
794 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
795 buffer.add(stmtContext);
797 LOG.debug("Skipping statement {}", stmtContext);
801 // FIXME: revise this, as it seems to be wrong
802 private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
803 YangStmtMapping.DESCRIPTION,
804 YangStmtMapping.REFERENCE,
805 YangStmtMapping.STATUS);
806 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
807 YangStmtMapping.TYPE,
808 YangStmtMapping.TYPEDEF,
809 YangStmtMapping.USES);
811 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
812 final StatementDefinition def = stmtContext.getPublicDefinition();
813 if (REUSED_DEF_SET.contains(def)) {
814 LOG.debug("Will reuse {} statement {}", def, stmtContext);
817 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
818 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
821 LOG.debug("Will copy {} statement {}", def, stmtContext);
825 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
826 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
830 public final String toString() {
831 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
834 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
835 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);