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