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