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