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);
326 private void shrinkEffective() {
327 if (effective.isEmpty()) {
328 effective = ImmutableList.of();
332 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
333 if (effective.isEmpty()) {
337 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
338 while (iterator.hasNext()) {
339 final StmtContext<?, ?, ?> next = iterator.next();
340 if (statementDef.equals(next.getPublicDefinition())) {
349 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
350 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
351 * definition and statement argument match with one of the effective substatements' statement definition
355 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
357 * @param statementDef statement definition of the statement context to remove
358 * @param statementArg statement argument of the statement context to remove
360 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
361 final String statementArg) {
362 if (statementArg == null) {
363 removeStatementFromEffectiveSubstatements(statementDef);
366 if (effective.isEmpty()) {
370 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
371 while (iterator.hasNext()) {
372 final Mutable<?, ?, ?> next = iterator.next();
373 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
382 * Adds an effective statement to collection of substatements.
384 * @param substatement substatement
385 * @throws IllegalStateException
386 * if added in declared phase
387 * @throws NullPointerException
388 * if statement parameter is null
390 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
391 beforeAddEffectiveStatement(1);
392 effective.add(substatement);
396 * Adds an effective statement to collection of substatements.
398 * @param statements substatements
399 * @throws IllegalStateException
400 * if added in declared phase
401 * @throws NullPointerException
402 * if statement parameter is null
404 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
405 if (statements.isEmpty()) {
409 statements.forEach(Objects::requireNonNull);
410 beforeAddEffectiveStatement(statements.size());
411 effective.addAll(statements);
414 private void beforeAddEffectiveStatement(final int toAdd) {
415 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
416 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
417 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
418 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
420 if (effective.isEmpty()) {
421 effective = new ArrayList<>(toAdd);
426 * Create a new substatement at the specified offset.
428 * @param offset Substatement offset
429 * @param def definition context
430 * @param ref source reference
431 * @param argument statement argument
432 * @param <X> new substatement argument type
433 * @param <Y> new substatement declared type
434 * @param <Z> new substatement effective type
435 * @return A new substatement
437 @SuppressWarnings("checkstyle:methodTypeParameterName")
438 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
439 StatementContextBase<X, Y, Z> createSubstatement(final int offset,
440 final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
441 final String argument) {
442 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
443 checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
444 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
446 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
447 if (implicitParent.isPresent()) {
448 return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
452 final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
453 substatements = substatements.put(offset, ret);
454 def.onStatementAdded(ret);
458 private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
459 final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
460 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
461 return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
464 public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
465 createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
466 ImplicitSubstatement.of(getStatementSourceReference()), null);
470 * Lookup substatement by its offset in this statement.
472 * @param offset Substatement offset
473 * @return Substatement, or null if substatement does not exist.
475 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
476 return substatements.get(offset);
479 final void setFullyDefined() {
480 this.fullyDefined = true;
483 final void resizeSubstatements(final int expectedSize) {
484 substatements = substatements.ensureCapacity(expectedSize);
487 final void walkChildren(final ModelProcessingPhase phase) {
488 checkState(fullyDefined);
489 substatements.values().forEach(stmt -> {
490 stmt.walkChildren(phase);
491 stmt.endDeclared(phase);
496 public D buildDeclared() {
497 checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
498 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
499 if (declaredInstance == null) {
500 declaredInstance = definition().getFactory().createDeclared(this);
502 return declaredInstance;
506 public E buildEffective() {
507 if (effectiveInstance == null) {
508 effectiveInstance = definition().getFactory().createEffective(this);
510 return effectiveInstance;
514 * tries to execute current {@link ModelProcessingPhase} of source parsing.
517 * to be executed (completed)
518 * @return if phase was successfully completed
519 * @throws SourceException
520 * when an error occurred in source parsing
522 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
524 boolean finished = true;
525 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
526 if (!openMutations.isEmpty()) {
527 final Iterator<ContextMutation> it = openMutations.iterator();
528 while (it.hasNext()) {
529 final ContextMutation current = it.next();
530 if (current.isFinished()) {
537 if (openMutations.isEmpty()) {
538 phaseMutation.removeAll(phase);
539 if (phaseMutation.isEmpty()) {
540 phaseMutation = ImmutableMultimap.of();
545 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
546 finished &= child.tryToCompletePhase(phase);
548 for (final Mutable<?, ?, ?> child : effective) {
549 if (child instanceof StatementContextBase) {
550 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
555 onPhaseCompleted(phase);
562 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
565 * that was to be completed (finished)
566 * @throws SourceException
567 * when an error occurred in source parsing
569 private void onPhaseCompleted(final ModelProcessingPhase phase) {
570 completedPhase = phase;
572 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
573 if (listeners.isEmpty()) {
577 final Iterator<OnPhaseFinished> listener = listeners.iterator();
578 while (listener.hasNext()) {
579 final OnPhaseFinished next = listener.next();
580 if (next.phaseFinished(this, phase)) {
585 if (listeners.isEmpty()) {
586 phaseListeners.removeAll(phase);
587 if (phaseListeners.isEmpty()) {
588 phaseListeners = ImmutableMultimap.of();
594 * Ends declared section of current node.
596 void endDeclared(final ModelProcessingPhase phase) {
597 definition().onDeclarationFinished(this, phase);
601 * Return the context in which this statement was defined.
603 * @return statement definition
605 protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
610 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
611 definition().checkNamespaceAllowed(type);
615 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
617 // definition().onNamespaceElementAdded(this, type, key, value);
620 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
621 final OnNamespaceItemAdded listener) {
622 final Object potential = getFromNamespace(type, key);
623 if (potential != null) {
624 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
625 listener.namespaceItemAdded(this, type, key, potential);
629 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
631 void onValueAdded(final Object value) {
632 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
637 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
638 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
639 final OnNamespaceItemAdded listener) {
640 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
641 if (existing.isPresent()) {
642 final Entry<K, V> entry = existing.get();
643 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
644 waitForPhase(entry.getValue(), type, phase, criterion, listener);
648 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
649 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
651 boolean onValueAdded(final K key, final V value) {
652 if (criterion.match(key)) {
653 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
654 waitForPhase(value, type, phase, criterion, listener);
663 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
664 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
665 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
666 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
668 final Entry<K, V> match = optMatch.get();
669 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
672 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
673 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
674 final OnNamespaceItemAdded listener) {
675 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
676 (context, phaseCompleted) -> {
677 selectMatch(type, criterion, listener);
682 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
683 final Class<N> type) {
684 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
685 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
688 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
692 public StatementDefinition getPublicDefinition() {
693 return definition().getPublicView();
697 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
698 return getRoot().getSourceContext().newInferenceAction(phase);
701 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
702 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
706 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
707 * the listener is notified immediately.
709 * @param phase requested completion phase
710 * @param listener listener to invoke
711 * @throws NullPointerException if any of the arguments is null
713 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
714 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
715 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
717 ModelProcessingPhase finishedPhase = completedPhase;
718 while (finishedPhase != null) {
719 if (phase.equals(finishedPhase)) {
720 listener.phaseFinished(this, finishedPhase);
723 finishedPhase = finishedPhase.getPreviousPhase();
725 if (phaseListeners.isEmpty()) {
726 phaseListeners = newMultimap();
729 phaseListeners.put(phase, listener);
733 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
735 * @throws IllegalStateException
736 * when the mutation was registered after phase was completed
738 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
739 ModelProcessingPhase finishedPhase = completedPhase;
740 while (finishedPhase != null) {
741 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
742 getStatementSourceReference());
743 finishedPhase = finishedPhase.getPreviousPhase();
746 if (phaseMutation.isEmpty()) {
747 phaseMutation = newMultimap();
749 phaseMutation.put(phase, mutation);
753 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
754 final KT key,final StmtContext<?, ?, ?> stmt) {
755 addContextToNamespace(namespace, key, stmt);
759 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
760 final QNameModule targetModule) {
761 checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
762 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
763 checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
764 return childCopyOf((SubstatementContext<?, ?, ?>) stmt, type, targetModule);
767 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
768 final SubstatementContext<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
769 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
770 original.getPublicDefinition());
772 final SubstatementContext<X, Y, Z> result;
773 final SubstatementContext<X, Y, Z> copy;
775 if (implicitParent.isPresent()) {
776 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
777 result = new SubstatementContext(this, def, original.getSourceReference(),
778 original.rawStatementArgument(), original.getStatementArgument(), type);
780 final CopyType childCopyType;
782 case ADDED_BY_AUGMENTATION:
783 childCopyType = CopyType.ORIGINAL;
785 case ADDED_BY_USES_AUGMENTATION:
786 childCopyType = CopyType.ADDED_BY_USES;
791 childCopyType = type;
794 copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
795 result.addEffectiveSubstatement(copy);
797 result = copy = new SubstatementContext<>(original, this, type, targetModule);
800 original.definition().onStatementAdded(copy);
801 original.copyTo(copy, type, targetModule);
806 public @NonNull StatementDefinition getDefinition() {
807 return getPublicDefinition();
811 public @NonNull StatementSourceReference getSourceReference() {
812 return getStatementSourceReference();
816 public boolean isFullyDefined() {
821 public final boolean hasImplicitParentSupport() {
822 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
826 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
827 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
828 original.getPublicDefinition());
829 if (optImplicit.isEmpty()) {
833 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
834 final CopyType type = original.getCopyHistory().getLastOperation();
835 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
836 original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
839 result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
840 result.setCompletedPhase(original.getCompletedPhase());
845 * Config statements are not all that common which means we are performing a recursive search towards the root
846 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
847 * for the (usually non-existent) config statement.
850 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
851 * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
854 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
855 * {@link #isIgnoringConfig(StatementContextBase)}.
857 final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
858 final int fl = flags & SET_CONFIGURATION;
860 return fl == SET_CONFIGURATION;
862 if (isIgnoringConfig(parent)) {
863 // Note: SET_CONFIGURATION has been stored in flags
867 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
868 ConfigStatement.class);
869 final boolean isConfig;
870 if (configStatement != null) {
871 isConfig = configStatement.coerceStatementArgument();
873 // Validity check: if parent is config=false this cannot be a config=true
874 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
875 "Parent node has config=false, this node must not be specifed as config=true");
878 // If "config" statement is not specified, the default is the same as the parent's "config" value.
879 isConfig = parent.isConfiguration();
882 // Resolved, make sure we cache this return
883 flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
887 protected abstract boolean isIgnoringConfig();
890 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
891 * keep on returning the same result without performing any lookups. Exists only to support
892 * {@link SubstatementContext#isIgnoringConfig()}.
895 * Note: use of this method implies that {@link #isConfiguration()} is realized with
896 * {@link #isConfiguration(StatementContextBase)}.
898 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
899 final int fl = flags & SET_IGNORE_CONFIG;
901 return fl == SET_IGNORE_CONFIG;
903 if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
904 flags |= SET_IGNORE_CONFIG;
908 flags |= HAVE_IGNORE_CONFIG;
912 protected abstract boolean isIgnoringIfFeatures();
915 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
916 * keep on returning the same result without performing any lookups. Exists only to support
917 * {@link SubstatementContext#isIgnoringIfFeatures()}.
919 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
920 final int fl = flags & SET_IGNORE_IF_FEATURE;
922 return fl == SET_IGNORE_IF_FEATURE;
924 if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
925 flags |= SET_IGNORE_IF_FEATURE;
929 flags |= HAVE_IGNORE_IF_FEATURE;
933 final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
934 @Nullable final QNameModule targetModule) {
935 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
937 for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
938 if (stmtContext.isSupportedByFeatures()) {
939 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
943 for (final Mutable<?, ?, ?> stmtContext : effective) {
944 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
947 target.addEffectiveSubstatements(buffer);
950 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
951 final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
952 if (needToCopyByUses(stmtContext)) {
953 final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
954 LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
956 } else if (isReusedByUses(stmtContext)) {
957 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
958 buffer.add(stmtContext);
960 LOG.debug("Skipping statement {}", stmtContext);
964 // FIXME: revise this, as it seems to be wrong
965 private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
966 YangStmtMapping.DESCRIPTION,
967 YangStmtMapping.REFERENCE,
968 YangStmtMapping.STATUS);
969 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
970 YangStmtMapping.TYPE,
971 YangStmtMapping.TYPEDEF,
972 YangStmtMapping.USES);
974 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
975 final StatementDefinition def = stmtContext.getPublicDefinition();
976 if (REUSED_DEF_SET.contains(def)) {
977 LOG.debug("Will reuse {} statement {}", def, stmtContext);
980 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
981 return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
984 LOG.debug("Will copy {} statement {}", def, stmtContext);
988 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
989 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
993 public final String toString() {
994 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
997 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
998 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);