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 StmtContext<?, ?, ?> prevCopyCtx;
105 private final CopyHistory copyHistory;
106 private final String rawArgument;
108 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
109 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
110 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
111 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
112 private StatementMap substatements = StatementMap.empty();
114 private boolean isSupportedToBuildEffective = true;
115 private @Nullable ModelProcessingPhase completedPhase;
116 private @Nullable D declaredInstance;
117 private @Nullable E effectiveInstance;
119 // BooleanFields value
120 private byte supportedByFeatures;
122 private boolean fullyDefined;
124 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
125 final String rawArgument) {
126 this.definition = requireNonNull(def);
127 this.statementDeclSource = requireNonNull(ref);
128 this.rawArgument = def.internArgument(rawArgument);
129 this.copyHistory = CopyHistory.original();
130 this.originalCtx = null;
131 this.prevCopyCtx = null;
134 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
135 final String rawArgument, final CopyType copyType) {
136 this.definition = requireNonNull(def);
137 this.statementDeclSource = requireNonNull(ref);
138 this.rawArgument = rawArgument;
139 this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
140 this.originalCtx = null;
141 this.prevCopyCtx = null;
144 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
145 this.definition = original.definition;
146 this.statementDeclSource = original.statementDeclSource;
147 this.rawArgument = original.rawArgument;
148 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
149 this.originalCtx = original.getOriginalCtx().orElse(original);
150 this.prevCopyCtx = original;
153 StatementContextBase(final StatementContextBase<A, D, E> original) {
154 this.definition = original.definition;
155 this.statementDeclSource = original.statementDeclSource;
156 this.rawArgument = original.rawArgument;
157 this.copyHistory = original.getCopyHistory();
158 this.originalCtx = original.getOriginalCtx().orElse(original);
159 this.prevCopyCtx = original;
160 this.substatements = original.substatements;
161 this.effective = original.effective;
165 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
166 return effectOfStatement;
170 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
171 if (effectOfStatement.isEmpty()) {
172 effectOfStatement = new ArrayList<>(1);
174 effectOfStatement.add(ctx);
178 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
179 if (ctxs.isEmpty()) {
183 if (effectOfStatement.isEmpty()) {
184 effectOfStatement = new ArrayList<>(ctxs.size());
186 effectOfStatement.addAll(ctxs);
190 public boolean isSupportedByFeatures() {
191 if (OptionalBoolean.isPresent(supportedByFeatures)) {
192 return OptionalBoolean.get(supportedByFeatures);
195 if (isIgnoringIfFeatures()) {
196 supportedByFeatures = OptionalBoolean.of(true);
200 final boolean isParentSupported = isParentSupportedByFeatures();
202 * If parent is not supported, then this context is also not supported.
203 * So we do not need to check if-features statements of this context and
204 * we can return false immediately.
206 if (!isParentSupported) {
207 supportedByFeatures = OptionalBoolean.of(false);
212 * If parent is supported, we need to check if-features statements of
215 // If the set of supported features has not been provided, all features are supported by default.
216 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
217 SupportedFeatures.SUPPORTED_FEATURES);
218 final boolean ret = supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
219 supportedByFeatures = OptionalBoolean.of(ret);
223 protected abstract boolean isParentSupportedByFeatures();
225 protected abstract boolean isIgnoringIfFeatures();
227 protected abstract boolean isIgnoringConfig();
230 public boolean isSupportedToBuildEffective() {
231 return isSupportedToBuildEffective;
235 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
236 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
240 public CopyHistory getCopyHistory() {
245 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
246 return Optional.ofNullable(originalCtx);
250 public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
251 return Optional.ofNullable(prevCopyCtx);
255 public ModelProcessingPhase getCompletedPhase() {
256 return completedPhase;
260 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
261 this.completedPhase = completedPhase;
265 public abstract StatementContextBase<?, ?, ?> getParentContext();
268 * Returns the model root for this statement.
270 * @return root context of statement
273 public abstract RootStatementContext<?, ?, ?> getRoot();
276 * Returns the origin of the statement.
278 * @return origin of statement
281 public StatementSource getStatementSource() {
282 return statementDeclSource.getStatementSource();
286 * Returns a reference to statement source.
288 * @return reference of statement source
291 public StatementSourceReference getStatementSourceReference() {
292 return statementDeclSource;
296 public final String rawStatementArgument() {
301 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
302 return substatements.values();
306 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
307 return substatements.values();
311 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
312 return mutableEffectiveSubstatements();
316 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
317 if (effective instanceof ImmutableCollection) {
321 return Collections.unmodifiableCollection(effective);
325 * Remove a set of statements from effective statements.
327 * @param statements statements to be removed
328 * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
329 * It is no longer used in that capacity and slated for removal.
331 // FIXME: 5.0.0: remove this method
332 @Deprecated(forRemoval = true)
333 public void removeStatementsFromEffectiveSubstatements(
334 final Collection<? extends StmtContext<?, ?, ?>> statements) {
335 if (!effective.isEmpty()) {
336 effective.removeAll(statements);
341 private void shrinkEffective() {
342 if (effective.isEmpty()) {
343 effective = ImmutableList.of();
347 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
348 if (effective.isEmpty()) {
352 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
353 while (iterator.hasNext()) {
354 final StmtContext<?, ?, ?> next = iterator.next();
355 if (statementDef.equals(next.getPublicDefinition())) {
364 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
365 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
366 * definition and statement argument match with one of the effective substatements' statement definition
370 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
372 * @param statementDef statement definition of the statement context to remove
373 * @param statementArg statement argument of the statement context to remove
375 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
376 final String statementArg) {
377 if (statementArg == null) {
378 removeStatementFromEffectiveSubstatements(statementDef);
381 if (effective.isEmpty()) {
385 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
386 while (iterator.hasNext()) {
387 final Mutable<?, ?, ?> next = iterator.next();
388 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
397 * Adds an effective statement to collection of substatements.
399 * @param substatement substatement
400 * @throws IllegalStateException
401 * if added in declared phase
402 * @throws NullPointerException
403 * if statement parameter is null
405 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
406 beforeAddEffectiveStatement(1);
407 effective.add(substatement);
411 * Adds an effective statement to collection of substatements.
413 * @param statements substatements
414 * @throws IllegalStateException
415 * if added in declared phase
416 * @throws NullPointerException
417 * if statement parameter is null
419 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
420 if (statements.isEmpty()) {
424 statements.forEach(Objects::requireNonNull);
425 beforeAddEffectiveStatement(statements.size());
426 effective.addAll(statements);
429 private void beforeAddEffectiveStatement(final int toAdd) {
430 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
431 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
432 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
433 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
435 if (effective.isEmpty()) {
436 effective = new ArrayList<>(toAdd);
441 * Create a new substatement at the specified offset.
443 * @param offset Substatement offset
444 * @param def definition context
445 * @param ref source reference
446 * @param argument statement argument
447 * @param <X> new substatement argument type
448 * @param <Y> new substatement declared type
449 * @param <Z> new substatement effective type
450 * @return A new substatement
452 @SuppressWarnings("checkstyle:methodTypeParameterName")
453 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
454 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
455 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
456 final String argument) {
457 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
458 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
459 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
461 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
462 if (implicitParent.isPresent()) {
463 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
467 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
468 substatements = substatements.put(offset, ret);
469 def.onStatementAdded(ret);
473 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
474 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
475 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
476 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
479 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
480 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
481 ImplicitSubstatement.of(getStatementSourceReference()), null);
485 * Lookup substatement by its offset in this statement.
487 * @param offset Substatement offset
488 * @return Substatement, or null if substatement does not exist.
490 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
491 return substatements.get(offset);
494 final void setFullyDefined() {
495 this.fullyDefined = true;
498 final void resizeSubstatements(final int expectedSize) {
499 substatements = substatements.ensureCapacity(expectedSize);
502 final void walkChildren(final ModelProcessingPhase phase) {
503 checkState(fullyDefined);
504 substatements.values().forEach(stmt -> {
505 stmt.walkChildren(phase);
506 stmt.endDeclared(phase);
511 public D buildDeclared() {
512 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
513 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
514 if (declaredInstance == null) {
515 declaredInstance = definition().getFactory().createDeclared(this);
517 return declaredInstance;
521 public E buildEffective() {
522 if (effectiveInstance == null) {
523 effectiveInstance = definition().getFactory().createEffective(this);
525 return effectiveInstance;
529 * tries to execute current {@link ModelProcessingPhase} of source parsing.
532 * to be executed (completed)
533 * @return if phase was successfully completed
534 * @throws SourceException
535 * when an error occurred in source parsing
537 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
539 boolean finished = true;
540 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
541 if (!openMutations.isEmpty()) {
542 final Iterator<ContextMutation> it = openMutations.iterator();
543 while (it.hasNext()) {
544 final ContextMutation current = it.next();
545 if (current.isFinished()) {
552 if (openMutations.isEmpty()) {
553 phaseMutation.removeAll(phase);
554 if (phaseMutation.isEmpty()) {
555 phaseMutation = ImmutableMultimap.of();
560 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
561 finished &= child.tryToCompletePhase(phase);
563 for (final Mutable<?, ?, ?> child : effective) {
564 if (child instanceof StatementContextBase) {
565 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
570 onPhaseCompleted(phase);
577 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
580 * that was to be completed (finished)
581 * @throws SourceException
582 * when an error occurred in source parsing
584 private void onPhaseCompleted(final ModelProcessingPhase phase) {
585 completedPhase = phase;
587 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
588 if (listeners.isEmpty()) {
592 final Iterator<OnPhaseFinished> listener = listeners.iterator();
593 while (listener.hasNext()) {
594 final OnPhaseFinished next = listener.next();
595 if (next.phaseFinished(this, phase)) {
600 if (listeners.isEmpty()) {
601 phaseListeners.removeAll(phase);
602 if (phaseListeners.isEmpty()) {
603 phaseListeners = ImmutableMultimap.of();
609 * Ends declared section of current node.
611 void endDeclared(final ModelProcessingPhase phase) {
612 definition().onDeclarationFinished(this, phase);
616 * Return the context in which this statement was defined.
618 * @return statement definition
620 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
625 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
626 definition().checkNamespaceAllowed(type);
630 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
632 // definition().onNamespaceElementAdded(this, type, key, value);
635 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
636 final OnNamespaceItemAdded listener) {
637 final Object potential = getFromNamespace(type, key);
638 if (potential != null) {
639 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
640 listener.namespaceItemAdded(this, type, key, potential);
644 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
646 void onValueAdded(final Object value) {
647 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
652 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
653 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
654 final OnNamespaceItemAdded listener) {
655 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
656 if (existing.isPresent()) {
657 final Entry<K, V> entry = existing.get();
658 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
659 waitForPhase(entry.getValue(), type, phase, criterion, listener);
663 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
664 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
666 boolean onValueAdded(final K key, final V value) {
667 if (criterion.match(key)) {
668 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
669 waitForPhase(value, type, phase, criterion, listener);
678 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
679 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
680 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
681 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
683 final Entry<K, V> match = optMatch.get();
684 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
687 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
688 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
689 final OnNamespaceItemAdded listener) {
690 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
691 (context, phaseCompleted) -> {
692 selectMatch(type, criterion, listener);
697 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
698 final Class<N> type) {
699 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
700 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
703 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
707 * See {@link StatementSupport#getPublicView()}.
710 public StatementDefinition getPublicDefinition() {
711 return definition().getPublicView();
715 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
716 return getRoot().getSourceContext().newInferenceAction(phase);
719 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
720 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
724 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
725 * the listener is notified immediately.
727 * @param phase requested completion phase
728 * @param listener listener to invoke
729 * @throws NullPointerException if any of the arguments is null
731 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
732 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
733 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
735 ModelProcessingPhase finishedPhase = completedPhase;
736 while (finishedPhase != null) {
737 if (phase.equals(finishedPhase)) {
738 listener.phaseFinished(this, finishedPhase);
741 finishedPhase = finishedPhase.getPreviousPhase();
743 if (phaseListeners.isEmpty()) {
744 phaseListeners = newMultimap();
747 phaseListeners.put(phase, listener);
751 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
753 * @throws IllegalStateException
754 * when the mutation was registered after phase was completed
756 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
757 ModelProcessingPhase finishedPhase = completedPhase;
758 while (finishedPhase != null) {
759 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
760 getStatementSourceReference());
761 finishedPhase = finishedPhase.getPreviousPhase();
764 if (phaseMutation.isEmpty()) {
765 phaseMutation = newMultimap();
767 phaseMutation.put(phase, mutation);
771 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
772 final KT key,final StmtContext<?, ?, ?> stmt) {
773 addContextToNamespace(namespace, key, stmt);
777 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
778 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
779 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
780 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
782 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
784 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
785 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
786 original.getPublicDefinition());
788 final SubstatementContext<X, Y, Z> result;
789 final SubstatementContext<X, Y, Z> copy;
791 if (implicitParent.isPresent()) {
792 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
793 result = new SubstatementContext(this, def, original.getSourceReference(),
794 original.rawStatementArgument(), original.getStatementArgument(), type);
796 final CopyType childCopyType;
798 case ADDED_BY_AUGMENTATION:
799 childCopyType = CopyType.ORIGINAL;
801 case ADDED_BY_USES_AUGMENTATION:
802 childCopyType = CopyType.ADDED_BY_USES;
807 childCopyType = type;
810 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
811 result.addEffectiveSubstatement(copy);
812 original.definition().onStatementAdded(copy);
814 result = copy = new SubstatementContext<>(original, this, type, targetModule);
815 original.definition().onStatementAdded(copy);
818 original.copyTo(copy, type, targetModule);
823 public @NonNull StatementDefinition getDefinition() {
824 return getPublicDefinition();
828 public @NonNull StatementSourceReference getSourceReference() {
829 return getStatementSourceReference();
833 public boolean isFullyDefined() {
838 public final boolean hasImplicitParentSupport() {
839 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
843 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
844 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
845 original.getPublicDefinition());
846 if (optImplicit.isEmpty()) {
850 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
851 final CopyType type = original.getCopyHistory().getLastOperation();
852 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
853 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
856 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
857 result.setCompletedPhase(original.getCompletedPhase());
861 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
862 @Nullable final QNameModule targetModule) {
863 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
865 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
866 if (stmtContext.isSupportedByFeatures()) {
867 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
871 for (final Mutable<?, ?, ?> stmtContext : effective) {
872 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
875 target.addEffectiveSubstatements(buffer);
878 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
879 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
880 if (needToCopyByUses(stmtContext)) {
881 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
882 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
884 } else if (isReusedByUses(stmtContext)) {
885 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
886 buffer.add(stmtContext);
888 LOG.debug("Skipping statement {}", stmtContext);
892 // FIXME: revise this, as it seems to be wrong
893 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
894 YangStmtMapping.DESCRIPTION,
895 YangStmtMapping.REFERENCE,
896 YangStmtMapping.STATUS);
897 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
898 YangStmtMapping.TYPE,
899 YangStmtMapping.TYPEDEF,
900 YangStmtMapping.USES);
902 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
903 final StatementDefinition def = stmtContext.getPublicDefinition();
904 if (REUSED_DEF_SET.contains(def)) {
905 LOG.debug("Will reuse {} statement {}", def, stmtContext);
908 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
909 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
912 LOG.debug("Will copy {} statement {}", def, stmtContext);
916 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
917 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
921 public final String toString() {
922 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
925 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
926 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);