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_CONFIGURATION = 0x04;
106 private static final int HAVE_CONFIGURATION = 0x08;
107 private static final int IS_IGNORE_CONFIG = 0x10;
108 private static final int HAVE_IGNORE_CONFIG = 0x20;
109 private static final int IS_IGNORE_IF_FEATURE = 0x40;
110 private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
112 // Have-and-set flag constants, also used as masks
113 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
114 private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
115 private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG;
116 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
118 private final @NonNull StatementDefinitionContext<A, D, E> definition;
119 private final @NonNull StatementSourceReference statementDeclSource;
120 private final StmtContext<?, ?, ?> originalCtx;
121 private final StmtContext<?, ?, ?> prevCopyCtx;
122 private final CopyHistory copyHistory;
123 private final String rawArgument;
125 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
126 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
127 private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
128 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
129 private StatementMap substatements = StatementMap.empty();
131 private @Nullable ModelProcessingPhase completedPhase;
132 private @Nullable D declaredInstance;
133 private @Nullable E effectiveInstance;
136 private boolean isSupportedToBuildEffective = true;
137 private boolean fullyDefined;
139 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above booleans and
140 // hence improve memory layout.
143 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
144 final String rawArgument) {
145 this.definition = requireNonNull(def);
146 this.statementDeclSource = requireNonNull(ref);
147 this.rawArgument = def.internArgument(rawArgument);
148 this.copyHistory = CopyHistory.original();
149 this.originalCtx = null;
150 this.prevCopyCtx = null;
153 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
154 final String rawArgument, final CopyType copyType) {
155 this.definition = requireNonNull(def);
156 this.statementDeclSource = requireNonNull(ref);
157 this.rawArgument = rawArgument;
158 this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
159 this.originalCtx = null;
160 this.prevCopyCtx = null;
163 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
164 this.definition = original.definition;
165 this.statementDeclSource = original.statementDeclSource;
166 this.rawArgument = original.rawArgument;
167 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
168 this.originalCtx = original.getOriginalCtx().orElse(original);
169 this.prevCopyCtx = original;
172 StatementContextBase(final StatementContextBase<A, D, E> original) {
173 this.definition = original.definition;
174 this.statementDeclSource = original.statementDeclSource;
175 this.rawArgument = original.rawArgument;
176 this.copyHistory = original.getCopyHistory();
177 this.originalCtx = original.getOriginalCtx().orElse(original);
178 this.prevCopyCtx = original;
179 this.substatements = original.substatements;
180 this.effective = original.effective;
184 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
185 return effectOfStatement;
189 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
190 if (effectOfStatement.isEmpty()) {
191 effectOfStatement = new ArrayList<>(1);
193 effectOfStatement.add(ctx);
197 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
198 if (ctxs.isEmpty()) {
202 if (effectOfStatement.isEmpty()) {
203 effectOfStatement = new ArrayList<>(ctxs.size());
205 effectOfStatement.addAll(ctxs);
209 public boolean isSupportedByFeatures() {
210 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
212 return fl == SET_SUPPORTED_BY_FEATURES;
214 if (isIgnoringIfFeatures()) {
215 flags |= SET_SUPPORTED_BY_FEATURES;
220 * If parent is supported, we need to check if-features statements of this context.
222 if (isParentSupportedByFeatures()) {
223 // If the set of supported features has not been provided, all features are supported by default.
224 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
225 SupportedFeatures.SUPPORTED_FEATURES);
226 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
227 flags |= SET_SUPPORTED_BY_FEATURES;
232 // Either parent is not supported or this statement is not supported
233 flags |= HAVE_SUPPORTED_BY_FEATURES;
237 protected abstract boolean isParentSupportedByFeatures();
240 public boolean isSupportedToBuildEffective() {
241 return isSupportedToBuildEffective;
245 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
246 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
250 public CopyHistory getCopyHistory() {
255 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
256 return Optional.ofNullable(originalCtx);
260 public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
261 return Optional.ofNullable(prevCopyCtx);
265 public ModelProcessingPhase getCompletedPhase() {
266 return completedPhase;
270 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
271 this.completedPhase = completedPhase;
275 public abstract StatementContextBase<?, ?, ?> getParentContext();
278 * Returns the model root for this statement.
280 * @return root context of statement
283 public abstract RootStatementContext<?, ?, ?> getRoot();
286 public StatementSource getStatementSource() {
287 return statementDeclSource.getStatementSource();
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 private void shrinkEffective() {
325 if (effective.isEmpty()) {
326 effective = ImmutableList.of();
330 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
331 if (effective.isEmpty()) {
335 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
336 while (iterator.hasNext()) {
337 final StmtContext<?, ?, ?> next = iterator.next();
338 if (statementDef.equals(next.getPublicDefinition())) {
347 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
348 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
349 * definition and statement argument match with one of the effective substatements' statement definition
353 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
355 * @param statementDef statement definition of the statement context to remove
356 * @param statementArg statement argument of the statement context to remove
358 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
359 final String statementArg) {
360 if (statementArg == null) {
361 removeStatementFromEffectiveSubstatements(statementDef);
364 if (effective.isEmpty()) {
368 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
369 while (iterator.hasNext()) {
370 final Mutable<?, ?, ?> next = iterator.next();
371 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
380 * Adds an effective statement to collection of substatements.
382 * @param substatement substatement
383 * @throws IllegalStateException
384 * if added in declared phase
385 * @throws NullPointerException
386 * if statement parameter is null
388 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
389 beforeAddEffectiveStatement(1);
390 effective.add(substatement);
394 * Adds an effective statement to collection of substatements.
396 * @param statements substatements
397 * @throws IllegalStateException
398 * if added in declared phase
399 * @throws NullPointerException
400 * if statement parameter is null
402 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
403 if (statements.isEmpty()) {
407 statements.forEach(Objects::requireNonNull);
408 beforeAddEffectiveStatement(statements.size());
409 effective.addAll(statements);
412 private void beforeAddEffectiveStatement(final int toAdd) {
413 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
414 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
415 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
416 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
418 if (effective.isEmpty()) {
419 effective = new ArrayList<>(toAdd);
424 * Create a new substatement at the specified offset.
426 * @param offset Substatement offset
427 * @param def definition context
428 * @param ref source reference
429 * @param argument statement argument
430 * @param <X> new substatement argument type
431 * @param <Y> new substatement declared type
432 * @param <Z> new substatement effective type
433 * @return A new substatement
435 @SuppressWarnings("checkstyle:methodTypeParameterName")
436 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
437 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
438 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
439 final String argument) {
440 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
441 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
442 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
444 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
445 if (implicitParent.isPresent()) {
446 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
450 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
451 substatements = substatements.put(offset, ret);
452 def.onStatementAdded(ret);
456 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
457 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
458 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
459 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
462 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
463 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
464 ImplicitSubstatement.of(getStatementSourceReference()), null);
468 * Lookup substatement by its offset in this statement.
470 * @param offset Substatement offset
471 * @return Substatement, or null if substatement does not exist.
473 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
474 return substatements.get(offset);
477 final void setFullyDefined() {
478 this.fullyDefined = true;
481 final void resizeSubstatements(final int expectedSize) {
482 substatements = substatements.ensureCapacity(expectedSize);
485 final void walkChildren(final ModelProcessingPhase phase) {
486 checkState(fullyDefined);
487 substatements.values().forEach(stmt -> {
488 stmt.walkChildren(phase);
489 stmt.endDeclared(phase);
494 public D buildDeclared() {
495 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
496 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
497 if (declaredInstance == null) {
498 declaredInstance = definition().getFactory().createDeclared(this);
500 return declaredInstance;
504 public E buildEffective() {
505 if (effectiveInstance == null) {
506 effectiveInstance = definition().getFactory().createEffective(this);
508 return effectiveInstance;
512 * tries to execute current {@link ModelProcessingPhase} of source parsing.
515 * to be executed (completed)
516 * @return if phase was successfully completed
517 * @throws SourceException
518 * when an error occurred in source parsing
520 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
522 boolean finished = true;
523 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
524 if (!openMutations.isEmpty()) {
525 final Iterator<ContextMutation> it = openMutations.iterator();
526 while (it.hasNext()) {
527 final ContextMutation current = it.next();
528 if (current.isFinished()) {
535 if (openMutations.isEmpty()) {
536 phaseMutation.removeAll(phase);
537 if (phaseMutation.isEmpty()) {
538 phaseMutation = ImmutableMultimap.of();
543 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
544 finished &= child.tryToCompletePhase(phase);
546 for (final Mutable<?, ?, ?> child : effective) {
547 if (child instanceof StatementContextBase) {
548 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
553 onPhaseCompleted(phase);
560 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
563 * that was to be completed (finished)
564 * @throws SourceException
565 * when an error occurred in source parsing
567 private void onPhaseCompleted(final ModelProcessingPhase phase) {
568 completedPhase = phase;
570 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
571 if (listeners.isEmpty()) {
575 final Iterator<OnPhaseFinished> listener = listeners.iterator();
576 while (listener.hasNext()) {
577 final OnPhaseFinished next = listener.next();
578 if (next.phaseFinished(this, phase)) {
583 if (listeners.isEmpty()) {
584 phaseListeners.removeAll(phase);
585 if (phaseListeners.isEmpty()) {
586 phaseListeners = ImmutableMultimap.of();
592 * Ends declared section of current node.
594 void endDeclared(final ModelProcessingPhase phase) {
595 definition().onDeclarationFinished(this, phase);
599 * Return the context in which this statement was defined.
601 * @return statement definition
603 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
608 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
609 definition().checkNamespaceAllowed(type);
613 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
615 // definition().onNamespaceElementAdded(this, type, key, value);
618 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
619 final OnNamespaceItemAdded listener) {
620 final Object potential = getFromNamespace(type, key);
621 if (potential != null) {
622 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
623 listener.namespaceItemAdded(this, type, key, potential);
627 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
629 void onValueAdded(final Object value) {
630 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
635 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
636 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
637 final OnNamespaceItemAdded listener) {
638 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
639 if (existing.isPresent()) {
640 final Entry<K, V> entry = existing.get();
641 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
642 waitForPhase(entry.getValue(), type, phase, criterion, listener);
646 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
647 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
649 boolean onValueAdded(final K key, final V value) {
650 if (criterion.match(key)) {
651 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
652 waitForPhase(value, type, phase, criterion, listener);
661 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
662 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
663 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
664 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
666 final Entry<K, V> match = optMatch.get();
667 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
670 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
671 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
672 final OnNamespaceItemAdded listener) {
673 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
674 (context, phaseCompleted) -> {
675 selectMatch(type, criterion, listener);
680 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
681 final Class<N> type) {
682 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
683 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
686 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
690 public StatementDefinition getPublicDefinition() {
691 return definition().getPublicView();
695 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
696 return getRoot().getSourceContext().newInferenceAction(phase);
699 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
700 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
704 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
705 * the listener is notified immediately.
707 * @param phase requested completion phase
708 * @param listener listener to invoke
709 * @throws NullPointerException if any of the arguments is null
711 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
712 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
713 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
715 ModelProcessingPhase finishedPhase = completedPhase;
716 while (finishedPhase != null) {
717 if (phase.equals(finishedPhase)) {
718 listener.phaseFinished(this, finishedPhase);
721 finishedPhase = finishedPhase.getPreviousPhase();
723 if (phaseListeners.isEmpty()) {
724 phaseListeners = newMultimap();
727 phaseListeners.put(phase, listener);
731 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
733 * @throws IllegalStateException
734 * when the mutation was registered after phase was completed
736 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
737 ModelProcessingPhase finishedPhase = completedPhase;
738 while (finishedPhase != null) {
739 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
740 getStatementSourceReference());
741 finishedPhase = finishedPhase.getPreviousPhase();
744 if (phaseMutation.isEmpty()) {
745 phaseMutation = newMultimap();
747 phaseMutation.put(phase, mutation);
751 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
752 final KT key,final StmtContext<?, ?, ?> stmt) {
753 addContextToNamespace(namespace, key, stmt);
757 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
758 final QNameModule targetModule) {
759 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
760 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
761 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
762 return childCopyOf((SubstatementContext<?, ?, ?>) stmt, type, targetModule);
765 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
766 final SubstatementContext<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
767 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
768 original.getPublicDefinition());
770 final SubstatementContext<X, Y, Z> result;
771 final SubstatementContext<X, Y, Z> copy;
773 if (implicitParent.isPresent()) {
774 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
775 result = new SubstatementContext(this, def, original.getSourceReference(),
776 original.rawStatementArgument(), original.getStatementArgument(), type);
778 final CopyType childCopyType;
780 case ADDED_BY_AUGMENTATION:
781 childCopyType = CopyType.ORIGINAL;
783 case ADDED_BY_USES_AUGMENTATION:
784 childCopyType = CopyType.ADDED_BY_USES;
789 childCopyType = type;
792 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
793 result.addEffectiveSubstatement(copy);
795 result = copy = new SubstatementContext<>(original, this, type, targetModule);
798 original.definition().onStatementAdded(copy);
799 original.copyTo(copy, type, targetModule);
804 public @NonNull StatementDefinition getDefinition() {
805 return getPublicDefinition();
809 public @NonNull StatementSourceReference getSourceReference() {
810 return getStatementSourceReference();
814 public boolean isFullyDefined() {
819 public final boolean hasImplicitParentSupport() {
820 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
824 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
825 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
826 original.getPublicDefinition());
827 if (optImplicit.isEmpty()) {
831 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
832 final CopyType type = original.getCopyHistory().getLastOperation();
833 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
834 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
837 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
838 result.setCompletedPhase(original.getCompletedPhase());
843 * Config statements are not all that common which means we are performing a recursive search towards the root
844 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
845 * for the (usually non-existent) config statement.
848 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
849 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
851 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
852 if (isIgnoringConfig()) {
855 final int fl = flags & SET_CONFIGURATION;
857 return fl == SET_CONFIGURATION;
859 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
860 ConfigStatement.class);
861 final boolean parentIsConfig = parent.isConfiguration();
863 final boolean isConfig;
864 if (configStatement != null) {
865 isConfig = configStatement.coerceStatementArgument();
867 // Validity check: if parent is config=false this cannot be a config=true
868 InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
869 "Parent node has config=false, this node must not be specifed as config=true");
871 // If "config" statement is not specified, the default is the same as the parent's "config" value.
872 isConfig = parentIsConfig;
875 // Resolved, make sure we cache this return
876 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
880 protected abstract boolean isIgnoringConfig();
883 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
884 * keep on returning the same result without performing any lookups. Exists only to support
885 * {@link SubstatementContext#isIgnoringConfig()}.
887 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
888 final int fl = flags & SET_IGNORE_CONFIG;
890 return fl == SET_IGNORE_CONFIG;
892 if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
893 flags |= SET_IGNORE_CONFIG;
897 flags |= HAVE_IGNORE_CONFIG;
901 protected abstract boolean isIgnoringIfFeatures();
904 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
905 * keep on returning the same result without performing any lookups. Exists only to support
906 * {@link SubstatementContext#isIgnoringIfFeatures()}.
908 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
909 final int fl = flags & SET_IGNORE_IF_FEATURE;
911 return fl == SET_IGNORE_IF_FEATURE;
913 if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
914 flags |= SET_IGNORE_IF_FEATURE;
918 flags |= HAVE_IGNORE_IF_FEATURE;
922 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
923 @Nullable final QNameModule targetModule) {
924 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
926 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
927 if (stmtContext.isSupportedByFeatures()) {
928 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
932 for (final Mutable<?, ?, ?> stmtContext : effective) {
933 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
936 target.addEffectiveSubstatements(buffer);
939 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
940 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
941 if (needToCopyByUses(stmtContext)) {
942 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
943 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
945 } else if (isReusedByUses(stmtContext)) {
946 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
947 buffer.add(stmtContext);
949 LOG.debug("Skipping statement {}", stmtContext);
953 // FIXME: revise this, as it seems to be wrong
954 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
955 YangStmtMapping.DESCRIPTION,
956 YangStmtMapping.REFERENCE,
957 YangStmtMapping.STATUS);
958 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
959 YangStmtMapping.TYPE,
960 YangStmtMapping.TYPEDEF,
961 YangStmtMapping.USES);
963 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
964 final StatementDefinition def = stmtContext.getPublicDefinition();
965 if (REUSED_DEF_SET.contains(def)) {
966 LOG.debug("Will reuse {} statement {}", def, stmtContext);
969 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
970 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
973 LOG.debug("Will copy {} statement {}", def, stmtContext);
977 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
978 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
982 public final String toString() {
983 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
986 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
987 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);