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.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
43 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
44 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
45 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
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.InferenceException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
59 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
61 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
62 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter.ResumedStatement;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
66 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
71 extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
73 * Event listener when an item is added to model namespace.
75 interface OnNamespaceItemAdded extends EventListener {
77 * Invoked whenever a new item is added to a namespace.
79 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
83 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
85 interface OnPhaseFinished extends EventListener {
87 * Invoked whenever a processing phase has finished.
89 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
93 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
95 interface ContextMutation {
100 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
102 // Flag bit assignments
103 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
104 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
105 private static final int IS_IGNORE_IF_FEATURE = 0x04;
106 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
107 // Note: these four are related
108 private static final int IS_IGNORE_CONFIG = 0x10;
109 private static final int HAVE_IGNORE_CONFIG = 0x20;
110 private static final int IS_CONFIGURATION = 0x40;
111 private static final int HAVE_CONFIGURATION = 0x80;
113 // Have-and-set flag constants, also used as masks
114 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
115 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
116 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
117 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
118 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
120 private final @NonNull StatementDefinitionContext<A, D, E> definition;
121 private final @NonNull StatementSourceReference statementDeclSource;
122 private final StmtContext<?, ?, ?> originalCtx;
123 private final StmtContext<?, ?, ?> prevCopyCtx;
124 private final CopyHistory copyHistory;
125 private final String rawArgument;
127 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
128 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
129 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
130 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
131 private StatementMap substatements = StatementMap.empty();
133 private @Nullable ModelProcessingPhase completedPhase;
134 private @Nullable D declaredInstance;
135 private @Nullable E effectiveInstance;
138 private boolean isSupportedToBuildEffective = true;
139 private boolean fullyDefined;
141 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above booleans and
142 // hence improve memory layout.
145 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
146 final String rawArgument) {
147 this.definition = requireNonNull(def);
148 this.statementDeclSource = requireNonNull(ref);
149 this.rawArgument = def.internArgument(rawArgument);
150 this.copyHistory = CopyHistory.original();
151 this.originalCtx = null;
152 this.prevCopyCtx = null;
155 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
156 final String rawArgument, final CopyType copyType) {
157 this.definition = requireNonNull(def);
158 this.statementDeclSource = requireNonNull(ref);
159 this.rawArgument = rawArgument;
160 this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
161 this.originalCtx = null;
162 this.prevCopyCtx = null;
165 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
166 this.definition = original.definition;
167 this.statementDeclSource = original.statementDeclSource;
168 this.rawArgument = original.rawArgument;
169 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
170 this.originalCtx = original.getOriginalCtx().orElse(original);
171 this.prevCopyCtx = original;
174 StatementContextBase(final StatementContextBase<A, D, E> original) {
175 this.definition = original.definition;
176 this.statementDeclSource = original.statementDeclSource;
177 this.rawArgument = original.rawArgument;
178 this.copyHistory = original.getCopyHistory();
179 this.originalCtx = original.getOriginalCtx().orElse(original);
180 this.prevCopyCtx = original;
181 this.substatements = original.substatements;
182 this.effective = original.effective;
186 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
187 return effectOfStatement;
191 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
192 if (effectOfStatement.isEmpty()) {
193 effectOfStatement = new ArrayList<>(1);
195 effectOfStatement.add(ctx);
199 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
200 if (ctxs.isEmpty()) {
204 if (effectOfStatement.isEmpty()) {
205 effectOfStatement = new ArrayList<>(ctxs.size());
207 effectOfStatement.addAll(ctxs);
211 public boolean isSupportedByFeatures() {
212 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
214 return fl == SET_SUPPORTED_BY_FEATURES;
216 if (isIgnoringIfFeatures()) {
217 flags |= SET_SUPPORTED_BY_FEATURES;
222 * If parent is supported, we need to check if-features statements of this context.
224 if (isParentSupportedByFeatures()) {
225 // If the set of supported features has not been provided, all features are supported by default.
226 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
227 SupportedFeatures.SUPPORTED_FEATURES);
228 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
229 flags |= SET_SUPPORTED_BY_FEATURES;
234 // Either parent is not supported or this statement is not supported
235 flags |= HAVE_SUPPORTED_BY_FEATURES;
239 protected abstract boolean isParentSupportedByFeatures();
242 public boolean isSupportedToBuildEffective() {
243 return isSupportedToBuildEffective;
247 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
248 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
252 public CopyHistory getCopyHistory() {
257 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
258 return Optional.ofNullable(originalCtx);
262 public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
263 return Optional.ofNullable(prevCopyCtx);
267 public ModelProcessingPhase getCompletedPhase() {
268 return completedPhase;
272 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
273 this.completedPhase = completedPhase;
277 public abstract StatementContextBase<?, ?, ?> getParentContext();
280 * Returns the model root for this statement.
282 * @return root context of statement
285 public abstract RootStatementContext<?, ?, ?> getRoot();
288 public StatementSource getStatementSource() {
289 return statementDeclSource.getStatementSource();
293 public StatementSourceReference getStatementSourceReference() {
294 return statementDeclSource;
298 public final String rawStatementArgument() {
303 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
304 return substatements.values();
308 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
309 return substatements.values();
313 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
314 return mutableEffectiveSubstatements();
318 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
319 if (effective instanceof ImmutableCollection) {
323 return Collections.unmodifiableCollection(effective);
327 * Remove a set of statements from effective statements.
329 * @param statements statements to be removed
330 * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
331 * It is no longer used in that capacity and slated for removal.
333 // FIXME: 5.0.0: remove this method
334 @Deprecated(forRemoval = true)
335 public void removeStatementsFromEffectiveSubstatements(
336 final Collection<? extends StmtContext<?, ?, ?>> statements) {
337 if (!effective.isEmpty()) {
338 effective.removeAll(statements);
343 private void shrinkEffective() {
344 if (effective.isEmpty()) {
345 effective = ImmutableList.of();
349 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
350 if (effective.isEmpty()) {
354 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
355 while (iterator.hasNext()) {
356 final StmtContext<?, ?, ?> next = iterator.next();
357 if (statementDef.equals(next.getPublicDefinition())) {
366 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
367 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
368 * definition and statement argument match with one of the effective substatements' statement definition
372 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
374 * @param statementDef statement definition of the statement context to remove
375 * @param statementArg statement argument of the statement context to remove
377 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
378 final String statementArg) {
379 if (statementArg == null) {
380 removeStatementFromEffectiveSubstatements(statementDef);
383 if (effective.isEmpty()) {
387 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
388 while (iterator.hasNext()) {
389 final Mutable<?, ?, ?> next = iterator.next();
390 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
399 * Adds an effective statement to collection of substatements.
401 * @param substatement substatement
402 * @throws IllegalStateException
403 * if added in declared phase
404 * @throws NullPointerException
405 * if statement parameter is null
407 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
408 beforeAddEffectiveStatement(1);
409 effective.add(substatement);
413 * Adds an effective statement to collection of substatements.
415 * @param statements substatements
416 * @throws IllegalStateException
417 * if added in declared phase
418 * @throws NullPointerException
419 * if statement parameter is null
421 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
422 if (statements.isEmpty()) {
426 statements.forEach(Objects::requireNonNull);
427 beforeAddEffectiveStatement(statements.size());
428 effective.addAll(statements);
431 private void beforeAddEffectiveStatement(final int toAdd) {
432 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
433 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
434 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
435 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
437 if (effective.isEmpty()) {
438 effective = new ArrayList<>(toAdd);
443 * Create a new substatement at the specified offset.
445 * @param offset Substatement offset
446 * @param def definition context
447 * @param ref source reference
448 * @param argument statement argument
449 * @param <X> new substatement argument type
450 * @param <Y> new substatement declared type
451 * @param <Z> new substatement effective type
452 * @return A new substatement
454 @SuppressWarnings("checkstyle:methodTypeParameterName")
455 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
456 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
457 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
458 final String argument) {
459 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
460 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
461 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
463 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
464 if (implicitParent.isPresent()) {
465 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
469 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
470 substatements = substatements.put(offset, ret);
471 def.onStatementAdded(ret);
475 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
476 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
477 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
478 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
481 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
482 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
483 ImplicitSubstatement.of(getStatementSourceReference()), null);
487 * Lookup substatement by its offset in this statement.
489 * @param offset Substatement offset
490 * @return Substatement, or null if substatement does not exist.
492 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
493 return substatements.get(offset);
496 final void setFullyDefined() {
497 this.fullyDefined = true;
500 final void resizeSubstatements(final int expectedSize) {
501 substatements = substatements.ensureCapacity(expectedSize);
504 final void walkChildren(final ModelProcessingPhase phase) {
505 checkState(fullyDefined);
506 substatements.values().forEach(stmt -> {
507 stmt.walkChildren(phase);
508 stmt.endDeclared(phase);
513 public D buildDeclared() {
514 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
515 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
516 if (declaredInstance == null) {
517 declaredInstance = definition().getFactory().createDeclared(this);
519 return declaredInstance;
523 public E buildEffective() {
524 if (effectiveInstance == null) {
525 effectiveInstance = definition().getFactory().createEffective(this);
527 return effectiveInstance;
531 * tries to execute current {@link ModelProcessingPhase} of source parsing.
534 * to be executed (completed)
535 * @return if phase was successfully completed
536 * @throws SourceException
537 * when an error occurred in source parsing
539 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
541 boolean finished = true;
542 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
543 if (!openMutations.isEmpty()) {
544 final Iterator<ContextMutation> it = openMutations.iterator();
545 while (it.hasNext()) {
546 final ContextMutation current = it.next();
547 if (current.isFinished()) {
554 if (openMutations.isEmpty()) {
555 phaseMutation.removeAll(phase);
556 if (phaseMutation.isEmpty()) {
557 phaseMutation = ImmutableMultimap.of();
562 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
563 finished &= child.tryToCompletePhase(phase);
565 for (final Mutable<?, ?, ?> child : effective) {
566 if (child instanceof StatementContextBase) {
567 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
572 onPhaseCompleted(phase);
579 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
582 * that was to be completed (finished)
583 * @throws SourceException
584 * when an error occurred in source parsing
586 private void onPhaseCompleted(final ModelProcessingPhase phase) {
587 completedPhase = phase;
589 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
590 if (listeners.isEmpty()) {
594 final Iterator<OnPhaseFinished> listener = listeners.iterator();
595 while (listener.hasNext()) {
596 final OnPhaseFinished next = listener.next();
597 if (next.phaseFinished(this, phase)) {
602 if (listeners.isEmpty()) {
603 phaseListeners.removeAll(phase);
604 if (phaseListeners.isEmpty()) {
605 phaseListeners = ImmutableMultimap.of();
611 * Ends declared section of current node.
613 void endDeclared(final ModelProcessingPhase phase) {
614 definition().onDeclarationFinished(this, phase);
618 * Return the context in which this statement was defined.
620 * @return statement definition
622 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
627 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
628 definition().checkNamespaceAllowed(type);
632 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
634 // definition().onNamespaceElementAdded(this, type, key, value);
637 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
638 final OnNamespaceItemAdded listener) {
639 final Object potential = getFromNamespace(type, key);
640 if (potential != null) {
641 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
642 listener.namespaceItemAdded(this, type, key, potential);
646 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
648 void onValueAdded(final Object value) {
649 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
654 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
655 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
656 final OnNamespaceItemAdded listener) {
657 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
658 if (existing.isPresent()) {
659 final Entry<K, V> entry = existing.get();
660 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
661 waitForPhase(entry.getValue(), type, phase, criterion, listener);
665 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
666 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
668 boolean onValueAdded(final K key, final V value) {
669 if (criterion.match(key)) {
670 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
671 waitForPhase(value, type, phase, criterion, listener);
680 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
681 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
682 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
683 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
685 final Entry<K, V> match = optMatch.get();
686 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
689 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
690 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
691 final OnNamespaceItemAdded listener) {
692 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
693 (context, phaseCompleted) -> {
694 selectMatch(type, criterion, listener);
699 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
700 final Class<N> type) {
701 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
702 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
705 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
709 public StatementDefinition getPublicDefinition() {
710 return definition().getPublicView();
714 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
715 return getRoot().getSourceContext().newInferenceAction(phase);
718 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
719 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
723 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
724 * the listener is notified immediately.
726 * @param phase requested completion phase
727 * @param listener listener to invoke
728 * @throws NullPointerException if any of the arguments is null
730 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
731 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
732 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
734 ModelProcessingPhase finishedPhase = completedPhase;
735 while (finishedPhase != null) {
736 if (phase.equals(finishedPhase)) {
737 listener.phaseFinished(this, finishedPhase);
740 finishedPhase = finishedPhase.getPreviousPhase();
742 if (phaseListeners.isEmpty()) {
743 phaseListeners = newMultimap();
746 phaseListeners.put(phase, listener);
750 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
752 * @throws IllegalStateException
753 * when the mutation was registered after phase was completed
755 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
756 ModelProcessingPhase finishedPhase = completedPhase;
757 while (finishedPhase != null) {
758 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
759 getStatementSourceReference());
760 finishedPhase = finishedPhase.getPreviousPhase();
763 if (phaseMutation.isEmpty()) {
764 phaseMutation = newMultimap();
766 phaseMutation.put(phase, mutation);
770 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
771 final KT key,final StmtContext<?, ?, ?> stmt) {
772 addContextToNamespace(namespace, key, stmt);
776 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
777 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
778 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
779 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
781 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
783 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
784 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
785 original.getPublicDefinition());
787 final SubstatementContext<X, Y, Z> result;
788 final SubstatementContext<X, Y, Z> copy;
790 if (implicitParent.isPresent()) {
791 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
792 result = new SubstatementContext(this, def, original.getSourceReference(),
793 original.rawStatementArgument(), original.getStatementArgument(), type);
795 final CopyType childCopyType;
797 case ADDED_BY_AUGMENTATION:
798 childCopyType = CopyType.ORIGINAL;
800 case ADDED_BY_USES_AUGMENTATION:
801 childCopyType = CopyType.ADDED_BY_USES;
806 childCopyType = type;
809 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
810 result.addEffectiveSubstatement(copy);
812 result = copy = new SubstatementContext<>(original, this, type, targetModule);
815 original.definition().onStatementAdded(copy);
816 original.copyTo(copy, type, targetModule);
821 public @NonNull StatementDefinition getDefinition() {
822 return getPublicDefinition();
826 public @NonNull StatementSourceReference getSourceReference() {
827 return getStatementSourceReference();
831 public boolean isFullyDefined() {
836 public final boolean hasImplicitParentSupport() {
837 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
841 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
842 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
843 original.getPublicDefinition());
844 if (optImplicit.isEmpty()) {
848 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
849 final CopyType type = original.getCopyHistory().getLastOperation();
850 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
851 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
854 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
855 result.setCompletedPhase(original.getCompletedPhase());
860 * Config statements are not all that common which means we are performing a recursive search towards the root
861 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
862 * for the (usually non-existent) config statement.
865 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
866 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
869 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
870 * {@link #isIgnoringConfig(StatementContextBase)}.
872 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
873 final int fl = flags & SET_CONFIGURATION;
875 return fl == SET_CONFIGURATION;
877 if (isIgnoringConfig(parent)) {
878 // Note: SET_CONFIGURATION has been stored in flags
882 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
883 ConfigStatement.class);
884 final boolean isConfig;
885 if (configStatement != null) {
886 isConfig = configStatement.coerceStatementArgument();
888 // Validity check: if parent is config=false this cannot be a config=true
889 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
890 "Parent node has config=false, this node must not be specifed as config=true");
893 // If "config" statement is not specified, the default is the same as the parent's "config" value.
894 isConfig = parent.isConfiguration();
897 // Resolved, make sure we cache this return
898 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
902 protected abstract boolean isIgnoringConfig();
905 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
906 * keep on returning the same result without performing any lookups. Exists only to support
907 * {@link SubstatementContext#isIgnoringConfig()}.
910 * Note: use of this method implies that {@link #isConfiguration()} is realized with
911 * {@link #isConfiguration(StatementContextBase)}.
913 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
914 final int fl = flags & SET_IGNORE_CONFIG;
916 return fl == SET_IGNORE_CONFIG;
918 if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
919 flags |= SET_IGNORE_CONFIG;
923 flags |= HAVE_IGNORE_CONFIG;
927 protected abstract boolean isIgnoringIfFeatures();
930 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
931 * keep on returning the same result without performing any lookups. Exists only to support
932 * {@link SubstatementContext#isIgnoringIfFeatures()}.
934 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
935 final int fl = flags & SET_IGNORE_IF_FEATURE;
937 return fl == SET_IGNORE_IF_FEATURE;
939 if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
940 flags |= SET_IGNORE_IF_FEATURE;
944 flags |= HAVE_IGNORE_IF_FEATURE;
948 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
949 @Nullable final QNameModule targetModule) {
950 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
952 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
953 if (stmtContext.isSupportedByFeatures()) {
954 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
958 for (final Mutable<?, ?, ?> stmtContext : effective) {
959 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
962 target.addEffectiveSubstatements(buffer);
965 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
966 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
967 if (needToCopyByUses(stmtContext)) {
968 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
969 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
971 } else if (isReusedByUses(stmtContext)) {
972 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
973 buffer.add(stmtContext);
975 LOG.debug("Skipping statement {}", stmtContext);
979 // FIXME: revise this, as it seems to be wrong
980 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
981 YangStmtMapping.DESCRIPTION,
982 YangStmtMapping.REFERENCE,
983 YangStmtMapping.STATUS);
984 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
985 YangStmtMapping.TYPE,
986 YangStmtMapping.TYPEDEF,
987 YangStmtMapping.USES);
989 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
990 final StatementDefinition def = stmtContext.getPublicDefinition();
991 if (REUSED_DEF_SET.contains(def)) {
992 LOG.debug("Will reuse {} statement {}", def, stmtContext);
995 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
996 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
999 LOG.debug("Will copy {} statement {}", def, stmtContext);
1003 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
1004 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
1008 public final String toString() {
1009 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1012 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1013 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);