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