Fix StmtContext nullness problems
[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.base.MoreObjects;
16 import com.google.common.base.MoreObjects.ToStringHelper;
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.ImmutableSet;
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.Map.Entry;
30 import java.util.Objects;
31 import java.util.Optional;
32 import java.util.Set;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.util.OptionalBoolean;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
39 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
40 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
42 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
43 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
56 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
57 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter.ResumedStatement;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
61 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
62 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
67         extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
68     /**
69      * Event listener when an item is added to model namespace.
70      */
71     interface OnNamespaceItemAdded extends EventListener {
72         /**
73          * Invoked whenever a new item is added to a namespace.
74          */
75         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
76     }
77
78     /**
79      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
80      */
81     interface OnPhaseFinished extends EventListener {
82         /**
83          * Invoked whenever a processing phase has finished.
84          */
85         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
86     }
87
88     /**
89      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
90      */
91     interface ContextMutation {
92
93         boolean isFinished();
94     }
95
96     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
97
98     private final @NonNull StatementDefinitionContext<A, D, E> definition;
99     private final @NonNull StatementSourceReference statementDeclSource;
100     private final StmtContext<?, ?, ?> originalCtx;
101     private final CopyHistory copyHistory;
102     private final String rawArgument;
103
104     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
105     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
106     private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
107     private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
108     private StatementMap substatements = StatementMap.empty();
109
110     private boolean isSupportedToBuildEffective = true;
111     private @Nullable ModelProcessingPhase completedPhase;
112     private @Nullable D declaredInstance;
113     private @Nullable E effectiveInstance;
114
115     // BooleanFields value
116     private byte supportedByFeatures;
117
118     private boolean fullyDefined;
119
120     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
121             final String rawArgument) {
122         this.definition = requireNonNull(def);
123         this.statementDeclSource = requireNonNull(ref);
124         this.rawArgument = def.internArgument(rawArgument);
125         this.copyHistory = CopyHistory.original();
126         this.originalCtx = null;
127     }
128
129     StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
130         this.definition = original.definition;
131         this.statementDeclSource = original.statementDeclSource;
132         this.rawArgument = original.rawArgument;
133         this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
134         this.originalCtx = original.getOriginalCtx().orElse(original);
135     }
136
137     @Override
138     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
139         return effectOfStatement;
140     }
141
142     @Override
143     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
144         if (effectOfStatement.isEmpty()) {
145             effectOfStatement = new ArrayList<>(1);
146         }
147         effectOfStatement.add(ctx);
148     }
149
150     @Override
151     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
152         if (ctxs.isEmpty()) {
153             return;
154         }
155
156         if (effectOfStatement.isEmpty()) {
157             effectOfStatement = new ArrayList<>(ctxs.size());
158         }
159         effectOfStatement.addAll(ctxs);
160     }
161
162     @Override
163     public boolean isSupportedByFeatures() {
164         if (OptionalBoolean.isPresent(supportedByFeatures)) {
165             return OptionalBoolean.get(supportedByFeatures);
166         }
167
168         if (isIgnoringIfFeatures()) {
169             supportedByFeatures = OptionalBoolean.of(true);
170             return true;
171         }
172
173         final boolean isParentSupported = isParentSupportedByFeatures();
174         /*
175          * If parent is not supported, then this context is also not supported.
176          * So we do not need to check if-features statements of this context and
177          * we can return false immediately.
178          */
179         if (!isParentSupported) {
180             supportedByFeatures = OptionalBoolean.of(false);
181             return false;
182         }
183
184         /*
185          * If parent is supported, we need to check if-features statements of
186          * this context.
187          */
188         // If the set of supported features has not been provided, all features are supported by default.
189         final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
190                 SupportedFeatures.SUPPORTED_FEATURES);
191         final boolean ret = supportedFeatures == null ? true
192                 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
193
194         supportedByFeatures = OptionalBoolean.of(ret);
195         return ret;
196     }
197
198     protected abstract boolean isParentSupportedByFeatures();
199
200     protected abstract boolean isIgnoringIfFeatures();
201
202     protected abstract boolean isIgnoringConfig();
203
204     @Override
205     public boolean isSupportedToBuildEffective() {
206         return isSupportedToBuildEffective;
207     }
208
209     @Override
210     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
211         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
212     }
213
214     @Override
215     public CopyHistory getCopyHistory() {
216         return copyHistory;
217     }
218
219     @Override
220     public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
221         return Optional.ofNullable(originalCtx);
222     }
223
224     @Override
225     public ModelProcessingPhase getCompletedPhase() {
226         return completedPhase;
227     }
228
229     @Override
230     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
231         this.completedPhase = completedPhase;
232     }
233
234     @Override
235     public abstract StatementContextBase<?, ?, ?> getParentContext();
236
237     /**
238      * Returns the model root for this statement.
239      *
240      * @return root context of statement
241      */
242     @Override
243     public abstract RootStatementContext<?, ?, ?> getRoot();
244
245     /**
246      * Returns the origin of the statement.
247      *
248      * @return origin of statement
249      */
250     @Override
251     public StatementSource getStatementSource() {
252         return statementDeclSource.getStatementSource();
253     }
254
255     /**
256      * Returns a reference to statement source.
257      *
258      * @return reference of statement source
259      */
260     @Override
261     public StatementSourceReference getStatementSourceReference() {
262         return statementDeclSource;
263     }
264
265     @Override
266     public final String rawStatementArgument() {
267         return rawArgument;
268     }
269
270     @Override
271     public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
272         return substatements.values();
273     }
274
275     @Override
276     public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
277         return substatements.values();
278     }
279
280     @Override
281     public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
282         return mutableEffectiveSubstatements();
283     }
284
285     @Override
286     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
287         if (effective instanceof ImmutableCollection) {
288             return effective;
289         }
290
291         return Collections.unmodifiableCollection(effective);
292     }
293
294     public void removeStatementsFromEffectiveSubstatements(
295             final Collection<? extends StmtContext<?, ?, ?>> statements) {
296         if (!effective.isEmpty()) {
297             effective.removeAll(statements);
298             shrinkEffective();
299         }
300     }
301
302     private void shrinkEffective() {
303         if (effective.isEmpty()) {
304             effective = ImmutableList.of();
305         }
306     }
307
308     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
309         if (effective.isEmpty()) {
310             return;
311         }
312
313         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
314         while (iterator.hasNext()) {
315             final StmtContext<?, ?, ?> next = iterator.next();
316             if (statementDef.equals(next.getPublicDefinition())) {
317                 iterator.remove();
318             }
319         }
320
321         shrinkEffective();
322     }
323
324     /**
325      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
326      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
327      * definition and statement argument match with one of the effective substatements' statement definition
328      * and argument.
329      *
330      * <p>
331      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
332      *
333      * @param statementDef statement definition of the statement context to remove
334      * @param statementArg statement argument of the statement context to remove
335      */
336     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
337             final String statementArg) {
338         if (statementArg == null) {
339             removeStatementFromEffectiveSubstatements(statementDef);
340         }
341
342         if (effective.isEmpty()) {
343             return;
344         }
345
346         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
347         while (iterator.hasNext()) {
348             final Mutable<?, ?, ?> next = iterator.next();
349             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
350                 iterator.remove();
351             }
352         }
353
354         shrinkEffective();
355     }
356
357     /**
358      * Adds an effective statement to collection of substatements.
359      *
360      * @param substatement substatement
361      * @throws IllegalStateException
362      *             if added in declared phase
363      * @throws NullPointerException
364      *             if statement parameter is null
365      */
366     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
367         beforeAddEffectiveStatement(1);
368         effective.add(substatement);
369     }
370
371     /**
372      * Adds an effective statement to collection of substatements.
373      *
374      * @param statements substatements
375      * @throws IllegalStateException
376      *             if added in declared phase
377      * @throws NullPointerException
378      *             if statement parameter is null
379      */
380     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
381         if (statements.isEmpty()) {
382             return;
383         }
384
385         statements.forEach(Objects::requireNonNull);
386         beforeAddEffectiveStatement(statements.size());
387         effective.addAll(statements);
388     }
389
390     private void beforeAddEffectiveStatement(final int toAdd) {
391         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
392         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
393                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
394                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
395
396         if (effective.isEmpty()) {
397             effective = new ArrayList<>(toAdd);
398         }
399     }
400
401     /**
402      * Create a new substatement at the specified offset.
403      *
404      * @param offset Substatement offset
405      * @param def definition context
406      * @param ref source reference
407      * @param argument statement argument
408      * @param <X> new substatement argument type
409      * @param <Y> new substatement declared type
410      * @param <Z> new substatement effective type
411      * @return A new substatement
412      */
413     @SuppressWarnings("checkstyle:methodTypeParameterName")
414     public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
415             StatementContextBase<X, Y, Z> createSubstatement(final int offset,
416                     final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
417                     final String argument) {
418         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
419         checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
420                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
421
422         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
423         if (implicitParent.isPresent()) {
424             return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
425                     ref, argument);
426         }
427
428         final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
429         substatements = substatements.put(offset, ret);
430         def.onStatementAdded(ret);
431         return ret;
432     }
433
434     private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
435             final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
436         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
437         return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
438     }
439
440     public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
441         createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
442                 ImplicitSubstatement.of(getStatementSourceReference()), null);
443     }
444
445     /**
446      * Lookup substatement by its offset in this statement.
447      *
448      * @param offset Substatement offset
449      * @return Substatement, or null if substatement does not exist.
450      */
451     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
452         return substatements.get(offset);
453     }
454
455     final void setFullyDefined() {
456         this.fullyDefined = true;
457     }
458
459     final void resizeSubstatements(final int expectedSize) {
460         substatements = substatements.ensureCapacity(expectedSize);
461     }
462
463     final void walkChildren(final ModelProcessingPhase phase) {
464         checkState(fullyDefined);
465         substatements.values().forEach(stmt -> {
466             stmt.walkChildren(phase);
467             stmt.endDeclared(phase);
468         });
469     }
470
471     @Override
472     public D buildDeclared() {
473         checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
474                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
475         if (declaredInstance == null) {
476             declaredInstance = definition().getFactory().createDeclared(this);
477         }
478         return declaredInstance;
479     }
480
481     @Override
482     public E buildEffective() {
483         if (effectiveInstance == null) {
484             effectiveInstance = definition().getFactory().createEffective(this);
485         }
486         return effectiveInstance;
487     }
488
489     /**
490      * tries to execute current {@link ModelProcessingPhase} of source parsing.
491      *
492      * @param phase
493      *            to be executed (completed)
494      * @return if phase was successfully completed
495      * @throws SourceException
496      *             when an error occurred in source parsing
497      */
498     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
499
500         boolean finished = true;
501         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
502         if (!openMutations.isEmpty()) {
503             final Iterator<ContextMutation> it = openMutations.iterator();
504             while (it.hasNext()) {
505                 final ContextMutation current = it.next();
506                 if (current.isFinished()) {
507                     it.remove();
508                 } else {
509                     finished = false;
510                 }
511             }
512
513             if (openMutations.isEmpty()) {
514                 phaseMutation.removeAll(phase);
515                 if (phaseMutation.isEmpty()) {
516                     phaseMutation = ImmutableMultimap.of();
517                 }
518             }
519         }
520
521         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
522             finished &= child.tryToCompletePhase(phase);
523         }
524         for (final Mutable<?, ?, ?> child : effective) {
525             if (child instanceof StatementContextBase) {
526                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
527             }
528         }
529
530         if (finished) {
531             onPhaseCompleted(phase);
532             return true;
533         }
534         return false;
535     }
536
537     /**
538      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
539      *
540      * @param phase
541      *            that was to be completed (finished)
542      * @throws SourceException
543      *             when an error occurred in source parsing
544      */
545     private void onPhaseCompleted(final ModelProcessingPhase phase) {
546         completedPhase = phase;
547
548         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
549         if (listeners.isEmpty()) {
550             return;
551         }
552
553         final Iterator<OnPhaseFinished> listener = listeners.iterator();
554         while (listener.hasNext()) {
555             final OnPhaseFinished next = listener.next();
556             if (next.phaseFinished(this, phase)) {
557                 listener.remove();
558             }
559         }
560
561         if (listeners.isEmpty()) {
562             phaseListeners.removeAll(phase);
563             if (phaseListeners.isEmpty()) {
564                 phaseListeners = ImmutableMultimap.of();
565             }
566         }
567     }
568
569     /**
570      * Ends declared section of current node.
571      */
572     void endDeclared(final ModelProcessingPhase phase) {
573         definition().onDeclarationFinished(this, phase);
574     }
575
576     /**
577      * Return the context in which this statement was defined.
578      *
579      * @return statement definition
580      */
581     protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
582         return definition;
583     }
584
585     @Override
586     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
587         definition().checkNamespaceAllowed(type);
588     }
589
590     @Override
591     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
592             final V value) {
593         // definition().onNamespaceElementAdded(this, type, key, value);
594     }
595
596     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
597             final OnNamespaceItemAdded listener) {
598         final Object potential = getFromNamespace(type, key);
599         if (potential != null) {
600             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
601             listener.namespaceItemAdded(this, type, key, potential);
602             return;
603         }
604
605         getBehaviour(type).addListener(new KeyedValueAddedListener<K>(this, key) {
606             @Override
607             void onValueAdded(final Object value) {
608                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
609             }
610         });
611     }
612
613     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
614             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
615             final OnNamespaceItemAdded listener) {
616         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
617         if (existing.isPresent()) {
618             final Entry<K, V> entry = existing.get();
619             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
620             waitForPhase(entry.getValue(), type, phase, criterion, listener);
621             return;
622         }
623
624         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
625         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
626             @Override
627             boolean onValueAdded(final K key, final V value) {
628                 if (criterion.match(key)) {
629                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
630                     waitForPhase(value, type, phase, criterion, listener);
631                     return true;
632                 }
633
634                 return false;
635             }
636         });
637     }
638
639     final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
640             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
641         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
642         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
643             type, this);
644         final Entry<K, V> match = optMatch.get();
645         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
646     }
647
648     final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
649             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
650             final OnNamespaceItemAdded listener) {
651         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
652             (context, phaseCompleted) -> {
653                 selectMatch(type, criterion, listener);
654                 return true;
655             });
656     }
657
658     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
659             final Class<N> type) {
660         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
661         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
662             type);
663
664         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
665     }
666
667     /**
668      * See {@link StatementSupport#getPublicView()}.
669      */
670     @Override
671     public StatementDefinition getPublicDefinition() {
672         return definition().getPublicView();
673     }
674
675     @Override
676     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
677         return getRoot().getSourceContext().newInferenceAction(phase);
678     }
679
680     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
681         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
682     }
683
684     /**
685      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
686      * the listener is notified immediately.
687      *
688      * @param phase requested completion phase
689      * @param listener listener to invoke
690      * @throws NullPointerException if any of the arguments is null
691      */
692     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
693         checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
694         checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
695
696         ModelProcessingPhase finishedPhase = completedPhase;
697         while (finishedPhase != null) {
698             if (phase.equals(finishedPhase)) {
699                 listener.phaseFinished(this, finishedPhase);
700                 return;
701             }
702             finishedPhase = finishedPhase.getPreviousPhase();
703         }
704         if (phaseListeners.isEmpty()) {
705             phaseListeners = newMultimap();
706         }
707
708         phaseListeners.put(phase, listener);
709     }
710
711     /**
712      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
713      *
714      * @throws IllegalStateException
715      *             when the mutation was registered after phase was completed
716      */
717     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
718         ModelProcessingPhase finishedPhase = completedPhase;
719         while (finishedPhase != null) {
720             checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
721                 getStatementSourceReference());
722             finishedPhase = finishedPhase.getPreviousPhase();
723         }
724
725         if (phaseMutation.isEmpty()) {
726             phaseMutation = newMultimap();
727         }
728         phaseMutation.put(phase, mutation);
729     }
730
731     @Override
732     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
733             final KT key,final StmtContext<?, ?, ?> stmt) {
734         addContextToNamespace(namespace, key, stmt);
735     }
736
737     @Override
738     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
739             final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
740         checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
741                 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
742
743         checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
744
745         final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
746         final SubstatementContext<X, Y, Z> copy = new SubstatementContext<>(original, this, type, targetModule);
747
748         original.definition().onStatementAdded(copy);
749         original.copyTo(copy, type, targetModule);
750
751         return copy;
752     }
753
754
755     @Override
756     public @NonNull StatementDefinition getDefinition() {
757         return getPublicDefinition();
758     }
759
760     @Override
761     public @NonNull StatementSourceReference getSourceReference() {
762         return getStatementSourceReference();
763     }
764
765     @Override
766     public boolean isFullyDefined() {
767         return fullyDefined;
768     }
769
770     final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
771             @Nullable final QNameModule targetModule) {
772         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
773
774         for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
775             if (stmtContext.isSupportedByFeatures()) {
776                 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
777             }
778         }
779
780         for (final Mutable<?, ?, ?> stmtContext : effective) {
781             copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
782         }
783
784         target.addEffectiveSubstatements(buffer);
785     }
786
787     private void copySubstatement(final Mutable<?, ?, ?> stmtContext,  final Mutable<?, ?, ?> target,
788             final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
789         if (needToCopyByUses(stmtContext)) {
790             final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
791             LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
792             buffer.add(copy);
793         } else if (isReusedByUses(stmtContext)) {
794             LOG.debug("Reusing substatement {} for {}", stmtContext, this);
795             buffer.add(stmtContext);
796         } else {
797             LOG.debug("Skipping statement {}", stmtContext);
798         }
799     }
800
801     // FIXME: revise this, as it seems to be wrong
802     private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
803         YangStmtMapping.DESCRIPTION,
804         YangStmtMapping.REFERENCE,
805         YangStmtMapping.STATUS);
806     private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
807         YangStmtMapping.TYPE,
808         YangStmtMapping.TYPEDEF,
809         YangStmtMapping.USES);
810
811     private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
812         final StatementDefinition def = stmtContext.getPublicDefinition();
813         if (REUSED_DEF_SET.contains(def)) {
814             LOG.debug("Will reuse {} statement {}", def, stmtContext);
815             return false;
816         }
817         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
818             return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
819         }
820
821         LOG.debug("Will copy {} statement {}", def, stmtContext);
822         return true;
823     }
824
825     private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
826         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
827     }
828
829     @Override
830     public final String toString() {
831         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
832     }
833
834     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
835         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
836     }
837 }