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