Move more StatementContextBase methods
[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.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static com.google.common.base.Verify.verify;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.collect.ImmutableCollection;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMultimap;
20 import com.google.common.collect.Multimap;
21 import com.google.common.collect.Multimaps;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.EnumMap;
26 import java.util.EventListener;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.stream.Stream;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
38 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
39 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
40 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
41 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
42 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
47 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
61 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
62 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
66 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 /**
71  * Core reactor statement implementation of {@link Mutable}.
72  *
73  * @param <A> Argument type
74  * @param <D> Declared Statement representation
75  * @param <E> Effective Statement representation
76  */
77 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
78         extends ReactorStmtCtx<A, D, E> {
79     /**
80      * Event listener when an item is added to model namespace.
81      */
82     interface OnNamespaceItemAdded extends EventListener {
83         /**
84          * Invoked whenever a new item is added to a namespace.
85          */
86         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
87     }
88
89     /**
90      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
91      */
92     interface OnPhaseFinished extends EventListener {
93         /**
94          * Invoked whenever a processing phase has finished.
95          */
96         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
97     }
98
99     /**
100      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
101      */
102     interface ContextMutation {
103
104         boolean isFinished();
105     }
106
107     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
108
109     // Flag bit assignments
110     private static final int IS_SUPPORTED_BY_FEATURES    = 0x01;
111     private static final int HAVE_SUPPORTED_BY_FEATURES  = 0x02;
112     private static final int IS_IGNORE_IF_FEATURE        = 0x04;
113     private static final int HAVE_IGNORE_IF_FEATURE      = 0x08;
114     // Note: these four are related
115     private static final int IS_IGNORE_CONFIG            = 0x10;
116     private static final int HAVE_IGNORE_CONFIG          = 0x20;
117     private static final int IS_CONFIGURATION            = 0x40;
118     private static final int HAVE_CONFIGURATION          = 0x80;
119
120     // Have-and-set flag constants, also used as masks
121     private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
122     private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
123     // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
124     private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
125     private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
126
127     private final CopyHistory copyHistory;
128     // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
129     //       operations, hence we want to keep it close by.
130     private final @NonNull StatementDefinitionContext<A, D, E> definition;
131
132     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
133     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
134
135     private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
136
137     private @Nullable ModelProcessingPhase completedPhase;
138
139     // Master flag controlling whether this context can yield an effective statement
140     // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
141     //        of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
142     private boolean isSupportedToBuildEffective = true;
143
144     // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
145     private boolean fullyDefined;
146
147     // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
148     // hence improve memory layout.
149     private byte flags;
150
151     // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
152     // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
153     private volatile SchemaPath schemaPath;
154
155     // Copy constructor used by subclasses to implement reparent()
156     StatementContextBase(final StatementContextBase<A, D, E> original) {
157         this.copyHistory = original.copyHistory;
158         this.definition = original.definition;
159
160         this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
161         this.fullyDefined = original.fullyDefined;
162         this.completedPhase = original.completedPhase;
163         this.flags = original.flags;
164     }
165
166     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
167         this.definition = requireNonNull(def);
168         this.copyHistory = CopyHistory.original();
169     }
170
171     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
172         this.definition = requireNonNull(def);
173         this.copyHistory = requireNonNull(copyHistory);
174     }
175
176     @Override
177     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
178         return effectOfStatement;
179     }
180
181     @Override
182     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
183         if (effectOfStatement.isEmpty()) {
184             effectOfStatement = new ArrayList<>(1);
185         }
186         effectOfStatement.add(ctx);
187     }
188
189     @Override
190     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
191         if (ctxs.isEmpty()) {
192             return;
193         }
194
195         if (effectOfStatement.isEmpty()) {
196             effectOfStatement = new ArrayList<>(ctxs.size());
197         }
198         effectOfStatement.addAll(ctxs);
199     }
200
201     @Override
202     public boolean isSupportedByFeatures() {
203         final int fl = flags & SET_SUPPORTED_BY_FEATURES;
204         if (fl != 0) {
205             return fl == SET_SUPPORTED_BY_FEATURES;
206         }
207         if (isIgnoringIfFeatures()) {
208             flags |= SET_SUPPORTED_BY_FEATURES;
209             return true;
210         }
211
212         /*
213          * If parent is supported, we need to check if-features statements of this context.
214          */
215         if (isParentSupportedByFeatures()) {
216             // If the set of supported features has not been provided, all features are supported by default.
217             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
218                     SupportedFeatures.SUPPORTED_FEATURES);
219             if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
220                 flags |= SET_SUPPORTED_BY_FEATURES;
221                 return true;
222             }
223         }
224
225         // Either parent is not supported or this statement is not supported
226         flags |= HAVE_SUPPORTED_BY_FEATURES;
227         return false;
228     }
229
230     protected abstract boolean isParentSupportedByFeatures();
231
232     @Override
233     public boolean isSupportedToBuildEffective() {
234         return isSupportedToBuildEffective;
235     }
236
237     @Override
238     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
239         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
240     }
241
242     @Override
243     public CopyHistory getCopyHistory() {
244         return copyHistory;
245     }
246
247     @Override
248     public ModelProcessingPhase getCompletedPhase() {
249         return completedPhase;
250     }
251
252     // FIXME: this should be propagated through a correct constructor
253     @Deprecated
254     final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
255         this.completedPhase = completedPhase;
256     }
257
258     @Override
259     public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
260             final Class<@NonNull N> type, final T key, final U value) {
261         addToNamespace(type, key, value);
262     }
263
264     static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
265             final List<StatementContextBase<?, ?, ?>> effective) {
266         return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
267     }
268
269     private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
270             final List<StatementContextBase<?, ?, ?>> effective) {
271         return effective.isEmpty() ? ImmutableList.of() : effective;
272     }
273
274     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
275
276     static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
277             final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef) {
278         if (effective.isEmpty()) {
279             return effective;
280         }
281
282         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
283         while (iterator.hasNext()) {
284             final StmtContext<?, ?, ?> next = iterator.next();
285             if (statementDef.equals(next.publicDefinition())) {
286                 iterator.remove();
287             }
288         }
289
290         return shrinkEffective(effective);
291     }
292
293     /**
294      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
295      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
296      * definition and statement argument match with one of the effective substatements' statement definition
297      * and argument.
298      *
299      * <p>
300      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
301      *
302      * @param statementDef statement definition of the statement context to remove
303      * @param statementArg statement argument of the statement context to remove
304      */
305     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
306             String statementArg);
307
308     static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
309             final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef,
310             final String statementArg) {
311         if (statementArg == null) {
312             return removeStatementFromEffectiveSubstatements(effective, statementDef);
313         }
314
315         if (effective.isEmpty()) {
316             return effective;
317         }
318
319         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
320         while (iterator.hasNext()) {
321             final Mutable<?, ?, ?> next = iterator.next();
322             if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
323                 iterator.remove();
324             }
325         }
326
327         return shrinkEffective(effective);
328     }
329
330     // YANG example: RPC/action statements always have 'input' and 'output' defined
331     @Beta
332     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
333             appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
334         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
335         //                       StatementContextBase subclass.
336         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
337                 ImplicitSubstatement.of(sourceReference()), rawArg);
338         support.onStatementAdded(ret);
339         addEffectiveSubstatement(ret);
340         return ret;
341     }
342
343     /**
344      * Adds an effective statement to collection of substatements.
345      *
346      * @param substatement substatement
347      * @throws IllegalStateException if added in declared phase
348      * @throws NullPointerException if statement parameter is null
349      */
350     public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
351
352     final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
353             final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
354         verifyStatement(substatement);
355
356         final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
357         final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
358         final ModelProcessingPhase phase = completedPhase;
359         if (phase != null) {
360             ensureCompletedPhase(stmt, phase);
361         }
362         resized.add(stmt);
363         return resized;
364     }
365
366     /**
367      * Adds an effective statement to collection of substatements.
368      *
369      * @param statements substatements
370      * @throws IllegalStateException
371      *             if added in declared phase
372      * @throws NullPointerException
373      *             if statement parameter is null
374      */
375     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
376         if (!statements.isEmpty()) {
377             statements.forEach(StatementContextBase::verifyStatement);
378             addEffectiveSubstatementsImpl(statements);
379         }
380     }
381
382     abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
383
384     final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
385             final List<StatementContextBase<?, ?, ?>> effective,
386             final Collection<? extends Mutable<?, ?, ?>> statements) {
387         final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
388         final Collection<? extends StatementContextBase<?, ?, ?>> casted =
389             (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
390         final ModelProcessingPhase phase = completedPhase;
391         if (phase != null) {
392             for (StatementContextBase<?, ?, ?> stmt : casted) {
393                 ensureCompletedPhase(stmt, phase);
394             }
395         }
396
397         resized.addAll(casted);
398         return resized;
399     }
400
401     abstract Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete();
402
403     // exposed for InferredStatementContext only
404     final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
405         verifyStatement(stmt);
406         final ModelProcessingPhase phase = completedPhase;
407         if (phase != null) {
408             ensureCompletedPhase((StatementContextBase<?, ?, ?>) stmt, phase);
409         }
410     }
411
412     // Make sure target statement has transitioned at least to specified phase. This method is just before we take
413     // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
414     // any statements which did not complete the same phase as the root statement.
415     private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
416             final ModelProcessingPhase phase) {
417         verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
418     }
419
420     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
421         verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
422     }
423
424     private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
425             final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
426         // We cannot allow statement to be further mutated
427         verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
428             sourceReference());
429         return beforeAddEffectiveStatementUnsafe(effective, toAdd);
430     }
431
432     final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
433             final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
434         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
435         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
436                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
437                 "Effective statement cannot be added in declared phase at: %s", sourceReference());
438
439         return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
440     }
441
442     // These two exists only due to memory optimization, should live in AbstractResumedStatement
443     final boolean fullyDefined() {
444         return fullyDefined;
445     }
446
447     final void setFullyDefined() {
448         fullyDefined = true;
449     }
450
451     // Exposed for ReplicaStatementContext
452     @Override
453     E createEffective() {
454         return definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this), streamDeclared(),
455             streamEffective());
456     }
457
458     abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
459
460     abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
461
462     /**
463      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
464      * this method does nothing.
465      *
466      * @param phase to be executed (completed)
467      * @return true if phase was successfully completed
468      * @throws SourceException when an error occurred in source parsing
469      */
470     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
471         return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
472     }
473
474     private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
475         final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
476         if (completeChildren(phase) && finished) {
477             onPhaseCompleted(phase);
478             return true;
479         }
480         return false;
481     }
482
483     private boolean completeChildren(final ModelProcessingPhase phase) {
484         boolean finished = true;
485         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
486             finished &= child.tryToCompletePhase(phase);
487         }
488         for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
489             finished &= child.tryToCompletePhase(phase);
490         }
491         return finished;
492     }
493
494     private boolean runMutations(final ModelProcessingPhase phase) {
495         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
496         return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
497     }
498
499     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
500         boolean finished = true;
501         final Iterator<ContextMutation> it = openMutations.iterator();
502         while (it.hasNext()) {
503             final ContextMutation current = it.next();
504             if (current.isFinished()) {
505                 it.remove();
506             } else {
507                 finished = false;
508             }
509         }
510
511         if (openMutations.isEmpty()) {
512             phaseMutation.removeAll(phase);
513             cleanupPhaseMutation();
514         }
515         return finished;
516     }
517
518     private void cleanupPhaseMutation() {
519         if (phaseMutation.isEmpty()) {
520             phaseMutation = ImmutableMultimap.of();
521         }
522     }
523
524     /**
525      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
526      *
527      * @param phase
528      *            that was to be completed (finished)
529      * @throws SourceException
530      *             when an error occurred in source parsing
531      */
532     private void onPhaseCompleted(final ModelProcessingPhase phase) {
533         completedPhase = phase;
534
535         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
536         if (!listeners.isEmpty()) {
537             runPhaseListeners(phase, listeners);
538         }
539     }
540
541     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
542         final Iterator<OnPhaseFinished> listener = listeners.iterator();
543         while (listener.hasNext()) {
544             final OnPhaseFinished next = listener.next();
545             if (next.phaseFinished(this, phase)) {
546                 listener.remove();
547             }
548         }
549
550         if (listeners.isEmpty()) {
551             phaseListeners.removeAll(phase);
552             if (phaseListeners.isEmpty()) {
553                 phaseListeners = ImmutableMultimap.of();
554             }
555         }
556     }
557
558     /**
559      * Ends declared section of current node.
560      */
561     void endDeclared(final ModelProcessingPhase phase) {
562         definition.onDeclarationFinished(this, phase);
563     }
564
565     @Override
566     final StatementDefinitionContext<A, D, E> definition() {
567         return definition;
568     }
569
570     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
571             final OnNamespaceItemAdded listener) {
572         final Object potential = getFromNamespace(type, key);
573         if (potential != null) {
574             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
575             listener.namespaceItemAdded(this, type, key, potential);
576             return;
577         }
578
579         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
580             @Override
581             void onValueAdded(final Object value) {
582                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
583             }
584         });
585     }
586
587     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
588             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
589             final OnNamespaceItemAdded listener) {
590         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
591         if (existing.isPresent()) {
592             final Entry<K, V> entry = existing.get();
593             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
594             waitForPhase(entry.getValue(), type, phase, criterion, listener);
595             return;
596         }
597
598         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
599         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
600             @Override
601             boolean onValueAdded(final K key, final V value) {
602                 if (criterion.match(key)) {
603                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
604                     waitForPhase(value, type, phase, criterion, listener);
605                     return true;
606                 }
607
608                 return false;
609             }
610         });
611     }
612
613     final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
614             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
615         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
616         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
617             type, this);
618         final Entry<K, V> match = optMatch.get();
619         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
620     }
621
622     final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
623             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
624             final OnNamespaceItemAdded listener) {
625         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
626             (context, phaseCompleted) -> {
627                 selectMatch(type, criterion, listener);
628                 return true;
629             });
630     }
631
632     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
633             final Class<N> type) {
634         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
635         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
636             type);
637
638         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
639     }
640
641     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
642         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
643     }
644
645     /**
646      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
647      * the listener is notified immediately.
648      *
649      * @param phase requested completion phase
650      * @param listener listener to invoke
651      * @throws NullPointerException if any of the arguments is null
652      */
653     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
654         checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
655         checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
656
657         ModelProcessingPhase finishedPhase = completedPhase;
658         while (finishedPhase != null) {
659             if (phase.equals(finishedPhase)) {
660                 listener.phaseFinished(this, finishedPhase);
661                 return;
662             }
663             finishedPhase = finishedPhase.getPreviousPhase();
664         }
665         if (phaseListeners.isEmpty()) {
666             phaseListeners = newMultimap();
667         }
668
669         phaseListeners.put(phase, listener);
670     }
671
672     /**
673      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
674      *
675      * @throws IllegalStateException when the mutation was registered after phase was completed
676      */
677     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
678         ModelProcessingPhase finishedPhase = completedPhase;
679         while (finishedPhase != null) {
680             checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
681                 sourceReference());
682             finishedPhase = finishedPhase.getPreviousPhase();
683         }
684
685         if (phaseMutation.isEmpty()) {
686             phaseMutation = newMultimap();
687         }
688         phaseMutation.put(phase, mutation);
689     }
690
691     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
692         if (!phaseMutation.isEmpty()) {
693             phaseMutation.remove(phase, mutation);
694             cleanupPhaseMutation();
695         }
696     }
697
698     @Override
699     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
700             final KT key,final StmtContext<?, ?, ?> stmt) {
701         addContextToNamespace(namespace, key, stmt);
702     }
703
704     @Override
705     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
706             final QNameModule targetModule) {
707         checkEffectiveModelCompleted(this);
708
709         final StatementSupport<A, D, E> support = definition.support();
710         final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
711         switch (policy) {
712             case CONTEXT_INDEPENDENT:
713                 if (hasEmptySubstatements()) {
714                     // This statement is context-independent and has no substatements -- hence it can be freely shared.
715                     return Optional.of(replicaAsChildOf(parent));
716                 }
717                 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
718                 // fall through
719             case DECLARED_COPY:
720                 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
721                 //                       context, so that we can support building an effective statement without copying
722                 //                       anything -- we will typically end up not being inferred against. In that case,
723                 //                       this slim context should end up dealing with differences at buildContext()
724                 //                       time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
725                 //                       cannot be shared across instances).
726                 return Optional.of(parent.childCopyOf(this, type, targetModule));
727             case IGNORE:
728                 return Optional.empty();
729             case REJECT:
730                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
731             default:
732                 throw new IllegalStateException("Unhandled policy " + policy);
733         }
734     }
735
736     @Override
737     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
738             final QNameModule targetModule) {
739         checkEffectiveModelCompleted(stmt);
740         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
741         return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
742     }
743
744     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
745             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
746         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
747             original.publicDefinition());
748
749         final StatementContextBase<X, Y, Z> result;
750         final InferredStatementContext<X, Y, Z> copy;
751
752         if (implicitParent.isPresent()) {
753             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
754             result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
755                 original.argument(), type);
756
757             final CopyType childCopyType;
758             switch (type) {
759                 case ADDED_BY_AUGMENTATION:
760                     childCopyType = CopyType.ORIGINAL;
761                     break;
762                 case ADDED_BY_USES_AUGMENTATION:
763                     childCopyType = CopyType.ADDED_BY_USES;
764                     break;
765                 case ADDED_BY_USES:
766                 case ORIGINAL:
767                 default:
768                     childCopyType = type;
769             }
770
771             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
772             result.addEffectiveSubstatement(copy);
773         } else {
774             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
775         }
776
777         original.definition.onStatementAdded(copy);
778         return result;
779     }
780
781     @Override
782     public final StatementContextBase<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
783         checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
784         return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
785     }
786
787     final @NonNull StatementContextBase<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
788         return new ReplicaStatementContext<>(stmt, this);
789     }
790
791     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
792         final ModelProcessingPhase phase = stmt.getCompletedPhase();
793         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
794                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
795     }
796
797     @Beta
798     public final boolean hasImplicitParentSupport() {
799         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
800     }
801
802     @Beta
803     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
804         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
805             original.publicDefinition());
806         if (optImplicit.isEmpty()) {
807             return original;
808         }
809
810         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
811         final CopyType type = original.getCopyHistory().getLastOperation();
812         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
813             original.sourceReference(), original.rawArgument(), original.argument(), type);
814
815         result.addEffectiveSubstatement(original.reparent(result));
816         result.setCompletedPhase(original.getCompletedPhase());
817         return result;
818     }
819
820     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
821
822     /**
823      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
824      *
825      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
826      */
827     abstract boolean hasEmptySubstatements();
828
829     /**
830      * Config statements are not all that common which means we are performing a recursive search towards the root
831      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
832      * for the (usually non-existent) config statement.
833      *
834      * <p>
835      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
836      * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
837      *
838      * <p>
839      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
840      *       {@link #isIgnoringConfig(StatementContextBase)}.
841      */
842     final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
843         final int fl = flags & SET_CONFIGURATION;
844         if (fl != 0) {
845             return fl == SET_CONFIGURATION;
846         }
847         if (isIgnoringConfig(parent)) {
848             // Note: SET_CONFIGURATION has been stored in flags
849             return true;
850         }
851
852         final boolean isConfig;
853         final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
854         if (optConfig.isPresent()) {
855             isConfig = optConfig.orElseThrow();
856             if (isConfig) {
857                 // Validity check: if parent is config=false this cannot be a config=true
858                 InferenceException.throwIf(!parent.isConfiguration(), sourceReference(),
859                         "Parent node has config=false, this node must not be specifed as config=true");
860             }
861         } else {
862             // If "config" statement is not specified, the default is the same as the parent's "config" value.
863             isConfig = parent.isConfiguration();
864         }
865
866         // Resolved, make sure we cache this return
867         flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
868         return isConfig;
869     }
870
871     protected abstract boolean isIgnoringConfig();
872
873     /**
874      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
875      * keep on returning the same result without performing any lookups. Exists only to support
876      * {@link SubstatementContext#isIgnoringConfig()}.
877      *
878      * <p>
879      * Note: use of this method implies that {@link #isConfiguration()} is realized with
880      *       {@link #isConfiguration(StatementContextBase)}.
881      */
882     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
883         final int fl = flags & SET_IGNORE_CONFIG;
884         if (fl != 0) {
885             return fl == SET_IGNORE_CONFIG;
886         }
887         if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
888             flags |= SET_IGNORE_CONFIG;
889             return true;
890         }
891
892         flags |= HAVE_IGNORE_CONFIG;
893         return false;
894     }
895
896     protected abstract boolean isIgnoringIfFeatures();
897
898     /**
899      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
900      * keep on returning the same result without performing any lookups. Exists only to support
901      * {@link SubstatementContext#isIgnoringIfFeatures()}.
902      */
903     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
904         final int fl = flags & SET_IGNORE_IF_FEATURE;
905         if (fl != 0) {
906             return fl == SET_IGNORE_IF_FEATURE;
907         }
908         if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
909             flags |= SET_IGNORE_IF_FEATURE;
910             return true;
911         }
912
913         flags |= HAVE_IGNORE_IF_FEATURE;
914         return false;
915     }
916
917     abstract @NonNull Optional<SchemaPath> schemaPath();
918
919     // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
920     @Deprecated
921     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
922         SchemaPath local = schemaPath;
923         if (local == null) {
924             synchronized (this) {
925                 local = schemaPath;
926                 if (local == null) {
927                     schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
928                 }
929             }
930         }
931
932         return Optional.ofNullable(local);
933     }
934
935     @Deprecated
936     private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
937         final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
938         verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
939         final SchemaPath parentPath = maybeParentPath.get();
940
941         if (StmtContextUtils.isUnknownStatement(this)) {
942             return parentPath.createChild(publicDefinition().getStatementName());
943         }
944         final Object argument = argument();
945         if (argument instanceof QName) {
946             final QName qname = (QName) argument;
947             if (producesDeclared(UsesStatement.class)) {
948                 return maybeParentPath.orElse(null);
949             }
950
951             return parentPath.createChild(qname);
952         }
953         if (argument instanceof String) {
954             // FIXME: This may yield illegal argument exceptions
955             final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
956             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
957             return parentPath.createChild(qname);
958         }
959         if (argument instanceof SchemaNodeIdentifier
960                 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
961                         || producesDeclared(DeviationStatement.class))) {
962
963             return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
964         }
965
966         // FIXME: this does not look right
967         return maybeParentPath.orElse(null);
968     }
969 }