CopyHistory should be an interface
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.java
1 /*
2  * Copyright (c) 2015 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.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.VerifyException;
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.Multimap;
22 import com.google.common.collect.Multimaps;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.EventListener;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.stream.Stream;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
56 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * Core reactor statement implementation of {@link Mutable}.
62  *
63  * @param <A> Argument type
64  * @param <D> Declared Statement representation
65  * @param <E> Effective Statement representation
66  */
67 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
68         extends ReactorStmtCtx<A, D, E> implements CopyHistory {
69     /**
70      * Event listener when an item is added to model namespace.
71      */
72     interface OnNamespaceItemAdded extends EventListener {
73         /**
74          * Invoked whenever a new item is added to a namespace.
75          */
76         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
77     }
78
79     /**
80      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
81      */
82     interface OnPhaseFinished extends EventListener {
83         /**
84          * Invoked whenever a processing phase has finished.
85          */
86         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
87     }
88
89     /**
90      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
91      */
92     interface ContextMutation {
93
94         boolean isFinished();
95     }
96
97     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
98
99     //
100     // {@link CopyHistory} encoded as a single byte. We still have 4 bits unused.
101     //
102     private static final byte COPY_LAST_TYPE_MASK        = 0x03;
103     private static final byte COPY_ADDED_BY_USES         = 0x04;
104     private static final byte COPY_ADDED_BY_AUGMENTATION = 0x08;
105     private static final byte COPY_ORIGINAL              = 0x00;
106
107     private final byte copyHistory;
108
109     static {
110         final int copyTypes = CopyType.values().length;
111         // This implies CopyType.ordinal() is <= COPY_TYPE_MASK
112         verify(copyTypes == COPY_LAST_TYPE_MASK + 1, "Unexpected %s CopyType values", copyTypes);
113     }
114
115     // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
116     //       operations, hence we want to keep it close by.
117     private final @NonNull StatementDefinitionContext<A, D, E> definition;
118
119     // TODO: consider keying by Byte equivalent of ExecutionOrder
120     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
121     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
122
123     private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
124
125     /**
126      * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
127      */
128     private byte executionOrder;
129
130     // Copy constructor used by subclasses to implement reparent()
131     StatementContextBase(final StatementContextBase<A, D, E> original) {
132         super(original);
133         this.copyHistory = original.copyHistory;
134         this.definition = original.definition;
135         this.executionOrder = original.executionOrder;
136     }
137
138     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
139         this.definition = requireNonNull(def);
140         this.copyHistory = COPY_ORIGINAL;
141     }
142
143     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final byte copyHistory) {
144         this.definition = requireNonNull(def);
145         this.copyHistory = copyHistory;
146     }
147
148     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
149         this.definition = requireNonNull(def);
150         this.copyHistory = (byte) copyFlags(copyType);
151     }
152
153     StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType) {
154         this.definition = prototype.definition;
155         this.copyHistory = (byte) (copyFlags(copyType) | prototype.copyHistory & ~COPY_LAST_TYPE_MASK);
156     }
157
158     private static int copyFlags(final CopyType copyType) {
159         return historyFlags(copyType) | copyType.ordinal();
160     }
161
162     private static byte historyFlags(final CopyType copyType) {
163         switch (copyType) {
164             case ADDED_BY_AUGMENTATION:
165                 return COPY_ADDED_BY_AUGMENTATION;
166             case ADDED_BY_USES:
167                 return COPY_ADDED_BY_USES;
168             case ADDED_BY_USES_AUGMENTATION:
169                 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
170             case ORIGINAL:
171                 return COPY_ORIGINAL;
172             default:
173                 throw new VerifyException("Unhandled type " + copyType);
174         }
175     }
176
177     @Override
178     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
179         return effectOfStatement;
180     }
181
182     @Override
183     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
184         if (ctxs.isEmpty()) {
185             return;
186         }
187
188         if (effectOfStatement.isEmpty()) {
189             effectOfStatement = new ArrayList<>(ctxs.size());
190         }
191         effectOfStatement.addAll(ctxs);
192     }
193
194     //
195     // CopyHistory integration
196     //
197
198     @Override
199     public final CopyHistory history() {
200         return this;
201     }
202
203     @Override
204     public final boolean isAddedByUses() {
205         return (copyHistory & COPY_ADDED_BY_USES) != 0;
206     }
207
208     @Override
209     public final boolean isAugmenting() {
210         return (copyHistory & COPY_ADDED_BY_AUGMENTATION) != 0;
211     }
212
213     @Override
214     public final CopyType getLastOperation() {
215         return CopyType.values()[copyHistory & COPY_LAST_TYPE_MASK];
216     }
217
218     //
219     // Inference completion tracking
220     //
221
222     @Override
223     final byte executionOrder() {
224         return executionOrder;
225     }
226
227     // FIXME: this should be propagated through a correct constructor
228     @Deprecated
229     final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
230         this.executionOrder = completedPhase.executionOrder();
231     }
232
233     @Override
234     public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
235             final Class<@NonNull N> type, final T key, final U value) {
236         addToNamespace(type, key, value);
237     }
238
239     static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
240             final List<ReactorStmtCtx<?, ?, ?>> effective) {
241         return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
242     }
243
244     private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
245         return effective.isEmpty() ? ImmutableList.of() : effective;
246     }
247
248     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
249
250     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
251             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
252         if (effective.isEmpty()) {
253             return effective;
254         }
255
256         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
257         while (iterator.hasNext()) {
258             final StmtContext<?, ?, ?> next = iterator.next();
259             if (statementDef.equals(next.publicDefinition())) {
260                 iterator.remove();
261             }
262         }
263
264         return shrinkEffective(effective);
265     }
266
267     /**
268      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
269      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
270      * definition and statement argument match with one of the effective substatements' statement definition
271      * and argument.
272      *
273      * <p>
274      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
275      *
276      * @param statementDef statement definition of the statement context to remove
277      * @param statementArg statement argument of the statement context to remove
278      */
279     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
280             String statementArg);
281
282     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
283             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
284             final String statementArg) {
285         if (statementArg == null) {
286             return removeStatementFromEffectiveSubstatements(effective, statementDef);
287         }
288
289         if (effective.isEmpty()) {
290             return effective;
291         }
292
293         final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
294         while (iterator.hasNext()) {
295             final Mutable<?, ?, ?> next = iterator.next();
296             if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
297                 iterator.remove();
298             }
299         }
300
301         return shrinkEffective(effective);
302     }
303
304     // YANG example: RPC/action statements always have 'input' and 'output' defined
305     @Beta
306     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
307             appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
308         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
309         //                       StatementContextBase subclass.
310         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
311                 ImplicitSubstatement.of(sourceReference()), rawArg);
312         support.onStatementAdded(ret);
313         addEffectiveSubstatement(ret);
314         return ret;
315     }
316
317     /**
318      * Adds an effective statement to collection of substatements.
319      *
320      * @param substatement substatement
321      * @throws IllegalStateException if added in declared phase
322      * @throws NullPointerException if statement parameter is null
323      */
324     public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
325
326     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
327             final Mutable<?, ?, ?> substatement) {
328         verifyStatement(substatement);
329
330         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
331         final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
332         ensureCompletedExecution(stmt);
333         resized.add(stmt);
334         return resized;
335     }
336
337     /**
338      * Adds an effective statement to collection of substatements.
339      *
340      * @param statements substatements
341      * @throws IllegalStateException
342      *             if added in declared phase
343      * @throws NullPointerException
344      *             if statement parameter is null
345      */
346     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
347         if (!statements.isEmpty()) {
348             statements.forEach(StatementContextBase::verifyStatement);
349             addEffectiveSubstatementsImpl(statements);
350         }
351     }
352
353     abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
354
355     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
356             final Collection<? extends Mutable<?, ?, ?>> statements) {
357         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
358         final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
359             (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
360         if (executionOrder != ExecutionOrder.NULL) {
361             for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
362                 ensureCompletedExecution(stmt, executionOrder);
363             }
364         }
365
366         resized.addAll(casted);
367         return resized;
368     }
369
370     abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
371
372     // exposed for InferredStatementContext only
373     final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
374         verifyStatement(stmt);
375         ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
376     }
377
378     // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
379     // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
380     // contain any statements which did not complete the same phase as the root statement.
381     private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
382         if (executionOrder != ExecutionOrder.NULL) {
383             ensureCompletedExecution(stmt, executionOrder);
384         }
385     }
386
387     private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
388         verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
389     }
390
391     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
392         verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
393     }
394
395     private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
396             final int toAdd) {
397         // We cannot allow statement to be further mutated.
398         // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
399         //       a phase after EFFECTIVE_MODEL
400         verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
401             sourceReference());
402         return beforeAddEffectiveStatementUnsafe(effective, toAdd);
403     }
404
405     final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
406             final int toAdd) {
407         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
408         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
409                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
410                 "Effective statement cannot be added in declared phase at: %s", sourceReference());
411
412         return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
413     }
414
415     @Override
416     final E createEffective() {
417         final E result = createEffective(definition.getFactory());
418         if (result instanceof MutableStatement) {
419             getRoot().addMutableStmtToSeal((MutableStatement) result);
420         }
421         return result;
422     }
423
424     @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
425         return createEffective(factory, this);
426     }
427
428     // Creates EffectiveStatement through full materialization
429     static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
430             final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
431         return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
432     }
433
434     /**
435      * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
436      * {@link StmtContext#buildEffective()} contract.
437      *
438      * @return Stream of supported declared statements.
439      */
440     // FIXME: we really want to unify this with streamEffective(), under its name
441     abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
442
443     /**
444      * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
445      * {@link StmtContext#buildEffective()} contract.
446      *
447      * @return Stream of supported effective statements.
448      */
449     // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
450     abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
451
452     @Override
453     final boolean doTryToCompletePhase(final byte targetOrder) {
454         final boolean finished = phaseMutation.isEmpty() ? true : runMutations(targetOrder);
455         if (completeChildren(targetOrder) && finished) {
456             onPhaseCompleted(targetOrder);
457             return true;
458         }
459         return false;
460     }
461
462     private boolean completeChildren(final byte targetOrder) {
463         boolean finished = true;
464         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
465             finished &= child.tryToCompletePhase(targetOrder);
466         }
467         for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
468             finished &= child.tryToCompletePhase(targetOrder);
469         }
470         return finished;
471     }
472
473     private boolean runMutations(final byte targetOrder) {
474         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
475         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
476         return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
477     }
478
479     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
480         boolean finished = true;
481         final Iterator<ContextMutation> it = openMutations.iterator();
482         while (it.hasNext()) {
483             final ContextMutation current = it.next();
484             if (current.isFinished()) {
485                 it.remove();
486             } else {
487                 finished = false;
488             }
489         }
490
491         if (openMutations.isEmpty()) {
492             phaseMutation.removeAll(phase);
493             cleanupPhaseMutation();
494         }
495         return finished;
496     }
497
498     private void cleanupPhaseMutation() {
499         if (phaseMutation.isEmpty()) {
500             phaseMutation = ImmutableMultimap.of();
501         }
502     }
503
504     /**
505      * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
506      * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
507      *
508      * @param phase that was to be completed (finished)
509      * @throws SourceException when an error occurred in source parsing
510      */
511     private void onPhaseCompleted(final byte completedOrder) {
512         executionOrder = completedOrder;
513         if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
514             // We have completed effective model, substatements are guaranteed not to change
515             summarizeSubstatementPolicy();
516         }
517
518         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
519         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
520         if (!listeners.isEmpty()) {
521             runPhaseListeners(phase, listeners);
522         }
523     }
524
525     private void summarizeSubstatementPolicy() {
526         if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
527             setAllSubstatementsContextIndependent();
528         }
529     }
530
531     /**
532      * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
533      * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
534      * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
535      * considered copy-insensitive.
536      *
537      * <p>
538      * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
539      *
540      * @return True if no substatements require copy-sensitive handling
541      */
542     abstract boolean noSensitiveSubstatements();
543
544     /**
545      * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
546      * {@link #noSensitiveSubstatements()}.
547      *
548      * @param substatements Substatements to check
549      * @return True if no substatements require context-sensitive handling
550      */
551     static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
552         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
553             if (stmt.isSupportedToBuildEffective()) {
554                 if (!stmt.allSubstatementsContextIndependent()) {
555                     // This is a recursive property
556                     return false;
557                 }
558
559                 switch (stmt.definition().support().copyPolicy()) {
560                     case CONTEXT_INDEPENDENT:
561                     case EXACT_REPLICA:
562                     case IGNORE:
563                         break;
564                     default:
565                         return false;
566                 }
567             }
568         }
569         return true;
570     }
571
572     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
573         final Iterator<OnPhaseFinished> listener = listeners.iterator();
574         while (listener.hasNext()) {
575             final OnPhaseFinished next = listener.next();
576             if (next.phaseFinished(this, phase)) {
577                 listener.remove();
578             }
579         }
580
581         if (listeners.isEmpty()) {
582             phaseListeners.removeAll(phase);
583             if (phaseListeners.isEmpty()) {
584                 phaseListeners = ImmutableMultimap.of();
585             }
586         }
587     }
588
589     /**
590      * Ends declared section of current node.
591      */
592     void endDeclared(final ModelProcessingPhase phase) {
593         definition.onDeclarationFinished(this, phase);
594     }
595
596     @Override
597     final StatementDefinitionContext<A, D, E> definition() {
598         return definition;
599     }
600
601     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
602             final OnNamespaceItemAdded listener) {
603         final Object potential = getFromNamespace(type, key);
604         if (potential != null) {
605             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
606             listener.namespaceItemAdded(this, type, key, potential);
607             return;
608         }
609
610         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
611             @Override
612             void onValueAdded(final Object value) {
613                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
614             }
615         });
616     }
617
618     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
619             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
620             final OnNamespaceItemAdded listener) {
621         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
622         if (existing.isPresent()) {
623             final Entry<K, V> entry = existing.get();
624             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
625             waitForPhase(entry.getValue(), type, phase, criterion, listener);
626             return;
627         }
628
629         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
630         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
631             @Override
632             boolean onValueAdded(final K key, final V value) {
633                 if (criterion.match(key)) {
634                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
635                     waitForPhase(value, type, phase, criterion, listener);
636                     return true;
637                 }
638
639                 return false;
640             }
641         });
642     }
643
644     final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
645             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
646         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
647         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
648             type, this);
649         final Entry<K, V> match = optMatch.get();
650         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
651     }
652
653     final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
654             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
655             final OnNamespaceItemAdded listener) {
656         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
657             (context, phaseCompleted) -> {
658                 selectMatch(type, criterion, listener);
659                 return true;
660             });
661     }
662
663     private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
664             final Class<N> type) {
665         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
666         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
667             type);
668
669         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
670     }
671
672     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
673         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
674     }
675
676     /**
677      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
678      * the listener is notified immediately.
679      *
680      * @param phase requested completion phase
681      * @param listener listener to invoke
682      * @throws NullPointerException if any of the arguments is null
683      */
684     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
685         requireNonNull(phase, "Statement context processing phase cannot be null");
686         requireNonNull(listener, "Statement context phase listener cannot be null");
687
688         ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
689         while (finishedPhase != null) {
690             if (phase.equals(finishedPhase)) {
691                 listener.phaseFinished(this, finishedPhase);
692                 return;
693             }
694             finishedPhase = finishedPhase.getPreviousPhase();
695         }
696         if (phaseListeners.isEmpty()) {
697             phaseListeners = newMultimap();
698         }
699
700         phaseListeners.put(phase, listener);
701     }
702
703     /**
704      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
705      *
706      * @throws IllegalStateException when the mutation was registered after phase was completed
707      */
708     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
709         checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
710             sourceReference());
711
712         if (phaseMutation.isEmpty()) {
713             phaseMutation = newMultimap();
714         }
715         phaseMutation.put(phase, mutation);
716     }
717
718     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
719         if (!phaseMutation.isEmpty()) {
720             phaseMutation.remove(phase, mutation);
721             cleanupPhaseMutation();
722         }
723     }
724
725     @Override
726     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
727             final KT key,final StmtContext<?, ?, ?> stmt) {
728         addContextToNamespace(namespace, key, stmt);
729     }
730
731     @Override
732     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
733             final QNameModule targetModule) {
734         checkEffectiveModelCompleted(this);
735         return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
736     }
737
738     private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
739             final QNameModule targetModule) {
740         final StatementSupport<A, D, E> support = definition.support();
741         final CopyPolicy policy = support.copyPolicy();
742         switch (policy) {
743             case EXACT_REPLICA:
744                 return replicaAsChildOf(parent);
745             case CONTEXT_INDEPENDENT:
746                 if (allSubstatementsContextIndependent()) {
747                     return replicaAsChildOf(parent);
748                 }
749
750                 // fall through
751             case DECLARED_COPY:
752                 // FIXME: ugly cast
753                 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
754             case IGNORE:
755                 return null;
756             case REJECT:
757                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
758             default:
759                 throw new IllegalStateException("Unhandled policy " + policy);
760         }
761     }
762
763     @Override
764     final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
765             final QNameModule targetModule) {
766         final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
767         if (copy == null) {
768             // The statement fizzled, this should never happen, perhaps a verify()?
769             return null;
770         }
771
772         parent.ensureCompletedPhase(copy);
773         return canReuseCurrent(copy) ? this : copy;
774     }
775
776     private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
777         // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
778         // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
779         return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
780             && allSubstatementsContextIndependent();
781     }
782
783     @Override
784     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
785             final QNameModule targetModule) {
786         checkEffectiveModelCompleted(stmt);
787         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
788         return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
789     }
790
791     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
792             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
793         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
794             original.publicDefinition());
795
796         final StatementContextBase<X, Y, Z> result;
797         final InferredStatementContext<X, Y, Z> copy;
798
799         if (implicitParent.isPresent()) {
800             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
801             result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
802                 original.argument(), type);
803
804             final CopyType childCopyType;
805             switch (type) {
806                 case ADDED_BY_AUGMENTATION:
807                     childCopyType = CopyType.ORIGINAL;
808                     break;
809                 case ADDED_BY_USES_AUGMENTATION:
810                     childCopyType = CopyType.ADDED_BY_USES;
811                     break;
812                 case ADDED_BY_USES:
813                 case ORIGINAL:
814                 default:
815                     childCopyType = type;
816             }
817
818             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
819             result.addEffectiveSubstatement(copy);
820         } else {
821             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
822         }
823
824         original.definition.onStatementAdded(copy);
825         return result;
826     }
827
828     @Override
829     final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
830         return new ReplicaStatementContext<>(parent, this);
831     }
832
833     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
834         final ModelProcessingPhase phase = stmt.getCompletedPhase();
835         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
836                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
837     }
838
839     @Beta
840     public final boolean hasImplicitParentSupport() {
841         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
842     }
843
844     @Beta
845     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
846         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
847             original.publicDefinition());
848         if (optImplicit.isEmpty()) {
849             return original;
850         }
851
852         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
853         final CopyType type = original.history().getLastOperation();
854         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
855             original.sourceReference(), original.rawArgument(), original.argument(), type);
856
857         result.addEffectiveSubstatement(original.reparent(result));
858         result.setCompletedPhase(original.getCompletedPhase());
859         return result;
860     }
861
862     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
863
864     /**
865      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
866      *
867      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
868      */
869     abstract boolean hasEmptySubstatements();
870 }