2 * Copyright (c) 2015, 2016 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.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.EFFECTIVE_MODEL;
15 import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.FULL_DECLARATION;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import java.util.ArrayList;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.function.Function;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
34 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.ContextMutation;
35 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnNamespaceItemAdded;
36 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnPhaseFinished;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
40 final class ModifierImpl implements ModelActionBuilder {
41 private static final Logger LOG = LoggerFactory.getLogger(ModifierImpl.class);
43 private final Set<AbstractPrerequisite<?>> unsatisfied = new HashSet<>(1);
44 private final Set<AbstractPrerequisite<?>> mutations = new HashSet<>(1);
45 private final InferenceContext ctx = new InferenceContext() { };
47 private List<Runnable> bootstraps;
48 private InferenceAction action;
49 private boolean actionApplied;
51 private <D> AbstractPrerequisite<D> addReq(final AbstractPrerequisite<D> prereq) {
52 LOG.trace("Modifier {} adding prerequisite {}", this, prereq);
53 unsatisfied.add(prereq);
57 private <T> @NonNull AbstractPrerequisite<T> addMutation(final @NonNull AbstractPrerequisite<T> mutation) {
58 LOG.trace("Modifier {} adding mutation {}", this, mutation);
59 mutations.add(mutation);
63 private void checkNotRegistered() {
64 checkState(action == null, "Action was already registered.");
67 private boolean removeSatisfied() {
68 final Iterator<AbstractPrerequisite<?>> it = unsatisfied.iterator();
69 while (it.hasNext()) {
70 final AbstractPrerequisite<?> prereq = it.next();
71 if (prereq.isDone()) {
72 // We are removing current prerequisite from list.
73 LOG.trace("Modifier {} prerequisite {} satisfied", this, prereq);
77 return unsatisfied.isEmpty();
86 action.prerequisiteFailed(unsatisfied);
90 private <K, C extends StmtContext<?, ?, ?>> @NonNull AbstractPrerequisite<C> requiresCtxImpl(
91 final StmtContext<?, ?, ?> context, final ParserNamespace<K, C> namespace, final K key,
92 final ModelProcessingPhase phase) {
95 AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
97 contextImpl(context).onNamespaceItemAddedAction(namespace, key, addedToNs);
101 private <K, C extends StmtContext<?, ?, ?>> @NonNull AbstractPrerequisite<C> requiresCtxImpl(
102 final StmtContext<?, ?, ?> context, final ParserNamespace<K, C> namespace,
103 final NamespaceKeyCriterion<K> criterion, final ModelProcessingPhase phase) {
104 checkNotRegistered();
106 AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
108 contextImpl(context).onNamespaceItemAddedAction(namespace, phase, criterion, addedToNs);
112 private <C extends StmtContext<?, ?, ?>> @NonNull AbstractPrerequisite<C> requiresCtxImpl(final C context,
113 final ModelProcessingPhase phase) {
114 checkNotRegistered();
116 PhaseFinished<C> phaseFin = new PhaseFinished<>();
118 addBootstrap(() -> contextImpl(context).addPhaseCompletedListener(phase, phaseFin));
122 @SuppressWarnings({ "rawtypes", "unchecked" })
123 private <K, C extends Mutable<?, ?, ?>> AbstractPrerequisite<C> mutatesCtxImpl(final StmtContext<?, ?, ?> context,
124 final ParserNamespace<K, ? extends StmtContext<?, ?, ?>> namespace, final K key,
125 final ModelProcessingPhase phase) {
126 checkNotRegistered();
128 final PhaseModificationInNamespace<C> mod = new PhaseModificationInNamespace<>(EFFECTIVE_MODEL);
131 contextImpl(context).onNamespaceItemAddedAction((ParserNamespace) namespace, key, mod);
135 private static StatementContextBase<?, ?, ?> contextImpl(final Object value) {
136 checkArgument(value instanceof StatementContextBase, "Supplied context %s is not provided by this reactor.",
138 return StatementContextBase.class.cast(value);
142 checkState(action != null, "Action was not defined yet.");
144 if (removeSatisfied()) {
145 if (!actionApplied) {
147 actionApplied = true;
155 public <C extends Mutable<?, ?, ?>, T extends C> Prerequisite<C> mutatesCtx(final T context,
156 final ModelProcessingPhase phase) {
157 return addMutation(new PhaseMutation<>(contextImpl(context), phase));
161 public <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
162 AbstractPrerequisite<StmtContext<A, D, E>> requiresCtx(final StmtContext<A, D, E> context,
163 final ModelProcessingPhase phase) {
164 return requiresCtxImpl(context, phase);
168 public <K, C extends StmtContext<?, ?, ?>> Prerequisite<C> requiresCtx(final StmtContext<?, ?, ?> context,
169 final ParserNamespace<K, C> namespace, final K key, final ModelProcessingPhase phase) {
170 return requiresCtxImpl(context, namespace, key, phase);
174 public <K, C extends StmtContext<?, ?, ?>> Prerequisite<C> requiresCtx(final StmtContext<?, ?, ?> context,
175 final ParserNamespace<K, C> namespace, final NamespaceKeyCriterion<K> criterion,
176 final ModelProcessingPhase phase) {
177 return requiresCtxImpl(context, namespace, criterion, phase);
181 public <K, C extends StmtContext<?, ?, ?>> Prerequisite<C> requiresCtxPath(final StmtContext<?, ?, ?> context,
182 final ParserNamespace<K, C> namespace, final Iterable<K> keys, final ModelProcessingPhase phase) {
183 checkNotRegistered();
185 final var ret = new PhaseRequirementInNamespacePath<C, K>(EFFECTIVE_MODEL, keys);
187 addBootstrap(() -> ret.hookOnto(context, namespace));
192 public <D extends DeclaredStatement<?>> Prerequisite<D> requiresDeclared(
193 final StmtContext<?, ? extends D, ?> context) {
194 return requiresCtxImpl(context, FULL_DECLARATION).transform(StmtContext::declared);
199 public <K, D extends DeclaredStatement<?>> Prerequisite<D> requiresDeclared(final StmtContext<?, ?, ?> context,
200 final ParserNamespace<K, StmtContext<?, ? extends D, ?>> namespace, final K key) {
201 return requiresCtxImpl(context, namespace, key, FULL_DECLARATION).transform(StmtContext::declared);
206 public <K, C extends StmtContext<?, ?, ?>> AbstractPrerequisite<C> requiresDeclaredCtx(
207 final StmtContext<?, ?, ?> context, final ParserNamespace<K, C> namespace, final K key) {
208 return requiresCtxImpl(context, namespace, key, FULL_DECLARATION);
213 public <E extends EffectiveStatement<?, ?>> Prerequisite<E> requiresEffective(
214 final StmtContext<?, ?, ? extends E> stmt) {
215 return requiresCtxImpl(stmt, EFFECTIVE_MODEL).transform(StmtContext::buildEffective);
220 public <K, E extends EffectiveStatement<?, ?>> Prerequisite<E> requiresEffective(final StmtContext<?, ?, ?> context,
221 final ParserNamespace<K, StmtContext<?, ?, ? extends E>> namespace, final K key) {
222 return requiresCtxImpl(context, namespace, key, EFFECTIVE_MODEL).transform(StmtContext::buildEffective);
227 public <K, C extends StmtContext<?, ?, ?>> AbstractPrerequisite<C> requiresEffectiveCtx(
228 final StmtContext<?, ?, ?> context, final ParserNamespace<K, C> namespace, final K key) {
229 return requiresCtxImpl(contextImpl(context), namespace, key, EFFECTIVE_MODEL);
234 public Prerequisite<Mutable<?, ?, ?>> mutatesNs(final Mutable<?, ?, ?> context,
235 final ParserNamespace<?, ?> namespace) {
236 return addMutation(new NamespaceMutation(contextImpl(context), namespace));
240 public <K, E extends EffectiveStatement<?, ?>> AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtx(
241 final StmtContext<?, ?, ?> context, final ParserNamespace<K, ? extends StmtContext<?, ?, ?>> namespace,
243 return mutatesCtxImpl(context, namespace, key, EFFECTIVE_MODEL);
247 public <K, E extends EffectiveStatement<?, ?>> AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtxPath(
248 final StmtContext<?, ?, ?> context, final ParserNamespace<K, ? extends StmtContext<?, ?, ?>> namespace,
249 final Iterable<K> keys) {
250 checkNotRegistered();
252 final var ret = new PhaseModificationInNamespacePath<Mutable<?, ?, E>, K>(EFFECTIVE_MODEL, keys);
255 addBootstrap(() -> ret.hookOnto(context, namespace));
260 @SuppressWarnings("checkstyle:hiddenField")
261 public void apply(final InferenceAction action) {
262 checkState(this.action == null, "Action already defined to %s", this.action);
263 this.action = requireNonNull(action);
264 if (bootstraps != null) {
265 bootstraps.forEach(Runnable::run);
270 private void addBootstrap(final Runnable bootstrap) {
271 if (bootstraps == null) {
272 bootstraps = new ArrayList<>(1);
274 bootstraps.add(bootstrap);
277 private abstract class AbstractPrerequisite<T> implements Prerequisite<T> {
278 private boolean done = false;
282 @SuppressWarnings("checkstyle:hiddenField")
283 public final T resolve(final InferenceContext ctx) {
285 checkArgument(ctx == ModifierImpl.this.ctx);
286 return verifyNotNull(value, "Attempted to access unavailable prerequisite %s", this);
289 final boolean isDone() {
293 @SuppressWarnings("checkstyle:hiddenField")
294 final boolean resolvePrereq(final T value) {
300 final <O> @NonNull Prerequisite<O> transform(final Function<? super T, O> transformation) {
301 return context -> transformation.apply(resolve(context));
305 public final String toString() {
306 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
309 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
310 return toStringHelper.add("value", value);
314 private abstract class AbstractPathPrerequisite<C extends StmtContext<?, ?, ?>, K> extends AbstractPrerequisite<C>
315 implements OnNamespaceItemAdded {
316 private final ModelProcessingPhase modPhase;
317 private final Iterable<K> keys;
318 private final Iterator<K> it;
320 AbstractPathPrerequisite(final ModelProcessingPhase phase, final Iterable<K> keys) {
321 this.modPhase = requireNonNull(phase);
322 this.keys = requireNonNull(keys);
323 it = keys.iterator();
327 public final void namespaceItemAdded(final StatementContextBase<?, ?, ?> context,
328 final ParserNamespace<?, ?> namespace, final Object key, final Object value) {
329 LOG.debug("Action for {} got key {}", keys, key);
331 final StatementContextBase<?, ?, ?> target = contextImpl(value);
332 if (!target.isSupportedByFeatures()) {
333 LOG.debug("Key {} in {} is not supported", key, keys);
335 action.prerequisiteUnavailable(this);
339 nextStep(modPhase, context, target);
342 // Last step: we are done
343 if (resolvePrereq((C) value)) {
349 // Make sure target's storage notifies us when the next step becomes available.
350 hookOnto(target, namespace, it.next());
353 abstract void nextStep(ModelProcessingPhase phase, StatementContextBase<?, ?, ?> current,
354 StatementContextBase<?, ?, ?> next);
357 final ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
358 return super.addToStringAttributes(toStringHelper).add("phase", modPhase).add("keys", keys);
361 final void hookOnto(final StmtContext<?, ?, ?> context, final ParserNamespace<?, ?> namespace) {
362 checkArgument(it.hasNext(), "Namespace %s keys may not be empty", namespace);
363 hookOnto(contextImpl(context), namespace, it.next());
366 @SuppressWarnings("unchecked")
367 private void hookOnto(final StatementContextBase<?, ?, ?> context, final ParserNamespace<?, ?> namespace,
369 context.onNamespaceItemAddedAction((ParserNamespace) namespace, requireNonNull(key), this);
373 private final class PhaseMutation<C> extends AbstractPrerequisite<C> implements ContextMutation {
374 @SuppressWarnings("unchecked")
375 PhaseMutation(final StatementContextBase<?, ?, ?> context, final ModelProcessingPhase phase) {
376 context.addMutation(phase, this);
377 resolvePrereq((C) context);
381 public boolean isFinished() {
386 private final class PhaseFinished<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
387 implements OnPhaseFinished {
388 @SuppressWarnings("unchecked")
390 public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
391 final ModelProcessingPhase finishedPhase) {
392 return resolvePrereq((C) context) || tryApply();
396 private final class NamespaceMutation extends AbstractPrerequisite<Mutable<?, ?, ?>> {
397 NamespaceMutation(final StatementContextBase<?, ?, ?> ctx, final ParserNamespace<?, ?> namespace) {
402 private final class AddedToNamespace<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
403 implements OnNamespaceItemAdded, OnPhaseFinished {
404 private final ModelProcessingPhase phase;
406 AddedToNamespace(final ModelProcessingPhase phase) {
407 this.phase = requireNonNull(phase);
411 public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context,
412 final ParserNamespace<?, ?> namespace, final Object key, final Object value) {
413 ((StatementContextBase<?, ?, ?>) value).addPhaseCompletedListener(phase, this);
416 @SuppressWarnings("unchecked")
418 public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
419 final ModelProcessingPhase finishedPhase) {
420 return resolvePrereq((C) context) || tryApply();
424 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
425 return super.addToStringAttributes(toStringHelper).add("phase", phase);
429 private final class PhaseRequirementInNamespacePath<C extends StmtContext<?, ?, ?>, K>
430 extends AbstractPathPrerequisite<C, K> {
431 PhaseRequirementInNamespacePath(final ModelProcessingPhase phase, final Iterable<K> keys) {
436 void nextStep(final ModelProcessingPhase phase, final StatementContextBase<?, ?, ?> current,
437 final StatementContextBase<?, ?, ?> next) {
442 private final class PhaseModificationInNamespace<C extends Mutable<?, ?, ?>> extends AbstractPrerequisite<C>
443 implements OnNamespaceItemAdded, ContextMutation {
444 private final ModelProcessingPhase modPhase;
446 PhaseModificationInNamespace(final ModelProcessingPhase phase) {
447 checkArgument(phase != null, "Model processing phase must not be null");
448 this.modPhase = phase;
451 @SuppressWarnings("unchecked")
453 public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context,
454 final ParserNamespace<?, ?> namespace, final Object key, final Object value) {
455 StatementContextBase<?, ?, ?> targetCtx = contextImpl(value);
456 targetCtx.addMutation(modPhase, this);
457 resolvePrereq((C) targetCtx);
461 public boolean isFinished() {
467 * This similar to {@link PhaseModificationInNamespace}, but allows recursive descent until it finds the real
468 * target. The mechanics is driven as a sequence of prerequisites along a path: first we hook onto namespace to
469 * give us the first step. When it does, we hook onto the first item to provide us the second step and so on.
471 private final class PhaseModificationInNamespacePath<C extends Mutable<?, ?, ?>, K>
472 extends AbstractPathPrerequisite<C, K> implements ContextMutation {
473 PhaseModificationInNamespacePath(final ModelProcessingPhase phase, final Iterable<K> keys) {
478 public boolean isFinished() {
483 void nextStep(final ModelProcessingPhase phase, final StatementContextBase<?, ?, ?> current,
484 final StatementContextBase<?, ?, ?> next) {
485 // Hook onto target: we either have a modification of the target itself or one of its children.
486 next.addMutation(phase, this);
487 // We have completed the context -> target step, hence we are no longer directly blocking context from
488 // making forward progress.
489 current.removeMutation(phase, this);