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