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