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;
71 * Core reactor statement implementation of {@link Mutable}.
73 * @param <A> Argument type
74 * @param <D> Declared Statement representation
75 * @param <E> Effective Statement representation
77 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
78 extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
80 * Event listener when an item is added to model namespace.
82 interface OnNamespaceItemAdded extends EventListener {
84 * Invoked whenever a new item is added to a namespace.
86 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
90 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
92 interface OnPhaseFinished extends EventListener {
94 * Invoked whenever a processing phase has finished.
96 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
100 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
102 interface ContextMutation {
104 boolean isFinished();
107 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
109 // Flag bit assignments
110 private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
111 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
112 private static final int IS_IGNORE_IF_FEATURE = 0x04;
113 private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
114 // Note: these four are related
115 private static final int IS_IGNORE_CONFIG = 0x10;
116 private static final int HAVE_IGNORE_CONFIG = 0x20;
117 private static final int IS_CONFIGURATION = 0x40;
118 private static final int HAVE_CONFIGURATION = 0x80;
120 // Have-and-set flag constants, also used as masks
121 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
122 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
123 // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
124 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
125 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
127 private final @NonNull StatementDefinitionContext<A, D, E> definition;
128 private final @NonNull StatementSourceReference statementDeclSource;
129 private final StmtContext<?, ?, ?> originalCtx;
130 private final StmtContext<?, ?, ?> prevCopyCtx;
131 private final CopyHistory copyHistory;
132 private final String rawArgument;
134 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
135 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
136 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
137 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
138 private StatementMap substatements = StatementMap.empty();
140 private @Nullable ModelProcessingPhase completedPhase;
141 private @Nullable D declaredInstance;
142 private @Nullable E effectiveInstance;
145 private boolean isSupportedToBuildEffective = true;
146 private boolean fullyDefined;
148 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above booleans and
149 // hence improve memory layout.
152 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
153 final String rawArgument) {
154 this.definition = requireNonNull(def);
155 this.statementDeclSource = requireNonNull(ref);
156 this.rawArgument = def.internArgument(rawArgument);
157 this.copyHistory = CopyHistory.original();
158 this.originalCtx = null;
159 this.prevCopyCtx = null;
162 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
163 final String rawArgument, final CopyType copyType) {
164 this.definition = requireNonNull(def);
165 this.statementDeclSource = requireNonNull(ref);
166 this.rawArgument = rawArgument;
167 this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
168 this.originalCtx = null;
169 this.prevCopyCtx = null;
172 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
173 this.definition = original.definition;
174 this.statementDeclSource = original.statementDeclSource;
175 this.rawArgument = original.rawArgument;
176 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
177 this.originalCtx = original.getOriginalCtx().orElse(original);
178 this.prevCopyCtx = original;
181 StatementContextBase(final StatementContextBase<A, D, E> original) {
182 this.definition = original.definition;
183 this.statementDeclSource = original.statementDeclSource;
184 this.rawArgument = original.rawArgument;
185 this.copyHistory = original.getCopyHistory();
186 this.originalCtx = original.getOriginalCtx().orElse(original);
187 this.prevCopyCtx = original;
188 this.substatements = original.substatements;
189 this.effective = original.effective;
193 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
194 return effectOfStatement;
198 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
199 if (effectOfStatement.isEmpty()) {
200 effectOfStatement = new ArrayList<>(1);
202 effectOfStatement.add(ctx);
206 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
207 if (ctxs.isEmpty()) {
211 if (effectOfStatement.isEmpty()) {
212 effectOfStatement = new ArrayList<>(ctxs.size());
214 effectOfStatement.addAll(ctxs);
218 public boolean isSupportedByFeatures() {
219 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
221 return fl == SET_SUPPORTED_BY_FEATURES;
223 if (isIgnoringIfFeatures()) {
224 flags |= SET_SUPPORTED_BY_FEATURES;
229 * If parent is supported, we need to check if-features statements of this context.
231 if (isParentSupportedByFeatures()) {
232 // If the set of supported features has not been provided, all features are supported by default.
233 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
234 SupportedFeatures.SUPPORTED_FEATURES);
235 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
236 flags |= SET_SUPPORTED_BY_FEATURES;
241 // Either parent is not supported or this statement is not supported
242 flags |= HAVE_SUPPORTED_BY_FEATURES;
246 protected abstract boolean isParentSupportedByFeatures();
249 public boolean isSupportedToBuildEffective() {
250 return isSupportedToBuildEffective;
254 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
255 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
259 public CopyHistory getCopyHistory() {
264 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
265 return Optional.ofNullable(originalCtx);
269 public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
270 return Optional.ofNullable(prevCopyCtx);
274 public ModelProcessingPhase getCompletedPhase() {
275 return completedPhase;
279 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
280 this.completedPhase = completedPhase;
284 public abstract StatementContextBase<?, ?, ?> getParentContext();
287 * Returns the model root for this statement.
289 * @return root context of statement
292 public abstract RootStatementContext<?, ?, ?> getRoot();
295 public StatementSource getStatementSource() {
296 return statementDeclSource.getStatementSource();
300 public StatementSourceReference getStatementSourceReference() {
301 return statementDeclSource;
305 public final String rawStatementArgument() {
310 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
311 return substatements.values();
315 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
316 return substatements.values();
320 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
321 return mutableEffectiveSubstatements();
325 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
326 if (effective instanceof ImmutableCollection) {
330 return Collections.unmodifiableCollection(effective);
334 * Remove a set of statements from effective statements.
336 * @param statements statements to be removed
337 * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
338 * It is no longer used in that capacity and slated for removal.
340 // FIXME: 5.0.0: remove this method
342 public void removeStatementsFromEffectiveSubstatements(
343 final Collection<? extends StmtContext<?, ?, ?>> statements) {
344 if (!effective.isEmpty()) {
345 effective.removeAll(statements);
350 private void shrinkEffective() {
351 if (effective.isEmpty()) {
352 effective = ImmutableList.of();
356 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
357 if (effective.isEmpty()) {
361 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
362 while (iterator.hasNext()) {
363 final StmtContext<?, ?, ?> next = iterator.next();
364 if (statementDef.equals(next.getPublicDefinition())) {
373 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
374 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
375 * definition and statement argument match with one of the effective substatements' statement definition
379 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
381 * @param statementDef statement definition of the statement context to remove
382 * @param statementArg statement argument of the statement context to remove
384 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
385 final String statementArg) {
386 if (statementArg == null) {
387 removeStatementFromEffectiveSubstatements(statementDef);
390 if (effective.isEmpty()) {
394 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
395 while (iterator.hasNext()) {
396 final Mutable<?, ?, ?> next = iterator.next();
397 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
406 * Adds an effective statement to collection of substatements.
408 * @param substatement substatement
409 * @throws IllegalStateException
410 * if added in declared phase
411 * @throws NullPointerException
412 * if statement parameter is null
414 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
415 beforeAddEffectiveStatement(1);
416 effective.add(substatement);
420 * Adds an effective statement to collection of substatements.
422 * @param statements substatements
423 * @throws IllegalStateException
424 * if added in declared phase
425 * @throws NullPointerException
426 * if statement parameter is null
428 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
429 if (statements.isEmpty()) {
433 statements.forEach(Objects::requireNonNull);
434 beforeAddEffectiveStatement(statements.size());
435 effective.addAll(statements);
438 private void beforeAddEffectiveStatement(final int toAdd) {
439 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
440 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
441 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
442 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
444 if (effective.isEmpty()) {
445 effective = new ArrayList<>(toAdd);
450 * Create a new substatement at the specified offset.
452 * @param offset Substatement offset
453 * @param def definition context
454 * @param ref source reference
455 * @param argument statement argument
456 * @param <X> new substatement argument type
457 * @param <Y> new substatement declared type
458 * @param <Z> new substatement effective type
459 * @return A new substatement
461 @SuppressWarnings("checkstyle:methodTypeParameterName")
462 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
463 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
464 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
465 final String argument) {
466 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
467 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
468 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
470 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
471 if (implicitParent.isPresent()) {
472 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
476 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
477 substatements = substatements.put(offset, ret);
478 def.onStatementAdded(ret);
482 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
483 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
484 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
485 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
488 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
489 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
490 ImplicitSubstatement.of(getStatementSourceReference()), null);
494 * Lookup substatement by its offset in this statement.
496 * @param offset Substatement offset
497 * @return Substatement, or null if substatement does not exist.
499 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
500 return substatements.get(offset);
503 final void setFullyDefined() {
504 this.fullyDefined = true;
507 final void resizeSubstatements(final int expectedSize) {
508 substatements = substatements.ensureCapacity(expectedSize);
511 final void walkChildren(final ModelProcessingPhase phase) {
512 checkState(fullyDefined);
513 substatements.values().forEach(stmt -> {
514 stmt.walkChildren(phase);
515 stmt.endDeclared(phase);
520 public D buildDeclared() {
521 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
522 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
523 if (declaredInstance == null) {
524 declaredInstance = definition().getFactory().createDeclared(this);
526 return declaredInstance;
530 public E buildEffective() {
531 if (effectiveInstance == null) {
532 effectiveInstance = definition().getFactory().createEffective(this);
534 return effectiveInstance;
538 * tries to execute current {@link ModelProcessingPhase} of source parsing.
541 * to be executed (completed)
542 * @return if phase was successfully completed
543 * @throws SourceException
544 * when an error occurred in source parsing
546 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
548 boolean finished = true;
549 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
550 if (!openMutations.isEmpty()) {
551 final Iterator<ContextMutation> it = openMutations.iterator();
552 while (it.hasNext()) {
553 final ContextMutation current = it.next();
554 if (current.isFinished()) {
561 if (openMutations.isEmpty()) {
562 phaseMutation.removeAll(phase);
563 if (phaseMutation.isEmpty()) {
564 phaseMutation = ImmutableMultimap.of();
569 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
570 finished &= child.tryToCompletePhase(phase);
572 for (final Mutable<?, ?, ?> child : effective) {
573 if (child instanceof StatementContextBase) {
574 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
579 onPhaseCompleted(phase);
586 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
589 * that was to be completed (finished)
590 * @throws SourceException
591 * when an error occurred in source parsing
593 private void onPhaseCompleted(final ModelProcessingPhase phase) {
594 completedPhase = phase;
596 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
597 if (listeners.isEmpty()) {
601 final Iterator<OnPhaseFinished> listener = listeners.iterator();
602 while (listener.hasNext()) {
603 final OnPhaseFinished next = listener.next();
604 if (next.phaseFinished(this, phase)) {
609 if (listeners.isEmpty()) {
610 phaseListeners.removeAll(phase);
611 if (phaseListeners.isEmpty()) {
612 phaseListeners = ImmutableMultimap.of();
618 * Ends declared section of current node.
620 void endDeclared(final ModelProcessingPhase phase) {
621 definition().onDeclarationFinished(this, phase);
625 * Return the context in which this statement was defined.
627 * @return statement definition
629 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
634 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
635 definition().checkNamespaceAllowed(type);
639 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
641 // definition().onNamespaceElementAdded(this, type, key, value);
644 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
645 final OnNamespaceItemAdded listener) {
646 final Object potential = getFromNamespace(type, key);
647 if (potential != null) {
648 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
649 listener.namespaceItemAdded(this, type, key, potential);
653 getBehaviour(type).addListener(new KeyedValueAddedListener<K>(this, key) {
655 void onValueAdded(final Object value) {
656 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
661 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
662 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
663 final OnNamespaceItemAdded listener) {
664 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
665 if (existing.isPresent()) {
666 final Entry<K, V> entry = existing.get();
667 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
668 waitForPhase(entry.getValue(), type, phase, criterion, listener);
672 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
673 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
675 boolean onValueAdded(final K key, final V value) {
676 if (criterion.match(key)) {
677 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
678 waitForPhase(value, type, phase, criterion, listener);
687 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
688 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
689 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
690 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
692 final Entry<K, V> match = optMatch.get();
693 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
696 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
697 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
698 final OnNamespaceItemAdded listener) {
699 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
700 (context, phaseCompleted) -> {
701 selectMatch(type, criterion, listener);
706 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
707 final Class<N> type) {
708 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
709 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
712 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
716 public StatementDefinition getPublicDefinition() {
717 return definition().getPublicView();
721 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
722 return getRoot().getSourceContext().newInferenceAction(phase);
725 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
726 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
730 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
731 * the listener is notified immediately.
733 * @param phase requested completion phase
734 * @param listener listener to invoke
735 * @throws NullPointerException if any of the arguments is null
737 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
738 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
739 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
741 ModelProcessingPhase finishedPhase = completedPhase;
742 while (finishedPhase != null) {
743 if (phase.equals(finishedPhase)) {
744 listener.phaseFinished(this, finishedPhase);
747 finishedPhase = finishedPhase.getPreviousPhase();
749 if (phaseListeners.isEmpty()) {
750 phaseListeners = newMultimap();
753 phaseListeners.put(phase, listener);
757 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
759 * @throws IllegalStateException
760 * when the mutation was registered after phase was completed
762 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
763 ModelProcessingPhase finishedPhase = completedPhase;
764 while (finishedPhase != null) {
765 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
766 getStatementSourceReference());
767 finishedPhase = finishedPhase.getPreviousPhase();
770 if (phaseMutation.isEmpty()) {
771 phaseMutation = newMultimap();
773 phaseMutation.put(phase, mutation);
777 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
778 final KT key,final StmtContext<?, ?, ?> stmt) {
779 addContextToNamespace(namespace, key, stmt);
783 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
784 final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
785 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
786 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
788 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
790 final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
791 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
792 original.getPublicDefinition());
794 final SubstatementContext<X, Y, Z> result;
795 final SubstatementContext<X, Y, Z> copy;
797 if (implicitParent.isPresent()) {
798 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
799 result = new SubstatementContext(this, def, original.getSourceReference(),
800 original.rawStatementArgument(), original.getStatementArgument(), type);
802 final CopyType childCopyType;
804 case ADDED_BY_AUGMENTATION:
805 childCopyType = CopyType.ORIGINAL;
807 case ADDED_BY_USES_AUGMENTATION:
808 childCopyType = CopyType.ADDED_BY_USES;
813 childCopyType = type;
816 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
817 result.addEffectiveSubstatement(copy);
819 result = copy = new SubstatementContext<>(original, this, type, targetModule);
822 original.definition().onStatementAdded(copy);
823 original.copyTo(copy, type, targetModule);
828 public @NonNull StatementDefinition getDefinition() {
829 return getPublicDefinition();
833 public @NonNull StatementSourceReference getSourceReference() {
834 return getStatementSourceReference();
838 public boolean isFullyDefined() {
843 public final boolean hasImplicitParentSupport() {
844 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
848 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
849 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
850 original.getPublicDefinition());
851 if (!optImplicit.isPresent()) {
855 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
856 final CopyType type = original.getCopyHistory().getLastOperation();
857 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
858 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
861 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
862 result.setCompletedPhase(original.getCompletedPhase());
867 * Config statements are not all that common which means we are performing a recursive search towards the root
868 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
869 * for the (usually non-existent) config statement.
872 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
873 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
876 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
877 * {@link #isIgnoringConfig(StatementContextBase)}.
879 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
880 final int fl = flags & SET_CONFIGURATION;
882 return fl == SET_CONFIGURATION;
884 if (isIgnoringConfig(parent)) {
885 // Note: SET_CONFIGURATION has been stored in flags
889 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
890 ConfigStatement.class);
891 final boolean isConfig;
892 if (configStatement != null) {
893 isConfig = configStatement.coerceStatementArgument();
895 // Validity check: if parent is config=false this cannot be a config=true
896 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
897 "Parent node has config=false, this node must not be specifed as config=true");
900 // If "config" statement is not specified, the default is the same as the parent's "config" value.
901 isConfig = parent.isConfiguration();
904 // Resolved, make sure we cache this return
905 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
909 protected abstract boolean isIgnoringConfig();
912 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
913 * keep on returning the same result without performing any lookups. Exists only to support
914 * {@link SubstatementContext#isIgnoringConfig()}.
917 * Note: use of this method implies that {@link #isConfiguration()} is realized with
918 * {@link #isConfiguration(StatementContextBase)}.
920 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
921 final int fl = flags & SET_IGNORE_CONFIG;
923 return fl == SET_IGNORE_CONFIG;
925 if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
926 flags |= SET_IGNORE_CONFIG;
930 flags |= HAVE_IGNORE_CONFIG;
934 protected abstract boolean isIgnoringIfFeatures();
937 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
938 * keep on returning the same result without performing any lookups. Exists only to support
939 * {@link SubstatementContext#isIgnoringIfFeatures()}.
941 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
942 final int fl = flags & SET_IGNORE_IF_FEATURE;
944 return fl == SET_IGNORE_IF_FEATURE;
946 if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
947 flags |= SET_IGNORE_IF_FEATURE;
951 flags |= HAVE_IGNORE_IF_FEATURE;
955 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
956 @Nullable final QNameModule targetModule) {
957 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
959 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
960 if (stmtContext.isSupportedByFeatures()) {
961 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
965 for (final Mutable<?, ?, ?> stmtContext : effective) {
966 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
969 target.addEffectiveSubstatements(buffer);
972 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
973 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
974 if (needToCopyByUses(stmtContext)) {
975 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
976 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
978 } else if (isReusedByUses(stmtContext)) {
979 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
980 buffer.add(stmtContext);
982 LOG.debug("Skipping statement {}", stmtContext);
986 // FIXME: revise this, as it seems to be wrong
987 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
988 YangStmtMapping.DESCRIPTION,
989 YangStmtMapping.REFERENCE,
990 YangStmtMapping.STATUS);
991 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
992 YangStmtMapping.TYPE,
993 YangStmtMapping.TYPEDEF,
994 YangStmtMapping.USES);
996 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
997 final StatementDefinition def = stmtContext.getPublicDefinition();
998 if (REUSED_DEF_SET.contains(def)) {
999 LOG.debug("Will reuse {} statement {}", def, stmtContext);
1002 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
1003 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
1006 LOG.debug("Will copy {} statement {}", def, stmtContext);
1010 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
1011 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
1015 public final String toString() {
1016 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1019 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1020 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);