f70283c0f7baeec8f0779784a4c6b4911854a610
[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 com.google.common.base.Verify.verify;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import com.google.common.collect.ImmutableCollection;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMultimap;
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;
32 import java.util.Map.Entry;
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.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.common.YangVersion;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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.model.api.stmt.AugmentStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
51 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
52 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
69 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
70 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
72 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
73 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
74 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
75 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
76 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79
80 /**
81  * Core reactor statement implementation of {@link Mutable}.
82  *
83  * @param <A> Argument type
84  * @param <D> Declared Statement representation
85  * @param <E> Effective Statement representation
86  */
87 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
88         extends NamespaceStorageSupport implements Mutable<A, D, E> {
89     /**
90      * Event listener when an item is added to model namespace.
91      */
92     interface OnNamespaceItemAdded extends EventListener {
93         /**
94          * Invoked whenever a new item is added to a namespace.
95          */
96         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
97     }
98
99     /**
100      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
101      */
102     interface OnPhaseFinished extends EventListener {
103         /**
104          * Invoked whenever a processing phase has finished.
105          */
106         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
107     }
108
109     /**
110      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
111      */
112     interface ContextMutation {
113
114         boolean isFinished();
115     }
116
117     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
118
119     // Flag bit assignments
120     private static final int IS_SUPPORTED_BY_FEATURES    = 0x01;
121     private static final int HAVE_SUPPORTED_BY_FEATURES  = 0x02;
122     private static final int IS_IGNORE_IF_FEATURE        = 0x04;
123     private static final int HAVE_IGNORE_IF_FEATURE      = 0x08;
124     // Note: these four are related
125     private static final int IS_IGNORE_CONFIG            = 0x10;
126     private static final int HAVE_IGNORE_CONFIG          = 0x20;
127     private static final int IS_CONFIGURATION            = 0x40;
128     private static final int HAVE_CONFIGURATION          = 0x80;
129
130     // Have-and-set flag constants, also used as masks
131     private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
132     private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
133     // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
134     private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
135     private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
136
137     private final CopyHistory copyHistory;
138     // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
139     //       operations, hence we want to keep it close by.
140     private final @NonNull StatementDefinitionContext<A, D, E> definition;
141
142     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
143     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
144     private List<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
145     private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
146
147     private @Nullable ModelProcessingPhase completedPhase;
148     private @Nullable E effectiveInstance;
149
150     // Master flag controlling whether this context can yield an effective statement
151     // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
152     //        of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
153     private boolean isSupportedToBuildEffective = true;
154
155     // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
156     private boolean fullyDefined;
157
158     // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
159     // hence improve memory layout.
160     private byte flags;
161
162     // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
163     // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
164     private volatile SchemaPath schemaPath;
165
166     // Copy constructor used by subclasses to implement reparent()
167     StatementContextBase(final StatementContextBase<A, D, E> original) {
168         this.copyHistory = original.copyHistory;
169         this.definition = original.definition;
170
171         this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
172         this.fullyDefined = original.fullyDefined;
173         this.completedPhase = original.completedPhase;
174         this.flags = original.flags;
175     }
176
177     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
178         this.definition = requireNonNull(def);
179         this.copyHistory = CopyHistory.original();
180     }
181
182     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
183         this.definition = requireNonNull(def);
184         this.copyHistory = requireNonNull(copyHistory);
185     }
186
187     @Override
188     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
189         return effectOfStatement;
190     }
191
192     @Override
193     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
194         if (effectOfStatement.isEmpty()) {
195             effectOfStatement = new ArrayList<>(1);
196         }
197         effectOfStatement.add(ctx);
198     }
199
200     @Override
201     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
202         if (ctxs.isEmpty()) {
203             return;
204         }
205
206         if (effectOfStatement.isEmpty()) {
207             effectOfStatement = new ArrayList<>(ctxs.size());
208         }
209         effectOfStatement.addAll(ctxs);
210     }
211
212     @Override
213     public boolean isSupportedByFeatures() {
214         final int fl = flags & SET_SUPPORTED_BY_FEATURES;
215         if (fl != 0) {
216             return fl == SET_SUPPORTED_BY_FEATURES;
217         }
218         if (isIgnoringIfFeatures()) {
219             flags |= SET_SUPPORTED_BY_FEATURES;
220             return true;
221         }
222
223         /*
224          * If parent is supported, we need to check if-features statements of this context.
225          */
226         if (isParentSupportedByFeatures()) {
227             // If the set of supported features has not been provided, all features are supported by default.
228             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
229                     SupportedFeatures.SUPPORTED_FEATURES);
230             if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
231                 flags |= SET_SUPPORTED_BY_FEATURES;
232                 return true;
233             }
234         }
235
236         // Either parent is not supported or this statement is not supported
237         flags |= HAVE_SUPPORTED_BY_FEATURES;
238         return false;
239     }
240
241     protected abstract boolean isParentSupportedByFeatures();
242
243     @Override
244     public boolean isSupportedToBuildEffective() {
245         return isSupportedToBuildEffective;
246     }
247
248     @Override
249     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
250         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
251     }
252
253     @Override
254     public CopyHistory getCopyHistory() {
255         return copyHistory;
256     }
257
258     @Override
259     public ModelProcessingPhase getCompletedPhase() {
260         return completedPhase;
261     }
262
263     @Override
264     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
265         this.completedPhase = completedPhase;
266     }
267
268     @Override
269     public abstract StatementContextBase<?, ?, ?> getParentContext();
270
271     /**
272      * Returns the model root for this statement.
273      *
274      * @return root context of statement
275      */
276     @Override
277     public abstract RootStatementContext<?, ?, ?> getRoot();
278
279     @Override
280     public final @NonNull Registry getBehaviourRegistry() {
281         return getRoot().getBehaviourRegistryImpl();
282     }
283
284     @Override
285     public final YangVersion getRootVersion() {
286         return getRoot().getRootVersionImpl();
287     }
288
289     @Override
290     public final void setRootVersion(final YangVersion version) {
291         getRoot().setRootVersionImpl(version);
292     }
293
294     @Override
295     public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
296         getRoot().addMutableStmtToSealImpl(mutableStatement);
297     }
298
299     @Override
300     public final void addRequiredSource(final SourceIdentifier dependency) {
301         getRoot().addRequiredSourceImpl(dependency);
302     }
303
304     @Override
305     public final void setRootIdentifier(final SourceIdentifier identifier) {
306         getRoot().setRootIdentifierImpl(identifier);
307     }
308
309     @Override
310     public final boolean isEnabledSemanticVersioning() {
311         return getRoot().isEnabledSemanticVersioningImpl();
312     }
313
314     @Override
315     public StatementSource getStatementSource() {
316         return getStatementSourceReference().getStatementSource();
317     }
318
319     @Override
320     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
321             final Class<N> type) {
322         return getLocalNamespace(type);
323     }
324
325     @Override
326     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
327         return getNamespace(type);
328     }
329
330     /**
331      * Associate a value with a key within a namespace.
332      *
333      * @param type Namespace type
334      * @param key Key
335      * @param value value
336      * @param <K> namespace key type
337      * @param <V> namespace value type
338      * @param <N> namespace type
339      * @param <T> key type
340      * @param <U> value type
341      * @throws NamespaceNotAvailableException when the namespace is not available.
342      */
343     @Override
344     public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
345             final Class<N> type, final T key, final U value) {
346         addToNamespace(type, key, value);
347     }
348
349     @Override
350     public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
351
352     /**
353      * Return a value associated with specified key within a namespace.
354      *
355      * @param type Namespace type
356      * @param key Key
357      * @param <K> namespace key type
358      * @param <V> namespace value type
359      * @param <N> namespace type
360      * @param <T> key type
361      * @return Value, or null if there is no element
362      * @throws NamespaceNotAvailableException when the namespace is not available.
363      */
364     @Override
365     public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(final Class<N> type,
366             final T key) {
367         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
368     }
369
370     @Override
371     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
372         if (effective instanceof ImmutableCollection) {
373             return effective;
374         }
375
376         return Collections.unmodifiableCollection(effective);
377     }
378
379     /**
380      * Remove a set of statements from effective statements.
381      *
382      * @param statements statements to be removed
383      * @deprecated This method was used by EffectiveStatementBase to restore proper order of effects of uses statements.
384      *             It is no longer used in that capacity and slated for removal.
385      */
386     // FIXME: 5.0.0: remove this method
387     @Deprecated(forRemoval = true)
388     public void removeStatementsFromEffectiveSubstatements(
389             final Collection<? extends StmtContext<?, ?, ?>> statements) {
390         if (!effective.isEmpty()) {
391             effective.removeAll(statements);
392             shrinkEffective();
393         }
394     }
395
396     private void shrinkEffective() {
397         if (effective.isEmpty()) {
398             effective = ImmutableList.of();
399         }
400     }
401
402     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
403         if (effective.isEmpty()) {
404             return;
405         }
406
407         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
408         while (iterator.hasNext()) {
409             final StmtContext<?, ?, ?> next = iterator.next();
410             if (statementDef.equals(next.getPublicDefinition())) {
411                 iterator.remove();
412             }
413         }
414
415         shrinkEffective();
416     }
417
418     /**
419      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
420      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
421      * definition and statement argument match with one of the effective substatements' statement definition
422      * and argument.
423      *
424      * <p>
425      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
426      *
427      * @param statementDef statement definition of the statement context to remove
428      * @param statementArg statement argument of the statement context to remove
429      */
430     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
431             final String statementArg) {
432         if (statementArg == null) {
433             removeStatementFromEffectiveSubstatements(statementDef);
434         }
435
436         if (effective.isEmpty()) {
437             return;
438         }
439
440         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
441         while (iterator.hasNext()) {
442             final Mutable<?, ?, ?> next = iterator.next();
443             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
444                 iterator.remove();
445             }
446         }
447
448         shrinkEffective();
449     }
450
451     // YANG example: RPC/action statements always have 'input' and 'output' defined
452     @Beta
453     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
454             appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
455         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
456         //                       StatementContextBase subclass.
457         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
458                 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
459         support.onStatementAdded(ret);
460         addEffectiveSubstatement(ret);
461         return ret;
462     }
463
464     /**
465      * Adds an effective statement to collection of substatements.
466      *
467      * @param substatement substatement
468      * @throws IllegalStateException
469      *             if added in declared phase
470      * @throws NullPointerException
471      *             if statement parameter is null
472      */
473     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
474         verifyStatement(substatement);
475         beforeAddEffectiveStatement(1);
476
477         final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
478         final ModelProcessingPhase phase = completedPhase;
479         if (phase != null) {
480             ensureCompletedPhase(stmt, phase);
481         }
482         effective.add(stmt);
483     }
484
485     /**
486      * Adds an effective statement to collection of substatements.
487      *
488      * @param statements substatements
489      * @throws IllegalStateException
490      *             if added in declared phase
491      * @throws NullPointerException
492      *             if statement parameter is null
493      */
494     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
495         if (!statements.isEmpty()) {
496             statements.forEach(StatementContextBase::verifyStatement);
497             beforeAddEffectiveStatement(statements.size());
498
499             final Collection<? extends StatementContextBase<?, ?, ?>> casted =
500                     (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
501             final ModelProcessingPhase phase = completedPhase;
502             if (phase != null) {
503                 for (StatementContextBase<?, ?, ?> stmt : casted) {
504                     ensureCompletedPhase(stmt, phase);
505                 }
506             }
507
508             effective.addAll(casted);
509         }
510     }
511
512     // Make sure target statement has transitioned at least to specified phase. This method is just before we take
513     // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
514     // any statements which did not complete the same phase as the root statement.
515     private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
516             final ModelProcessingPhase phase) {
517         verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
518     }
519
520     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
521         verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
522     }
523
524     private void beforeAddEffectiveStatement(final int toAdd) {
525         // We cannot allow statement to be further mutated
526         final StatementSourceReference ref = getStatementSourceReference();
527         verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s", ref);
528
529         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
530         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
531                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
532                 "Effective statement cannot be added in declared phase at: %s", ref);
533
534         if (effective.isEmpty()) {
535             effective = new ArrayList<>(toAdd);
536         }
537     }
538
539     // Exists only due to memory optimization
540     final boolean fullyDefined() {
541         return fullyDefined;
542     }
543
544     // Exists only due to memory optimization, should live in AbstractResumedStatement
545     final void setFullyDefined() {
546         fullyDefined = true;
547     }
548
549     @Override
550     public E buildEffective() {
551         final E existing;
552         return (existing = effectiveInstance) != null ? existing : loadEffective();
553     }
554
555     private E loadEffective() {
556         return effectiveInstance = definition.getFactory().createEffective(this);
557     }
558
559     /**
560      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
561      * this method does nothing.
562      *
563      * @param phase to be executed (completed)
564      * @return true if phase was successfully completed
565      * @throws SourceException when an error occurred in source parsing
566      */
567     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
568         return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
569     }
570
571     private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
572         final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
573         if (completeChildren(phase) && finished) {
574             onPhaseCompleted(phase);
575             return true;
576         }
577         return false;
578     }
579
580     private boolean completeChildren(final ModelProcessingPhase phase) {
581         boolean finished = true;
582         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
583             finished &= child.tryToCompletePhase(phase);
584         }
585         for (final StatementContextBase<?, ?, ?> child : effective) {
586             finished &= child.tryToCompletePhase(phase);
587         }
588         return finished;
589     }
590
591     private boolean runMutations(final ModelProcessingPhase phase) {
592         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
593         return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
594     }
595
596     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
597         boolean finished = true;
598         final Iterator<ContextMutation> it = openMutations.iterator();
599         while (it.hasNext()) {
600             final ContextMutation current = it.next();
601             if (current.isFinished()) {
602                 it.remove();
603             } else {
604                 finished = false;
605             }
606         }
607
608         if (openMutations.isEmpty()) {
609             phaseMutation.removeAll(phase);
610             if (phaseMutation.isEmpty()) {
611                 phaseMutation = ImmutableMultimap.of();
612             }
613         }
614         return finished;
615     }
616
617     /**
618      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
619      *
620      * @param phase
621      *            that was to be completed (finished)
622      * @throws SourceException
623      *             when an error occurred in source parsing
624      */
625     private void onPhaseCompleted(final ModelProcessingPhase phase) {
626         completedPhase = phase;
627
628         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
629         if (!listeners.isEmpty()) {
630             runPhaseListeners(phase, listeners);
631         }
632     }
633
634     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
635         final Iterator<OnPhaseFinished> listener = listeners.iterator();
636         while (listener.hasNext()) {
637             final OnPhaseFinished next = listener.next();
638             if (next.phaseFinished(this, phase)) {
639                 listener.remove();
640             }
641         }
642
643         if (listeners.isEmpty()) {
644             phaseListeners.removeAll(phase);
645             if (phaseListeners.isEmpty()) {
646                 phaseListeners = ImmutableMultimap.of();
647             }
648         }
649     }
650
651     /**
652      * Ends declared section of current node.
653      */
654     void endDeclared(final ModelProcessingPhase phase) {
655         definition.onDeclarationFinished(this, phase);
656     }
657
658     /**
659      * Return the context in which this statement was defined.
660      *
661      * @return statement definition
662      */
663     protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
664         return definition;
665     }
666
667     @Override
668     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
669         definition.checkNamespaceAllowed(type);
670     }
671
672     @Override
673     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
674             final V value) {
675         // definition().onNamespaceElementAdded(this, type, key, value);
676     }
677
678     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
679             final OnNamespaceItemAdded listener) {
680         final Object potential = getFromNamespace(type, key);
681         if (potential != null) {
682             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
683             listener.namespaceItemAdded(this, type, key, potential);
684             return;
685         }
686
687         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
688             @Override
689             void onValueAdded(final Object value) {
690                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
691             }
692         });
693     }
694
695     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
696             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
697             final OnNamespaceItemAdded listener) {
698         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
699         if (existing.isPresent()) {
700             final Entry<K, V> entry = existing.get();
701             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
702             waitForPhase(entry.getValue(), type, phase, criterion, listener);
703             return;
704         }
705
706         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
707         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
708             @Override
709             boolean onValueAdded(final K key, final V value) {
710                 if (criterion.match(key)) {
711                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
712                     waitForPhase(value, type, phase, criterion, listener);
713                     return true;
714                 }
715
716                 return false;
717             }
718         });
719     }
720
721     final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
722             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
723         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
724         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
725             type, this);
726         final Entry<K, V> match = optMatch.get();
727         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
728     }
729
730     final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
731             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
732             final OnNamespaceItemAdded listener) {
733         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
734             (context, phaseCompleted) -> {
735                 selectMatch(type, criterion, listener);
736                 return true;
737             });
738     }
739
740     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
741             final Class<N> type) {
742         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
743         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
744             type);
745
746         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
747     }
748
749     @Override
750     public StatementDefinition getPublicDefinition() {
751         return definition.getPublicView();
752     }
753
754     @Override
755     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
756         return getRoot().getSourceContext().newInferenceAction(phase);
757     }
758
759     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
760         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
761     }
762
763     /**
764      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
765      * the listener is notified immediately.
766      *
767      * @param phase requested completion phase
768      * @param listener listener to invoke
769      * @throws NullPointerException if any of the arguments is null
770      */
771     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
772         checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
773         checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
774
775         ModelProcessingPhase finishedPhase = completedPhase;
776         while (finishedPhase != null) {
777             if (phase.equals(finishedPhase)) {
778                 listener.phaseFinished(this, finishedPhase);
779                 return;
780             }
781             finishedPhase = finishedPhase.getPreviousPhase();
782         }
783         if (phaseListeners.isEmpty()) {
784             phaseListeners = newMultimap();
785         }
786
787         phaseListeners.put(phase, listener);
788     }
789
790     /**
791      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
792      *
793      * @throws IllegalStateException
794      *             when the mutation was registered after phase was completed
795      */
796     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
797         ModelProcessingPhase finishedPhase = completedPhase;
798         while (finishedPhase != null) {
799             checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
800                 getStatementSourceReference());
801             finishedPhase = finishedPhase.getPreviousPhase();
802         }
803
804         if (phaseMutation.isEmpty()) {
805             phaseMutation = newMultimap();
806         }
807         phaseMutation.put(phase, mutation);
808     }
809
810     @Override
811     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
812             final KT key,final StmtContext<?, ?, ?> stmt) {
813         addContextToNamespace(namespace, key, stmt);
814     }
815
816     @Override
817     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
818             final QNameModule targetModule) {
819         checkEffectiveModelCompleted(this);
820
821         final StatementSupport<A, D, E> support = definition.support();
822         final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
823         switch (policy) {
824             case CONTEXT_INDEPENDENT:
825                 if (hasEmptySubstatements()) {
826                     // This statement is context-independent and has no substatements -- hence it can be freely shared.
827                     return Optional.of(this);
828                 }
829                 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
830                 // fall through
831             case DECLARED_COPY:
832                 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
833                 //                       context, so that we can support building an effective statement without copying
834                 //                       anything -- we will typically end up not being inferred against. In that case,
835                 //                       this slim context should end up dealing with differences at buildContext()
836                 //                       time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
837                 //                       cannot be shared across instances).
838                 return Optional.of(parent.childCopyOf(this, type, targetModule));
839             case IGNORE:
840                 return Optional.empty();
841             case REJECT:
842                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
843             default:
844                 throw new IllegalStateException("Unhandled policy " + policy);
845         }
846     }
847
848     @Override
849     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
850             final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
851         checkEffectiveModelCompleted(stmt);
852         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
853         return childCopyOf((StatementContextBase<X, Y, Z>)stmt, type, targetModule);
854     }
855
856     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
857             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
858         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
859             original.getPublicDefinition());
860
861         final StatementContextBase<X, Y, Z> result;
862         final InferredStatementContext<X, Y, Z> copy;
863
864         if (implicitParent.isPresent()) {
865             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
866             result = new SubstatementContext(this, def, original.getStatementSourceReference(),
867                 original.rawStatementArgument(), original.getStatementArgument(), type);
868
869             final CopyType childCopyType;
870             switch (type) {
871                 case ADDED_BY_AUGMENTATION:
872                     childCopyType = CopyType.ORIGINAL;
873                     break;
874                 case ADDED_BY_USES_AUGMENTATION:
875                     childCopyType = CopyType.ADDED_BY_USES;
876                     break;
877                 case ADDED_BY_USES:
878                 case ORIGINAL:
879                 default:
880                     childCopyType = type;
881             }
882
883             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
884             result.addEffectiveSubstatement(copy);
885         } else {
886             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
887         }
888
889         original.definition.onStatementAdded(copy);
890         return result;
891     }
892
893     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
894         final ModelProcessingPhase phase = stmt.getCompletedPhase();
895         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
896                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
897     }
898
899     @Beta
900     public final boolean hasImplicitParentSupport() {
901         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
902     }
903
904     @Beta
905     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
906         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
907             original.getPublicDefinition());
908         if (optImplicit.isEmpty()) {
909             return original;
910         }
911
912         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
913         final CopyType type = original.getCopyHistory().getLastOperation();
914         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
915             original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
916             type);
917
918         result.addEffectiveSubstatement(original.reparent(result));
919         result.setCompletedPhase(original.getCompletedPhase());
920         return result;
921     }
922
923     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
924
925     /**
926      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
927      *
928      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
929      */
930     abstract boolean hasEmptySubstatements();
931
932     final boolean hasEmptyEffectiveSubstatements() {
933         return effective.isEmpty();
934     }
935
936     /**
937      * Config statements are not all that common which means we are performing a recursive search towards the root
938      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
939      * for the (usually non-existent) config statement.
940      *
941      * <p>
942      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
943      * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
944      *
945      * <p>
946      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
947      *       {@link #isIgnoringConfig(StatementContextBase)}.
948      */
949     final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
950         final int fl = flags & SET_CONFIGURATION;
951         if (fl != 0) {
952             return fl == SET_CONFIGURATION;
953         }
954         if (isIgnoringConfig(parent)) {
955             // Note: SET_CONFIGURATION has been stored in flags
956             return true;
957         }
958
959         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
960             ConfigStatement.class);
961         final boolean isConfig;
962         if (configStatement != null) {
963             isConfig = configStatement.coerceStatementArgument();
964             if (isConfig) {
965                 // Validity check: if parent is config=false this cannot be a config=true
966                 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
967                         "Parent node has config=false, this node must not be specifed as config=true");
968             }
969         } else {
970             // If "config" statement is not specified, the default is the same as the parent's "config" value.
971             isConfig = parent.isConfiguration();
972         }
973
974         // Resolved, make sure we cache this return
975         flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
976         return isConfig;
977     }
978
979     protected abstract boolean isIgnoringConfig();
980
981     /**
982      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
983      * keep on returning the same result without performing any lookups. Exists only to support
984      * {@link SubstatementContext#isIgnoringConfig()}.
985      *
986      * <p>
987      * Note: use of this method implies that {@link #isConfiguration()} is realized with
988      *       {@link #isConfiguration(StatementContextBase)}.
989      */
990     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
991         final int fl = flags & SET_IGNORE_CONFIG;
992         if (fl != 0) {
993             return fl == SET_IGNORE_CONFIG;
994         }
995         if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
996             flags |= SET_IGNORE_CONFIG;
997             return true;
998         }
999
1000         flags |= HAVE_IGNORE_CONFIG;
1001         return false;
1002     }
1003
1004     protected abstract boolean isIgnoringIfFeatures();
1005
1006     /**
1007      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
1008      * keep on returning the same result without performing any lookups. Exists only to support
1009      * {@link SubstatementContext#isIgnoringIfFeatures()}.
1010      */
1011     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
1012         final int fl = flags & SET_IGNORE_IF_FEATURE;
1013         if (fl != 0) {
1014             return fl == SET_IGNORE_IF_FEATURE;
1015         }
1016         if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1017             flags |= SET_IGNORE_IF_FEATURE;
1018             return true;
1019         }
1020
1021         flags |= HAVE_IGNORE_IF_FEATURE;
1022         return false;
1023     }
1024
1025     // Exists only to support SubstatementContext/InferredStatementContext
1026     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1027         SchemaPath local = schemaPath;
1028         if (local == null) {
1029             synchronized (this) {
1030                 local = schemaPath;
1031                 if (local == null) {
1032                     local = createSchemaPath(coerceParentContext());
1033                     schemaPath = local;
1034                 }
1035             }
1036         }
1037
1038         return Optional.ofNullable(local);
1039     }
1040
1041     private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
1042         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
1043         verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1044         final SchemaPath parentPath = maybeParentPath.get();
1045
1046         if (StmtContextUtils.isUnknownStatement(this)) {
1047             return parentPath.createChild(getPublicDefinition().getStatementName());
1048         }
1049         final Object argument = getStatementArgument();
1050         if (argument instanceof QName) {
1051             final QName qname = (QName) argument;
1052             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
1053                 return maybeParentPath.orElse(null);
1054             }
1055
1056             return parentPath.createChild(qname);
1057         }
1058         if (argument instanceof String) {
1059             // FIXME: This may yield illegal argument exceptions
1060             final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
1061             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1062             return parentPath.createChild(qname);
1063         }
1064         if (argument instanceof SchemaNodeIdentifier
1065                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
1066                         || StmtContextUtils.producesDeclared(this, RefineStatement.class)
1067                         || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
1068
1069             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
1070         }
1071
1072         // FIXME: this does not look right
1073         return maybeParentPath.orElse(null);
1074     }
1075
1076     @Override
1077     public final String toString() {
1078         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1079     }
1080
1081     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1082         return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());
1083     }
1084 }