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