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