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