Defer mutatesEffectiveCtxPath() hookOnto()
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / ModifierImpl.java
1 /*
2  * Copyright (c) 2015, 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
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;
16
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;
23 import java.util.Set;
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.model.api.meta.IdentifierNamespace;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
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;
40
41 final class ModifierImpl implements ModelActionBuilder {
42     private static final Logger LOG = LoggerFactory.getLogger(ModifierImpl.class);
43
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() { };
47
48     private List<Runnable> bootstraps;
49     private InferenceAction action;
50     private boolean actionApplied;
51
52     private <D> AbstractPrerequisite<D> addReq(final AbstractPrerequisite<D> prereq) {
53         LOG.trace("Modifier {} adding prerequisite {}", this, prereq);
54         unsatisfied.add(prereq);
55         return prereq;
56     }
57
58     private <T> @NonNull AbstractPrerequisite<T> addMutation(final @NonNull AbstractPrerequisite<T> mutation) {
59         LOG.trace("Modifier {} adding mutation {}", this, mutation);
60         mutations.add(mutation);
61         return mutation;
62     }
63
64     private void checkNotRegistered() {
65         checkState(action == null, "Action was already registered.");
66     }
67
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);
75                 it.remove();
76             }
77         }
78         return unsatisfied.isEmpty();
79     }
80
81     boolean isApplied() {
82         return actionApplied;
83     }
84
85     void failModifier() {
86         removeSatisfied();
87         action.prerequisiteFailed(unsatisfied);
88         action = null;
89     }
90
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)  {
94         checkNotRegistered();
95
96         AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
97         addReq(addedToNs);
98         contextImpl(context).onNamespaceItemAddedAction(namespace, key, addedToNs);
99         return addedToNs;
100     }
101
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();
106
107         AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
108         addReq(addedToNs);
109         contextImpl(context).onNamespaceItemAddedAction(namespace, phase, criterion, addedToNs);
110         return addedToNs;
111     }
112
113     private <C extends StmtContext<?, ?, ?>> @NonNull AbstractPrerequisite<C> requiresCtxImpl(final C context,
114             final ModelProcessingPhase phase) {
115         checkNotRegistered();
116
117         PhaseFinished<C> phaseFin = new PhaseFinished<>();
118         addReq(phaseFin);
119         contextImpl(context).addPhaseCompletedListener(phase, phaseFin);
120         return phaseFin;
121     }
122
123     @SuppressWarnings({ "rawtypes", "unchecked" })
124     private <K, C extends Mutable<?, ?, ?>, N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>>
125             AbstractPrerequisite<C> mutatesCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace,
126                     final K key, final ModelProcessingPhase phase) {
127         checkNotRegistered();
128
129         final PhaseModificationInNamespace<C> mod = new PhaseModificationInNamespace<>(EFFECTIVE_MODEL);
130         addReq(mod);
131         addMutation(mod);
132         contextImpl(context).onNamespaceItemAddedAction((Class) namespace, key, mod);
133         return mod;
134     }
135
136     private static StatementContextBase<?, ?, ?> contextImpl(final Object value) {
137         checkArgument(value instanceof StatementContextBase, "Supplied context %s is not provided by this reactor.",
138             value);
139         return StatementContextBase.class.cast(value);
140     }
141
142     boolean tryApply() {
143         checkState(action != null, "Action was not defined yet.");
144
145         if (removeSatisfied()) {
146             if (!actionApplied) {
147                 action.apply(ctx);
148                 actionApplied = true;
149             }
150             return true;
151         }
152         return false;
153     }
154
155     @Override
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));
159     }
160
161     @Override
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);
166     }
167
168
169     @Override
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);
174     }
175
176     @Override
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);
181     }
182
183     @Override
184     public <D extends DeclaredStatement<?>> Prerequisite<D> requiresDeclared(
185             final StmtContext<?, ? extends D, ?> context) {
186         return requiresCtxImpl(context, FULL_DECLARATION).transform(StmtContext::buildDeclared);
187     }
188
189     @Override
190     @Deprecated
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,
194             FULL_DECLARATION);
195         return rawContext.transform(StmtContext::buildDeclared);
196     }
197
198     @Override
199     @Deprecated
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);
204     }
205
206     @Override
207     @Deprecated
208     public <E extends EffectiveStatement<?, ?>> Prerequisite<E> requiresEffective(
209             final StmtContext<?, ?, ? extends E> stmt) {
210         return requiresCtxImpl(stmt, EFFECTIVE_MODEL).transform(StmtContext::buildEffective);
211     }
212
213     @Override
214     @Deprecated
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,
218             EFFECTIVE_MODEL);
219         return rawContext.transform(StmtContext::buildEffective);
220     }
221
222     @Override
223     @Deprecated
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);
228     }
229
230     @Override
231     @Deprecated
232     public <N extends IdentifierNamespace<?, ?>> Prerequisite<Mutable<?, ?, ?>> mutatesNs(
233             final Mutable<?, ?, ?> context, final Class<N> namespace) {
234         return addMutation(new NamespaceMutation<>(contextImpl(context), namespace));
235     }
236
237     @Override
238     public <K, E extends EffectiveStatement<?, ?>, N extends IdentifierNamespace<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);
242     }
243
244     @Override
245     public <K, E extends EffectiveStatement<?, ?>, N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>>
246             AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtxPath(final StmtContext<?, ?, ?> context,
247                     final Class<N> namespace, final Iterable<K> keys) {
248         checkNotRegistered();
249
250         final PhaseModificationInNamespacePath<Mutable<?, ?, E>, K, N> ret = new PhaseModificationInNamespacePath<>(
251                 EFFECTIVE_MODEL, keys);
252         addReq(ret);
253         addMutation(ret);
254
255         if (bootstraps == null) {
256             bootstraps = new ArrayList<>(1);
257         }
258         bootstraps.add(() -> ret.hookOnto(context, namespace));
259         return ret;
260     }
261
262     @Override
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);
269             bootstraps = null;
270         }
271     }
272
273     private abstract class AbstractPrerequisite<T> implements Prerequisite<T> {
274         private boolean done = false;
275         private T value;
276
277         @Override
278         @SuppressWarnings("checkstyle:hiddenField")
279         public final T resolve(final InferenceContext ctx) {
280             checkState(done);
281             checkArgument(ctx == ModifierImpl.this.ctx);
282             return verifyNotNull(value, "Attempted to access unavailable prerequisite %s", this);
283         }
284
285         final boolean isDone() {
286             return done;
287         }
288
289         @SuppressWarnings("checkstyle:hiddenField")
290         final boolean resolvePrereq(final T value) {
291             this.value = value;
292             this.done = true;
293             return isApplied();
294         }
295
296         final <O> @NonNull Prerequisite<O> transform(final Function<? super T, O> transformation) {
297             return context -> transformation.apply(resolve(context));
298         }
299
300         @Override
301         public final String toString() {
302             return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
303         }
304
305         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
306             return toStringHelper.add("value", value);
307         }
308     }
309
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);
315         }
316
317         @Override
318         public boolean isFinished() {
319             return isApplied();
320         }
321     }
322
323     private final class PhaseFinished<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
324             implements OnPhaseFinished {
325         @SuppressWarnings("unchecked")
326         @Override
327         public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
328                 final ModelProcessingPhase finishedPhase) {
329             return resolvePrereq((C) context) || tryApply();
330         }
331     }
332
333     private final class NamespaceMutation<N extends IdentifierNamespace<?, ?>>
334             extends AbstractPrerequisite<Mutable<?, ?, ?>>  {
335         NamespaceMutation(final StatementContextBase<?, ?, ?> ctx, final Class<N> namespace) {
336             resolvePrereq(ctx);
337         }
338     }
339
340     private final class AddedToNamespace<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
341             implements OnNamespaceItemAdded, OnPhaseFinished {
342         private final ModelProcessingPhase phase;
343
344         AddedToNamespace(final ModelProcessingPhase phase) {
345             this.phase = requireNonNull(phase);
346         }
347
348         @Override
349         public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
350                 final Object key, final Object value) {
351             ((StatementContextBase<?, ?, ?>) value).addPhaseCompletedListener(phase, this);
352         }
353
354         @SuppressWarnings("unchecked")
355         @Override
356         public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
357                 final ModelProcessingPhase finishedPhase) {
358             return resolvePrereq((C) context) || tryApply();
359         }
360
361         @Override
362         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
363             return super.addToStringAttributes(toStringHelper).add("phase", phase);
364         }
365     }
366
367     private final class PhaseModificationInNamespace<C extends Mutable<?, ?, ?>> extends AbstractPrerequisite<C>
368             implements OnNamespaceItemAdded, ContextMutation {
369         private final ModelProcessingPhase modPhase;
370
371         PhaseModificationInNamespace(final ModelProcessingPhase phase) {
372             checkArgument(phase != null, "Model processing phase must not be null");
373             this.modPhase = phase;
374         }
375
376         @SuppressWarnings("unchecked")
377         @Override
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);
383         }
384
385         @Override
386         public boolean isFinished() {
387             return isApplied();
388         }
389     }
390
391     /**
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.
395      */
396     private final class PhaseModificationInNamespacePath<C extends Mutable<?, ?, ?>, K,
397             N extends IdentifierNamespace<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;
402
403         PhaseModificationInNamespacePath(final ModelProcessingPhase phase, final Iterable<K> keys) {
404             this.modPhase = requireNonNull(phase);
405             this.keys = requireNonNull(keys);
406             it = keys.iterator();
407         }
408
409         @Override
410         public boolean isFinished() {
411             return isApplied();
412         }
413
414         @Override
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);
418
419             final StatementContextBase<?, ?, ?> target = contextImpl(value);
420             if (!target.isSupportedByFeatures()) {
421                 LOG.debug("Key {} in {} is not supported", key, keys);
422                 resolvePrereq(null);
423                 action.prerequisiteUnavailable(this);
424                 return;
425             }
426
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);
432
433             if (!it.hasNext()) {
434                 // Last step: we are done
435                 if (resolvePrereq((C) value)) {
436                     tryApply();
437                 }
438                 return;
439             }
440
441             // Make sure target's storage notifies us when the next step becomes available.
442             hookOnto(target, namespace, it.next());
443         }
444
445         @Override
446         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
447             return super.addToStringAttributes(toStringHelper).add("phase", modPhase).add("keys", keys);
448         }
449
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());
453         }
454
455         @SuppressWarnings("unchecked")
456         private void hookOnto(final StatementContextBase<?, ?, ?> context, final Class<?> namespace, final K key) {
457             context.onNamespaceItemAddedAction((Class) namespace, requireNonNull(key), this);
458         }
459     }
460 }