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.StatementNamespace;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
35 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.ContextMutation;
36 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnNamespaceItemAdded;
37 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnPhaseFinished;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 final class ModifierImpl implements ModelActionBuilder {
42 private static final Logger LOG = LoggerFactory.getLogger(ModifierImpl.class);
44 private final Set<AbstractPrerequisite<?>> unsatisfied = new HashSet<>(1);
45 private final Set<AbstractPrerequisite<?>> mutations = new HashSet<>(1);
46 private final InferenceContext ctx = new InferenceContext() { };
48 private List<Runnable> bootstraps;
49 private InferenceAction action;
50 private boolean actionApplied;
52 private <D> AbstractPrerequisite<D> addReq(final AbstractPrerequisite<D> prereq) {
53 LOG.trace("Modifier {} adding prerequisite {}", this, prereq);
54 unsatisfied.add(prereq);
58 private <T> @NonNull AbstractPrerequisite<T> addMutation(final @NonNull AbstractPrerequisite<T> mutation) {
59 LOG.trace("Modifier {} adding mutation {}", this, mutation);
60 mutations.add(mutation);
64 private void checkNotRegistered() {
65 checkState(action == null, "Action was already registered.");
68 private boolean removeSatisfied() {
69 final Iterator<AbstractPrerequisite<?>> it = unsatisfied.iterator();
70 while (it.hasNext()) {
71 final AbstractPrerequisite<?> prereq = it.next();
72 if (prereq.isDone()) {
73 // We are removing current prerequisite from list.
74 LOG.trace("Modifier {} prerequisite {} satisfied", this, prereq);
78 return unsatisfied.isEmpty();
87 action.prerequisiteFailed(unsatisfied);
91 private <K, C extends StmtContext<?, ?, ?>, N extends StatementNamespace<K, ?, ?>> @NonNull AbstractPrerequisite<C>
92 requiresCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key,
93 final ModelProcessingPhase phase) {
96 AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
98 contextImpl(context).onNamespaceItemAddedAction(namespace, key, addedToNs);
102 private <K, C extends StmtContext<?, ?, ?>, N extends StatementNamespace<K, ?, ?>> @NonNull AbstractPrerequisite<C>
103 requiresCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace,
104 final NamespaceKeyCriterion<K> criterion, final ModelProcessingPhase phase) {
105 checkNotRegistered();
107 AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
109 contextImpl(context).onNamespaceItemAddedAction(namespace, phase, criterion, addedToNs);
113 private <C extends StmtContext<?, ?, ?>> @NonNull AbstractPrerequisite<C> requiresCtxImpl(final C context,
114 final ModelProcessingPhase phase) {
115 checkNotRegistered();
117 PhaseFinished<C> phaseFin = new PhaseFinished<>();
119 contextImpl(context).addPhaseCompletedListener(phase, phaseFin);
123 @SuppressWarnings({ "rawtypes", "unchecked" })
124 private <K, C extends Mutable<?, ?, ?>, N extends ParserNamespace<K, ? extends StmtContext<?, ?, ?>>>
125 AbstractPrerequisite<C> mutatesCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace,
126 final K key, final ModelProcessingPhase phase) {
127 checkNotRegistered();
129 final PhaseModificationInNamespace<C> mod = new PhaseModificationInNamespace<>(EFFECTIVE_MODEL);
132 contextImpl(context).onNamespaceItemAddedAction((Class) namespace, key, mod);
136 private static StatementContextBase<?, ?, ?> contextImpl(final Object value) {
137 checkArgument(value instanceof StatementContextBase, "Supplied context %s is not provided by this reactor.",
139 return StatementContextBase.class.cast(value);
143 checkState(action != null, "Action was not defined yet.");
145 if (removeSatisfied()) {
146 if (!actionApplied) {
148 actionApplied = true;
156 public <C extends Mutable<?, ?, ?>, T extends C> Prerequisite<C> mutatesCtx(final T context,
157 final ModelProcessingPhase phase) {
158 return addMutation(new PhaseMutation<>(contextImpl(context), phase));
162 public <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
163 AbstractPrerequisite<StmtContext<A, D, E>> requiresCtx(final StmtContext<A, D, E> context,
164 final ModelProcessingPhase phase) {
165 return requiresCtxImpl(context, phase);
170 public <K, N extends StatementNamespace<K, ?, ?>> Prerequisite<StmtContext<?, ?, ?>> requiresCtx(
171 final StmtContext<?, ?, ?> context, final Class<@NonNull N> namespace, final K key,
172 final ModelProcessingPhase phase) {
173 return requiresCtxImpl(context, namespace, key, phase);
177 public <K, N extends StatementNamespace<K, ?, ?>> Prerequisite<StmtContext<?, ?, ?>> requiresCtx(
178 final StmtContext<?, ?, ?> context, final Class<@NonNull N> namespace,
179 final NamespaceKeyCriterion<K> criterion, final ModelProcessingPhase phase) {
180 return requiresCtxImpl(context, namespace, criterion, phase);
184 public <D extends DeclaredStatement<?>> Prerequisite<D> requiresDeclared(
185 final StmtContext<?, ? extends D, ?> context) {
186 return requiresCtxImpl(context, FULL_DECLARATION).transform(StmtContext::declared);
191 public <K, D extends DeclaredStatement<?>, N extends StatementNamespace<K, ? extends D, ?>> Prerequisite<D>
192 requiresDeclared(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key) {
193 final AbstractPrerequisite<StmtContext<?, D, ?>> rawContext = requiresCtxImpl(context, namespace, key,
195 return rawContext.transform(StmtContext::declared);
200 public <K, D extends DeclaredStatement<?>, N extends StatementNamespace<K, ? extends D, ?>>
201 AbstractPrerequisite<StmtContext<?, D, ?>> requiresDeclaredCtx(final StmtContext<?, ?, ?> context,
202 final Class<N> namespace, final K key) {
203 return requiresCtxImpl(context, namespace, key, FULL_DECLARATION);
208 public <E extends EffectiveStatement<?, ?>> Prerequisite<E> requiresEffective(
209 final StmtContext<?, ?, ? extends E> stmt) {
210 return requiresCtxImpl(stmt, EFFECTIVE_MODEL).transform(StmtContext::buildEffective);
215 public <K, E extends EffectiveStatement<?, ?>, N extends StatementNamespace<K, ?, ? extends E>> Prerequisite<E>
216 requiresEffective(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key) {
217 final AbstractPrerequisite<StmtContext<?, ?, E>> rawContext = requiresCtxImpl(context, namespace, key,
219 return rawContext.transform(StmtContext::buildEffective);
224 public <K, E extends EffectiveStatement<?, ?>, N extends StatementNamespace<K, ?, ? extends E>>
225 AbstractPrerequisite<StmtContext<?, ?, E>> requiresEffectiveCtx(final StmtContext<?, ?, ?> context,
226 final Class<N> namespace, final K key) {
227 return requiresCtxImpl(contextImpl(context), namespace, key, EFFECTIVE_MODEL);
232 public <N extends ParserNamespace<?, ?>> Prerequisite<Mutable<?, ?, ?>> mutatesNs(final Mutable<?, ?, ?> context,
233 final Class<N> namespace) {
234 return addMutation(new NamespaceMutation<>(contextImpl(context), namespace));
238 public <K, E extends EffectiveStatement<?, ?>, N extends ParserNamespace<K, ? extends StmtContext<?, ?, ?>>>
239 AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtx(final StmtContext<?, ?, ?> context,
240 final Class<N> namespace, final K key) {
241 return mutatesCtxImpl(context, namespace, key, EFFECTIVE_MODEL);
245 public <K, E extends EffectiveStatement<?, ?>, N extends ParserNamespace<K, ? extends StmtContext<?, ?, ?>>>
246 AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtxPath(final StmtContext<?, ?, ?> context,
247 final Class<N> namespace, final Iterable<K> keys) {
248 checkNotRegistered();
250 final PhaseModificationInNamespacePath<Mutable<?, ?, E>, K, N> ret = new PhaseModificationInNamespacePath<>(
251 EFFECTIVE_MODEL, keys);
255 if (bootstraps == null) {
256 bootstraps = new ArrayList<>(1);
258 bootstraps.add(() -> ret.hookOnto(context, namespace));
263 @SuppressWarnings("checkstyle:hiddenField")
264 public void apply(final InferenceAction action) {
265 checkState(this.action == null, "Action already defined to %s", this.action);
266 this.action = requireNonNull(action);
267 if (bootstraps != null) {
268 bootstraps.forEach(Runnable::run);
273 private abstract class AbstractPrerequisite<T> implements Prerequisite<T> {
274 private boolean done = false;
278 @SuppressWarnings("checkstyle:hiddenField")
279 public final T resolve(final InferenceContext ctx) {
281 checkArgument(ctx == ModifierImpl.this.ctx);
282 return verifyNotNull(value, "Attempted to access unavailable prerequisite %s", this);
285 final boolean isDone() {
289 @SuppressWarnings("checkstyle:hiddenField")
290 final boolean resolvePrereq(final T value) {
296 final <O> @NonNull Prerequisite<O> transform(final Function<? super T, O> transformation) {
297 return context -> transformation.apply(resolve(context));
301 public final String toString() {
302 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
305 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
306 return toStringHelper.add("value", value);
310 private final class PhaseMutation<C> extends AbstractPrerequisite<C> implements ContextMutation {
311 @SuppressWarnings("unchecked")
312 PhaseMutation(final StatementContextBase<?, ?, ?> context, final ModelProcessingPhase phase) {
313 context.addMutation(phase, this);
314 resolvePrereq((C) context);
318 public boolean isFinished() {
323 private final class PhaseFinished<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
324 implements OnPhaseFinished {
325 @SuppressWarnings("unchecked")
327 public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
328 final ModelProcessingPhase finishedPhase) {
329 return resolvePrereq((C) context) || tryApply();
333 private final class NamespaceMutation<N extends ParserNamespace<?, ?>>
334 extends AbstractPrerequisite<Mutable<?, ?, ?>> {
335 NamespaceMutation(final StatementContextBase<?, ?, ?> ctx, final Class<N> namespace) {
340 private final class AddedToNamespace<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
341 implements OnNamespaceItemAdded, OnPhaseFinished {
342 private final ModelProcessingPhase phase;
344 AddedToNamespace(final ModelProcessingPhase phase) {
345 this.phase = requireNonNull(phase);
349 public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
350 final Object key, final Object value) {
351 ((StatementContextBase<?, ?, ?>) value).addPhaseCompletedListener(phase, this);
354 @SuppressWarnings("unchecked")
356 public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
357 final ModelProcessingPhase finishedPhase) {
358 return resolvePrereq((C) context) || tryApply();
362 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
363 return super.addToStringAttributes(toStringHelper).add("phase", phase);
367 private final class PhaseModificationInNamespace<C extends Mutable<?, ?, ?>> extends AbstractPrerequisite<C>
368 implements OnNamespaceItemAdded, ContextMutation {
369 private final ModelProcessingPhase modPhase;
371 PhaseModificationInNamespace(final ModelProcessingPhase phase) {
372 checkArgument(phase != null, "Model processing phase must not be null");
373 this.modPhase = phase;
376 @SuppressWarnings("unchecked")
378 public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
379 final Object key, final Object value) {
380 StatementContextBase<?, ?, ?> targetCtx = contextImpl(value);
381 targetCtx.addMutation(modPhase, this);
382 resolvePrereq((C) targetCtx);
386 public boolean isFinished() {
392 * This similar to {@link PhaseModificationInNamespace}, but allows recursive descent until it finds the real
393 * target. The mechanics is driven as a sequence of prerequisites along a path: first we hook onto namespace to
394 * give us the first step. When it does, we hook onto the first item to provide us the second step and so on.
396 private final class PhaseModificationInNamespacePath<C extends Mutable<?, ?, ?>, K,
397 N extends ParserNamespace<K, ? extends StmtContext<?, ?, ?>>> extends AbstractPrerequisite<C>
398 implements OnNamespaceItemAdded, ContextMutation {
399 private final ModelProcessingPhase modPhase;
400 private final Iterable<K> keys;
401 private final Iterator<K> it;
403 PhaseModificationInNamespacePath(final ModelProcessingPhase phase, final Iterable<K> keys) {
404 this.modPhase = requireNonNull(phase);
405 this.keys = requireNonNull(keys);
406 it = keys.iterator();
410 public boolean isFinished() {
415 public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
416 final Object key, final Object value) {
417 LOG.debug("Action for {} got key {}", keys, key);
419 final StatementContextBase<?, ?, ?> target = contextImpl(value);
420 if (!target.isSupportedByFeatures()) {
421 LOG.debug("Key {} in {} is not supported", key, keys);
423 action.prerequisiteUnavailable(this);
427 // Hook onto target: we either have a modification of the target itself or one of its children.
428 target.addMutation(modPhase, this);
429 // We have completed the context -> target step, hence we are no longer directly blocking context from
430 // making forward progress.
431 context.removeMutation(modPhase, this);
434 // Last step: we are done
435 if (resolvePrereq((C) value)) {
441 // Make sure target's storage notifies us when the next step becomes available.
442 hookOnto(target, namespace, it.next());
446 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
447 return super.addToStringAttributes(toStringHelper).add("phase", modPhase).add("keys", keys);
450 void hookOnto(final StmtContext<?, ?, ?> context, final Class<?> namespace) {
451 checkArgument(it.hasNext(), "Namespace %s keys may not be empty", namespace);
452 hookOnto(contextImpl(context), namespace, it.next());
455 @SuppressWarnings("unchecked")
456 private void hookOnto(final StatementContextBase<?, ?, ?> context, final Class<?> namespace, final K key) {
457 context.onNamespaceItemAddedAction((Class) namespace, requireNonNull(key), this);