Add CommonStmtCtx
[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.HashSet;
20 import java.util.Iterator;
21 import java.util.Set;
22 import java.util.function.Function;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
33 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.ContextMutation;
34 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnNamespaceItemAdded;
35 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase.OnPhaseFinished;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 final class ModifierImpl implements ModelActionBuilder {
40     private static final Logger LOG = LoggerFactory.getLogger(ModifierImpl.class);
41
42     private final InferenceContext ctx = new InferenceContext() { };
43
44     private final Set<AbstractPrerequisite<?>> unsatisfied = new HashSet<>(1);
45     private final Set<AbstractPrerequisite<?>> mutations = new HashSet<>(1);
46
47     private InferenceAction action;
48     private boolean actionApplied = false;
49
50     private <D> AbstractPrerequisite<D> addReq(final AbstractPrerequisite<D> prereq) {
51         LOG.trace("Modifier {} adding prerequisite {}", this, prereq);
52         unsatisfied.add(prereq);
53         return prereq;
54     }
55
56     private <T> @NonNull AbstractPrerequisite<T> addMutation(final @NonNull AbstractPrerequisite<T> mutation) {
57         LOG.trace("Modifier {} adding mutation {}", this, mutation);
58         mutations.add(mutation);
59         return mutation;
60     }
61
62     private void checkNotRegistered() {
63         checkState(action == null, "Action was already registered.");
64     }
65
66     private boolean removeSatisfied() {
67         final Iterator<AbstractPrerequisite<?>> it = unsatisfied.iterator();
68         while (it.hasNext()) {
69             final AbstractPrerequisite<?> prereq = it.next();
70             if (prereq.isDone()) {
71                 // We are removing current prerequisite from list.
72                 LOG.trace("Modifier {} prerequisite {} satisfied", this, prereq);
73                 it.remove();
74             }
75         }
76         return unsatisfied.isEmpty();
77     }
78
79     boolean isApplied() {
80         return actionApplied;
81     }
82
83     void failModifier() {
84         removeSatisfied();
85         action.prerequisiteFailed(unsatisfied);
86         action = null;
87     }
88
89     private void applyAction() {
90         checkState(!actionApplied);
91         action.apply(ctx);
92         actionApplied = true;
93     }
94
95     private <K, C extends StmtContext<?, ?, ?>, N extends StatementNamespace<K, ?, ?>> @NonNull AbstractPrerequisite<C>
96             requiresCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key,
97                     final ModelProcessingPhase phase)  {
98         checkNotRegistered();
99
100         AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
101         addReq(addedToNs);
102         contextImpl(context).onNamespaceItemAddedAction(namespace, key, addedToNs);
103         return addedToNs;
104     }
105
106     private <K, C extends StmtContext<?, ?, ?>, N extends StatementNamespace<K, ?, ?>> @NonNull AbstractPrerequisite<C>
107             requiresCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace,
108                     final NamespaceKeyCriterion<K> criterion, final ModelProcessingPhase phase)  {
109         checkNotRegistered();
110
111         AddedToNamespace<C> addedToNs = new AddedToNamespace<>(phase);
112         addReq(addedToNs);
113         contextImpl(context).onNamespaceItemAddedAction(namespace, phase, criterion, addedToNs);
114         return addedToNs;
115     }
116
117     private <C extends StmtContext<?, ?, ?>> @NonNull AbstractPrerequisite<C> requiresCtxImpl(final C context,
118             final ModelProcessingPhase phase) {
119         checkNotRegistered();
120
121         PhaseFinished<C> phaseFin = new PhaseFinished<>();
122         addReq(phaseFin);
123         contextImpl(context).addPhaseCompletedListener(phase, phaseFin);
124         return phaseFin;
125     }
126
127     @SuppressWarnings({ "rawtypes", "unchecked" })
128     private <K, C extends Mutable<?, ?, ?>, N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>>
129             AbstractPrerequisite<C> mutatesCtxImpl(final StmtContext<?, ?, ?> context, final Class<N> namespace,
130                     final K key, final ModelProcessingPhase phase) {
131         checkNotRegistered();
132
133         final PhaseModificationInNamespace<C> mod = new PhaseModificationInNamespace<>(EFFECTIVE_MODEL);
134         addReq(mod);
135         addMutation(mod);
136         contextImpl(context).onNamespaceItemAddedAction((Class) namespace, key, mod);
137         return mod;
138     }
139
140     private static StatementContextBase<?, ?, ?> contextImpl(final Object value) {
141         checkArgument(value instanceof StatementContextBase, "Supplied context %s is not provided by this reactor.",
142             value);
143         return StatementContextBase.class.cast(value);
144     }
145
146     boolean tryApply() {
147         checkState(action != null, "Action was not defined yet.");
148
149         if (removeSatisfied()) {
150             applyAction();
151             return true;
152         }
153         return false;
154     }
155
156     @Override
157     public <C extends Mutable<?, ?, ?>, T extends C> Prerequisite<C> mutatesCtx(final T context,
158             final ModelProcessingPhase phase) {
159         return addMutation(new PhaseMutation<>(contextImpl(context), phase));
160     }
161
162     @Override
163     public <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
164             AbstractPrerequisite<StmtContext<A, D, E>> requiresCtx(final StmtContext<A, D, E> context,
165                     final ModelProcessingPhase phase) {
166         return requiresCtxImpl(context, phase);
167     }
168
169
170     @Override
171     public <K, N extends StatementNamespace<K, ?, ?>> Prerequisite<StmtContext<?, ?, ?>> requiresCtx(
172             final StmtContext<?, ?, ?> context, final Class<@NonNull N> namespace, final K key,
173             final ModelProcessingPhase phase) {
174         return requiresCtxImpl(context, namespace, key, phase);
175     }
176
177     @Override
178     public <K, N extends StatementNamespace<K, ?, ?>> Prerequisite<StmtContext<?, ?, ?>> requiresCtx(
179             final StmtContext<?, ?, ?> context, final Class<@NonNull N> namespace,
180             final NamespaceKeyCriterion<K> criterion, final ModelProcessingPhase phase) {
181         return requiresCtxImpl(context, namespace, criterion, phase);
182     }
183
184     @Override
185     public <D extends DeclaredStatement<?>> Prerequisite<D> requiresDeclared(
186             final StmtContext<?, ? extends D, ?> context) {
187         return requiresCtxImpl(context, FULL_DECLARATION).transform(StmtContext::buildDeclared);
188     }
189
190     @Override
191     @Deprecated
192     public <K, D extends DeclaredStatement<?>, N extends StatementNamespace<K, ? extends D, ?>> Prerequisite<D>
193             requiresDeclared(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key) {
194         final AbstractPrerequisite<StmtContext<?, D, ?>> rawContext = requiresCtxImpl(context, namespace, key,
195             FULL_DECLARATION);
196         return rawContext.transform(StmtContext::buildDeclared);
197     }
198
199     @Override
200     @Deprecated
201     public <K, D extends DeclaredStatement<?>, N extends StatementNamespace<K, ? extends D, ?>>
202             AbstractPrerequisite<StmtContext<?, D, ?>> requiresDeclaredCtx(final StmtContext<?, ?, ?> context,
203                     final Class<N> namespace, final K key) {
204         return requiresCtxImpl(context, namespace, key, FULL_DECLARATION);
205     }
206
207     @Override
208     @Deprecated
209     public <E extends EffectiveStatement<?, ?>> Prerequisite<E> requiresEffective(
210             final StmtContext<?, ?, ? extends E> stmt) {
211         return requiresCtxImpl(stmt, EFFECTIVE_MODEL).transform(StmtContext::buildEffective);
212     }
213
214     @Override
215     @Deprecated
216     public <K, E extends EffectiveStatement<?, ?>, N extends StatementNamespace<K, ?, ? extends E>> Prerequisite<E>
217             requiresEffective(final StmtContext<?, ?, ?> context, final Class<N> namespace, final K key) {
218         final AbstractPrerequisite<StmtContext<?, ?, E>> rawContext = requiresCtxImpl(context, namespace, key,
219             EFFECTIVE_MODEL);
220         return rawContext.transform(StmtContext::buildEffective);
221     }
222
223     @Override
224     @Deprecated
225     public <K, E extends EffectiveStatement<?, ?>, N extends StatementNamespace<K, ?, ? extends E>>
226             AbstractPrerequisite<StmtContext<?, ?, E>> requiresEffectiveCtx(final StmtContext<?, ?, ?> context,
227                     final Class<N> namespace, final K key) {
228         return requiresCtxImpl(contextImpl(context), namespace, key, EFFECTIVE_MODEL);
229     }
230
231     @Override
232     @Deprecated
233     public <N extends IdentifierNamespace<?, ?>> Prerequisite<Mutable<?, ?, ?>> mutatesNs(
234             final Mutable<?, ?, ?> context, final Class<N> namespace) {
235         return addMutation(new NamespaceMutation<>(contextImpl(context), namespace));
236     }
237
238     @Override
239     public <K, E extends EffectiveStatement<?, ?>, N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>>
240             AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtx(final StmtContext<?, ?, ?> context,
241                     final Class<N> namespace, final K key) {
242         return mutatesCtxImpl(context, namespace, key, EFFECTIVE_MODEL);
243     }
244
245     @Override
246     public <K, E extends EffectiveStatement<?, ?>, N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>>
247             AbstractPrerequisite<Mutable<?, ?, E>> mutatesEffectiveCtxPath(final StmtContext<?, ?, ?> context,
248                     final Class<N> namespace, final Iterable<K> keys) {
249         checkNotRegistered();
250
251         final PhaseModificationInNamespacePath<Mutable<?, ?, E>, K, N> ret = new PhaseModificationInNamespacePath<>(
252                 EFFECTIVE_MODEL, keys);
253         addReq(ret);
254         addMutation(ret);
255
256         ret.hookOnto(context, namespace);
257         return ret;
258     }
259
260     @Override
261     @SuppressWarnings("checkstyle:hiddenField")
262     public void apply(final InferenceAction action) {
263         checkState(this.action == null, "Action already defined to %s", this.action);
264         this.action = requireNonNull(action);
265     }
266
267     private abstract class AbstractPrerequisite<T> implements Prerequisite<T> {
268         private boolean done = false;
269         private T value;
270
271         @Override
272         @SuppressWarnings("checkstyle:hiddenField")
273         public final T resolve(final InferenceContext ctx) {
274             checkState(done);
275             checkArgument(ctx == ModifierImpl.this.ctx);
276             return verifyNotNull(value, "Attempted to access unavailable prerequisite %s", this);
277         }
278
279         final boolean isDone() {
280             return done;
281         }
282
283         @SuppressWarnings("checkstyle:hiddenField")
284         final boolean resolvePrereq(final T value) {
285             this.value = value;
286             this.done = true;
287             return isApplied();
288         }
289
290         final <O> @NonNull Prerequisite<O> transform(final Function<? super T, O> transformation) {
291             return context -> transformation.apply(resolve(context));
292         }
293
294         @Override
295         public final String toString() {
296             return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
297         }
298
299         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
300             return toStringHelper.add("value", value);
301         }
302     }
303
304     private final class PhaseMutation<C> extends AbstractPrerequisite<C> implements ContextMutation {
305         @SuppressWarnings("unchecked")
306         PhaseMutation(final StatementContextBase<?, ?, ?> context, final ModelProcessingPhase phase) {
307             context.addMutation(phase, this);
308             resolvePrereq((C) context);
309         }
310
311         @Override
312         public boolean isFinished() {
313             return isApplied();
314         }
315     }
316
317     private final class PhaseFinished<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
318             implements OnPhaseFinished {
319         @SuppressWarnings("unchecked")
320         @Override
321         public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
322                 final ModelProcessingPhase finishedPhase) {
323             return resolvePrereq((C) context);
324         }
325     }
326
327     private final class NamespaceMutation<N extends IdentifierNamespace<?, ?>>
328             extends AbstractPrerequisite<Mutable<?, ?, ?>>  {
329         NamespaceMutation(final StatementContextBase<?, ?, ?> ctx, final Class<N> namespace) {
330             resolvePrereq(ctx);
331         }
332     }
333
334     private final class AddedToNamespace<C extends StmtContext<?, ?, ?>> extends AbstractPrerequisite<C>
335             implements OnNamespaceItemAdded, OnPhaseFinished {
336         private final ModelProcessingPhase phase;
337
338         AddedToNamespace(final ModelProcessingPhase phase) {
339             this.phase = requireNonNull(phase);
340         }
341
342         @Override
343         public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
344                 final Object key, final Object value) {
345             ((StatementContextBase<?, ?, ?>) value).addPhaseCompletedListener(phase, this);
346         }
347
348         @SuppressWarnings("unchecked")
349         @Override
350         public boolean phaseFinished(final StatementContextBase<?, ?, ?> context,
351                 final ModelProcessingPhase finishedPhase) {
352             return resolvePrereq((C) context);
353         }
354
355         @Override
356         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
357             return super.addToStringAttributes(toStringHelper).add("phase", phase);
358         }
359     }
360
361     private final class PhaseModificationInNamespace<C extends Mutable<?, ?, ?>> extends AbstractPrerequisite<C>
362             implements OnNamespaceItemAdded, ContextMutation {
363         private final ModelProcessingPhase modPhase;
364
365         PhaseModificationInNamespace(final ModelProcessingPhase phase) {
366             checkArgument(phase != null, "Model processing phase must not be null");
367             this.modPhase = phase;
368         }
369
370         @SuppressWarnings("unchecked")
371         @Override
372         public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
373                 final Object key, final Object value) {
374             StatementContextBase<?, ?, ?> targetCtx = contextImpl(value);
375             targetCtx.addMutation(modPhase, this);
376             resolvePrereq((C) targetCtx);
377         }
378
379         @Override
380         public boolean isFinished() {
381             return isApplied();
382         }
383     }
384
385     /**
386      * This similar to {@link PhaseModificationInNamespace}, but allows recursive descent until it finds the real
387      * target. The mechanics is driven as a sequence of prerequisites along a path: first we hook onto namespace to
388      * give us the first step. When it does, we hook onto the first item to provide us the second step and so on.
389      */
390     private final class PhaseModificationInNamespacePath<C extends Mutable<?, ?, ?>, K,
391             N extends IdentifierNamespace<K, ? extends StmtContext<?, ?, ?>>> extends AbstractPrerequisite<C>
392             implements OnNamespaceItemAdded, ContextMutation {
393         private final ModelProcessingPhase modPhase;
394         private final Iterable<K> keys;
395         private final Iterator<K> it;
396
397         PhaseModificationInNamespacePath(final ModelProcessingPhase phase, final Iterable<K> keys) {
398             this.modPhase = requireNonNull(phase);
399             this.keys = requireNonNull(keys);
400             it = keys.iterator();
401         }
402
403         @Override
404         public boolean isFinished() {
405             return isApplied();
406         }
407
408         @Override
409         public void namespaceItemAdded(final StatementContextBase<?, ?, ?> context, final Class<?> namespace,
410                 final Object key, final Object value) {
411             LOG.debug("Action for {} got key {}", keys, key);
412
413             final StatementContextBase<?, ?, ?> target = contextImpl(value);
414             if (!target.isSupportedByFeatures()) {
415                 LOG.debug("Key {} in {} is not supported", key, keys);
416                 resolvePrereq(null);
417                 action.prerequisiteUnavailable(this);
418                 return;
419             }
420
421             // Hook onto target: we either have a modification of the target itself or one of its children.
422             target.addMutation(modPhase, this);
423             // We have completed the context -> target step, hence we are no longer directly blocking context from
424             // making forward progress.
425             context.removeMutation(modPhase, this);
426
427             if (!it.hasNext()) {
428                 // Last step: we are done
429                 resolvePrereq((C) value);
430                 return;
431             }
432
433             // Make sure target's storage notifies us when the next step becomes available.
434             hookOnto(target, namespace, it.next());
435         }
436
437         @Override
438         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
439             return super.addToStringAttributes(toStringHelper).add("phase", modPhase).add("keys", keys);
440         }
441
442         void hookOnto(final StmtContext<?, ?, ?> context, final Class<?> namespace) {
443             checkArgument(it.hasNext(), "Namespace %s keys may not be empty", namespace);
444             hookOnto(contextImpl(context), namespace, it.next());
445         }
446
447         @SuppressWarnings("unchecked")
448         private void hookOnto(final StatementContextBase<?, ?, ?> context, final Class<?> namespace, final K key) {
449             context.onNamespaceItemAddedAction((Class) namespace, requireNonNull(key), this);
450         }
451     }
452 }