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);
324 public void removeStatementsFromEffectiveSubstatements(
325 final Collection<? extends StmtContext<?, ?, ?>> statements) {
326 if (!effective.isEmpty()) {
327 effective.removeAll(statements);
332 private void shrinkEffective() {
333 if (effective.isEmpty()) {
334 effective = ImmutableList.of();
338 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
339 if (effective.isEmpty()) {
343 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
344 while (iterator.hasNext()) {
345 final StmtContext<?, ?, ?> next = iterator.next();
346 if (statementDef.equals(next.getPublicDefinition())) {
355 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
356 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
357 * definition and statement argument match with one of the effective substatements' statement definition
361 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
363 * @param statementDef statement definition of the statement context to remove
364 * @param statementArg statement argument of the statement context to remove
366 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
367 final String statementArg) {
368 if (statementArg == null) {
369 removeStatementFromEffectiveSubstatements(statementDef);
372 if (effective.isEmpty()) {
376 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
377 while (iterator.hasNext()) {
378 final Mutable<?, ?, ?> next = iterator.next();
379 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
388 * Adds an effective statement to collection of substatements.
390 * @param substatement substatement
391 * @throws IllegalStateException
392 * if added in declared phase
393 * @throws NullPointerException
394 * if statement parameter is null
396 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
397 beforeAddEffectiveStatement(1);
398 effective.add(substatement);
402 * Adds an effective statement to collection of substatements.
404 * @param statements substatements
405 * @throws IllegalStateException
406 * if added in declared phase
407 * @throws NullPointerException
408 * if statement parameter is null
410 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
411 if (statements.isEmpty()) {
415 statements.forEach(Objects::requireNonNull);
416 beforeAddEffectiveStatement(statements.size());
417 effective.addAll(statements);
420 private void beforeAddEffectiveStatement(final int toAdd) {
421 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
422 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
423 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
424 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
426 if (effective.isEmpty()) {
427 effective = new ArrayList<>(toAdd);
432 * Create a new substatement at the specified offset.
434 * @param offset Substatement offset
435 * @param def definition context
436 * @param ref source reference
437 * @param argument statement argument
438 * @param <X> new substatement argument type
439 * @param <Y> new substatement declared type
440 * @param <Z> new substatement effective type
441 * @return A new substatement
443 @SuppressWarnings("checkstyle:methodTypeParameterName")
444 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
445 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
446 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
447 final String argument) {
448 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
449 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
450 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
452 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
453 if (implicitParent.isPresent()) {
454 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
458 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
459 substatements = substatements.put(offset, ret);
460 def.onStatementAdded(ret);
464 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
465 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
466 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
467 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
470 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
471 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
472 ImplicitSubstatement.of(getStatementSourceReference()), null);
476 * Lookup substatement by its offset in this statement.
478 * @param offset Substatement offset
479 * @return Substatement, or null if substatement does not exist.
481 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
482 return substatements.get(offset);
485 final void setFullyDefined() {
486 this.fullyDefined = true;
489 final void resizeSubstatements(final int expectedSize) {
490 substatements = substatements.ensureCapacity(expectedSize);
493 final void walkChildren(final ModelProcessingPhase phase) {
494 checkState(fullyDefined);
495 substatements.values().forEach(stmt -> {
496 stmt.walkChildren(phase);
497 stmt.endDeclared(phase);
502 public D buildDeclared() {
503 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
504 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
505 if (declaredInstance == null) {
506 declaredInstance = definition().getFactory().createDeclared(this);
508 return declaredInstance;
512 public E buildEffective() {
513 if (effectiveInstance == null) {
514 effectiveInstance = definition().getFactory().createEffective(this);
516 return effectiveInstance;
520 * tries to execute current {@link ModelProcessingPhase} of source parsing.
523 * to be executed (completed)
524 * @return if phase was successfully completed
525 * @throws SourceException
526 * when an error occurred in source parsing
528 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
530 boolean finished = true;
531 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
532 if (!openMutations.isEmpty()) {
533 final Iterator<ContextMutation> it = openMutations.iterator();
534 while (it.hasNext()) {
535 final ContextMutation current = it.next();
536 if (current.isFinished()) {
543 if (openMutations.isEmpty()) {
544 phaseMutation.removeAll(phase);
545 if (phaseMutation.isEmpty()) {
546 phaseMutation = ImmutableMultimap.of();
551 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
552 finished &= child.tryToCompletePhase(phase);
554 for (final Mutable<?, ?, ?> child : effective) {
555 if (child instanceof StatementContextBase) {
556 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
561 onPhaseCompleted(phase);
568 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
571 * that was to be completed (finished)
572 * @throws SourceException
573 * when an error occurred in source parsing
575 private void onPhaseCompleted(final ModelProcessingPhase phase) {
576 completedPhase = phase;
578 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
579 if (listeners.isEmpty()) {
583 final Iterator<OnPhaseFinished> listener = listeners.iterator();
584 while (listener.hasNext()) {
585 final OnPhaseFinished next = listener.next();
586 if (next.phaseFinished(this, phase)) {
591 if (listeners.isEmpty()) {
592 phaseListeners.removeAll(phase);
593 if (phaseListeners.isEmpty()) {
594 phaseListeners = ImmutableMultimap.of();
600 * Ends declared section of current node.
602 void endDeclared(final ModelProcessingPhase phase) {
603 definition().onDeclarationFinished(this, phase);
607 * Return the context in which this statement was defined.
609 * @return statement definition
611 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
616 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
617 definition().checkNamespaceAllowed(type);
621 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
623 // definition().onNamespaceElementAdded(this, type, key, value);
626 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
627 final OnNamespaceItemAdded listener) {
628 final Object potential = getFromNamespace(type, key);
629 if (potential != null) {
630 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
631 listener.namespaceItemAdded(this, type, key, potential);
635 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
637 void onValueAdded(final Object value) {
638 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
643 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
644 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
645 final OnNamespaceItemAdded listener) {
646 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
647 if (existing.isPresent()) {
648 final Entry<K, V> entry = existing.get();
649 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
650 waitForPhase(entry.getValue(), type, phase, criterion, listener);
654 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
655 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
657 boolean onValueAdded(final K key, final V value) {
658 if (criterion.match(key)) {
659 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
660 waitForPhase(value, type, phase, criterion, listener);
669 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
670 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
671 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
672 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
674 final Entry<K, V> match = optMatch.get();
675 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
678 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
679 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
680 final OnNamespaceItemAdded listener) {
681 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
682 (context, phaseCompleted) -> {
683 selectMatch(type, criterion, listener);
688 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
689 final Class<N> type) {
690 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
691 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
694 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
698 * See {@link StatementSupport#getPublicView()}.
701 public StatementDefinition getPublicDefinition() {
702 return definition().getPublicView();
706 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
707 return getRoot().getSourceContext().newInferenceAction(phase);
710 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
711 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
715 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
716 * the listener is notified immediately.
718 * @param phase requested completion phase
719 * @param listener listener to invoke
720 * @throws NullPointerException if any of the arguments is null
722 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
723 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
724 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
726 ModelProcessingPhase finishedPhase = completedPhase;
727 while (finishedPhase != null) {
728 if (phase.equals(finishedPhase)) {
729 listener.phaseFinished(this, finishedPhase);
732 finishedPhase = finishedPhase.getPreviousPhase();
734 if (phaseListeners.isEmpty()) {
735 phaseListeners = newMultimap();
738 phaseListeners.put(phase, listener);
742 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
744 * @throws IllegalStateException
745 * when the mutation was registered after phase was completed
747 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
748 ModelProcessingPhase finishedPhase = completedPhase;
749 while (finishedPhase != null) {
750 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
751 getStatementSourceReference());
752 finishedPhase = finishedPhase.getPreviousPhase();
755 if (phaseMutation.isEmpty()) {
756 phaseMutation = newMultimap();
758 phaseMutation.put(phase, mutation);
762 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
763 final KT key,final StmtContext<?, ?, ?> stmt) {
764 addContextToNamespace(namespace, key, stmt);
768 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
769 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
770 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
771 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
773 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
775 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
776 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
777 original.getPublicDefinition());
779 final SubstatementContext<X, Y, Z> result;
780 final SubstatementContext<X, Y, Z> copy;
782 if (implicitParent.isPresent()) {
783 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
784 result = new SubstatementContext(this, def, original.getSourceReference(),
785 original.rawStatementArgument(), original.getStatementArgument(), type);
787 final CopyType childCopyType;
789 case ADDED_BY_AUGMENTATION:
790 childCopyType = CopyType.ORIGINAL;
792 case ADDED_BY_USES_AUGMENTATION:
793 childCopyType = CopyType.ADDED_BY_USES;
798 childCopyType = type;
801 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
802 result.addEffectiveSubstatement(copy);
803 original.definition().onStatementAdded(copy);
805 result = copy = new SubstatementContext<>(original, this, type, targetModule);
806 original.definition().onStatementAdded(copy);
809 original.copyTo(copy, type, targetModule);
814 public @NonNull StatementDefinition getDefinition() {
815 return getPublicDefinition();
819 public @NonNull StatementSourceReference getSourceReference() {
820 return getStatementSourceReference();
824 public boolean isFullyDefined() {
829 public final boolean hasImplicitParentSupport() {
830 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
834 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
835 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
836 original.getPublicDefinition());
837 if (optImplicit.isEmpty()) {
841 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
842 final CopyType type = original.getCopyHistory().getLastOperation();
843 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
844 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
847 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
848 result.setCompletedPhase(original.getCompletedPhase());
852 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
853 @Nullable final QNameModule targetModule) {
854 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
856 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
857 if (stmtContext.isSupportedByFeatures()) {
858 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
862 for (final Mutable<?, ?, ?> stmtContext : effective) {
863 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
866 target.addEffectiveSubstatements(buffer);
869 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
870 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
871 if (needToCopyByUses(stmtContext)) {
872 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
873 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
875 } else if (isReusedByUses(stmtContext)) {
876 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
877 buffer.add(stmtContext);
879 LOG.debug("Skipping statement {}", stmtContext);
883 // FIXME: revise this, as it seems to be wrong
884 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
885 YangStmtMapping.DESCRIPTION,
886 YangStmtMapping.REFERENCE,
887 YangStmtMapping.STATUS);
888 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
889 YangStmtMapping.TYPE,
890 YangStmtMapping.TYPEDEF,
891 YangStmtMapping.USES);
893 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
894 final StatementDefinition def = stmtContext.getPublicDefinition();
895 if (REUSED_DEF_SET.contains(def)) {
896 LOG.debug("Will reuse {} statement {}", def, stmtContext);
899 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
900 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
903 LOG.debug("Will copy {} statement {}", def, stmtContext);
907 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
908 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
912 public final String toString() {
913 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
916 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
917 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);