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