Defer copy decisions to StatementSupport
[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.Objects;
34 import java.util.Optional;
35 import java.util.Set;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.common.YangVersion;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
43 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
45 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
46 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
47 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
51 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
52 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
53 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.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     private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
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     @Override
263     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
264         this.completedPhase = completedPhase;
265     }
266
267     @Override
268     public abstract StatementContextBase<?, ?, ?> getParentContext();
269
270     /**
271      * Returns the model root for this statement.
272      *
273      * @return root context of statement
274      */
275     @Override
276     public abstract RootStatementContext<?, ?, ?> getRoot();
277
278     @Override
279     public final @NonNull Registry getBehaviourRegistry() {
280         return getRoot().getBehaviourRegistryImpl();
281     }
282
283     @Override
284     public final YangVersion getRootVersion() {
285         return getRoot().getRootVersionImpl();
286     }
287
288     @Override
289     public final void setRootVersion(final YangVersion version) {
290         getRoot().setRootVersionImpl(version);
291     }
292
293     @Override
294     public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
295         getRoot().addMutableStmtToSealImpl(mutableStatement);
296     }
297
298     @Override
299     public final void addRequiredSource(final SourceIdentifier dependency) {
300         getRoot().addRequiredSourceImpl(dependency);
301     }
302
303     @Override
304     public final void setRootIdentifier(final SourceIdentifier identifier) {
305         getRoot().setRootIdentifierImpl(identifier);
306     }
307
308     @Override
309     public final boolean isEnabledSemanticVersioning() {
310         return getRoot().isEnabledSemanticVersioningImpl();
311     }
312
313     @Override
314     public StatementSource getStatementSource() {
315         return getStatementSourceReference().getStatementSource();
316     }
317
318     @Override
319     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
320             final Class<N> type) {
321         return getLocalNamespace(type);
322     }
323
324     @Override
325     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
326         return getNamespace(type);
327     }
328
329     /**
330      * Associate a value with a key within a namespace.
331      *
332      * @param type Namespace type
333      * @param key Key
334      * @param value value
335      * @param <K> namespace key type
336      * @param <V> namespace value type
337      * @param <N> namespace type
338      * @param <T> key type
339      * @param <U> value type
340      * @throws NamespaceNotAvailableException when the namespace is not available.
341      */
342     @Override
343     public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
344             final Class<N> type, final T key, final U value) {
345         addToNamespace(type, key, value);
346     }
347
348     @Override
349     public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
350
351     /**
352      * Return a value associated with specified key within a namespace.
353      *
354      * @param type Namespace type
355      * @param key Key
356      * @param <K> namespace key type
357      * @param <V> namespace value type
358      * @param <N> namespace type
359      * @param <T> key type
360      * @return Value, or null if there is no element
361      * @throws NamespaceNotAvailableException when the namespace is not available.
362      */
363     @Override
364     public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(final Class<N> type,
365             final T key) {
366         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
367     }
368
369     @Override
370     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
371         if (effective instanceof ImmutableCollection) {
372             return effective;
373         }
374
375         return Collections.unmodifiableCollection(effective);
376     }
377
378     private void shrinkEffective() {
379         if (effective.isEmpty()) {
380             effective = ImmutableList.of();
381         }
382     }
383
384     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
385         if (effective.isEmpty()) {
386             return;
387         }
388
389         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
390         while (iterator.hasNext()) {
391             final StmtContext<?, ?, ?> next = iterator.next();
392             if (statementDef.equals(next.getPublicDefinition())) {
393                 iterator.remove();
394             }
395         }
396
397         shrinkEffective();
398     }
399
400     /**
401      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
402      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
403      * definition and statement argument match with one of the effective substatements' statement definition
404      * and argument.
405      *
406      * <p>
407      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
408      *
409      * @param statementDef statement definition of the statement context to remove
410      * @param statementArg statement argument of the statement context to remove
411      */
412     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
413             final String statementArg) {
414         if (statementArg == null) {
415             removeStatementFromEffectiveSubstatements(statementDef);
416         }
417
418         if (effective.isEmpty()) {
419             return;
420         }
421
422         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
423         while (iterator.hasNext()) {
424             final Mutable<?, ?, ?> next = iterator.next();
425             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
426                 iterator.remove();
427             }
428         }
429
430         shrinkEffective();
431     }
432
433     // YANG example: RPC/action statements always have 'input' and 'output' defined
434     @Beta
435     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
436             appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
437         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
438         //                       StatementContextBase subclass.
439         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
440                 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
441         support.onStatementAdded(ret);
442         addEffectiveSubstatement(ret);
443         return ret;
444     }
445
446     /**
447      * Adds an effective statement to collection of substatements.
448      *
449      * @param substatement substatement
450      * @throws IllegalStateException
451      *             if added in declared phase
452      * @throws NullPointerException
453      *             if statement parameter is null
454      */
455     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
456         beforeAddEffectiveStatement(1);
457         effective.add(substatement);
458     }
459
460     /**
461      * Adds an effective statement to collection of substatements.
462      *
463      * @param statements substatements
464      * @throws IllegalStateException
465      *             if added in declared phase
466      * @throws NullPointerException
467      *             if statement parameter is null
468      */
469     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
470         if (statements.isEmpty()) {
471             return;
472         }
473
474         statements.forEach(Objects::requireNonNull);
475         beforeAddEffectiveStatement(statements.size());
476         effective.addAll(statements);
477     }
478
479     private void beforeAddEffectiveStatement(final int toAdd) {
480         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
481         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
482                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
483                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
484
485         if (effective.isEmpty()) {
486             effective = new ArrayList<>(toAdd);
487         }
488     }
489
490     // Exists only due to memory optimization
491     final boolean fullyDefined() {
492         return fullyDefined;
493     }
494
495     // Exists only due to memory optimization, should live in AbstractResumedStatement
496     final void setFullyDefined() {
497         fullyDefined = true;
498     }
499
500     @Override
501     public E buildEffective() {
502         final E existing = effectiveInstance;
503         return existing != null ? existing : (effectiveInstance = definition.getFactory().createEffective(this));
504     }
505
506     /**
507      * tries to execute current {@link ModelProcessingPhase} of source parsing.
508      *
509      * @param phase
510      *            to be executed (completed)
511      * @return if phase was successfully completed
512      * @throws SourceException
513      *             when an error occurred in source parsing
514      */
515     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
516
517         boolean finished = true;
518         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
519         if (!openMutations.isEmpty()) {
520             final Iterator<ContextMutation> it = openMutations.iterator();
521             while (it.hasNext()) {
522                 final ContextMutation current = it.next();
523                 if (current.isFinished()) {
524                     it.remove();
525                 } else {
526                     finished = false;
527                 }
528             }
529
530             if (openMutations.isEmpty()) {
531                 phaseMutation.removeAll(phase);
532                 if (phaseMutation.isEmpty()) {
533                     phaseMutation = ImmutableMultimap.of();
534                 }
535             }
536         }
537
538         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
539             finished &= child.tryToCompletePhase(phase);
540         }
541         for (final Mutable<?, ?, ?> child : effective) {
542             if (child instanceof StatementContextBase) {
543                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
544             }
545         }
546
547         if (finished) {
548             onPhaseCompleted(phase);
549             return true;
550         }
551         return false;
552     }
553
554     /**
555      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
556      *
557      * @param phase
558      *            that was to be completed (finished)
559      * @throws SourceException
560      *             when an error occurred in source parsing
561      */
562     private void onPhaseCompleted(final ModelProcessingPhase phase) {
563         completedPhase = phase;
564
565         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
566         if (listeners.isEmpty()) {
567             return;
568         }
569
570         final Iterator<OnPhaseFinished> listener = listeners.iterator();
571         while (listener.hasNext()) {
572             final OnPhaseFinished next = listener.next();
573             if (next.phaseFinished(this, phase)) {
574                 listener.remove();
575             }
576         }
577
578         if (listeners.isEmpty()) {
579             phaseListeners.removeAll(phase);
580             if (phaseListeners.isEmpty()) {
581                 phaseListeners = ImmutableMultimap.of();
582             }
583         }
584     }
585
586     /**
587      * Ends declared section of current node.
588      */
589     void endDeclared(final ModelProcessingPhase phase) {
590         definition.onDeclarationFinished(this, phase);
591     }
592
593     /**
594      * Return the context in which this statement was defined.
595      *
596      * @return statement definition
597      */
598     protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
599         return definition;
600     }
601
602     @Override
603     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
604         definition.checkNamespaceAllowed(type);
605     }
606
607     @Override
608     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
609             final V value) {
610         // definition().onNamespaceElementAdded(this, type, key, value);
611     }
612
613     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
614             final OnNamespaceItemAdded listener) {
615         final Object potential = getFromNamespace(type, key);
616         if (potential != null) {
617             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
618             listener.namespaceItemAdded(this, type, key, potential);
619             return;
620         }
621
622         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
623             @Override
624             void onValueAdded(final Object value) {
625                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
626             }
627         });
628     }
629
630     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
631             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
632             final OnNamespaceItemAdded listener) {
633         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
634         if (existing.isPresent()) {
635             final Entry<K, V> entry = existing.get();
636             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
637             waitForPhase(entry.getValue(), type, phase, criterion, listener);
638             return;
639         }
640
641         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
642         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
643             @Override
644             boolean onValueAdded(final K key, final V value) {
645                 if (criterion.match(key)) {
646                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
647                     waitForPhase(value, type, phase, criterion, listener);
648                     return true;
649                 }
650
651                 return false;
652             }
653         });
654     }
655
656     final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
657             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
658         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
659         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
660             type, this);
661         final Entry<K, V> match = optMatch.get();
662         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
663     }
664
665     final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
666             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
667             final OnNamespaceItemAdded listener) {
668         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
669             (context, phaseCompleted) -> {
670                 selectMatch(type, criterion, listener);
671                 return true;
672             });
673     }
674
675     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
676             final Class<N> type) {
677         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
678         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
679             type);
680
681         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
682     }
683
684     @Override
685     public StatementDefinition getPublicDefinition() {
686         return definition.getPublicView();
687     }
688
689     @Override
690     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
691         return getRoot().getSourceContext().newInferenceAction(phase);
692     }
693
694     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
695         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
696     }
697
698     /**
699      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
700      * the listener is notified immediately.
701      *
702      * @param phase requested completion phase
703      * @param listener listener to invoke
704      * @throws NullPointerException if any of the arguments is null
705      */
706     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
707         checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
708         checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
709
710         ModelProcessingPhase finishedPhase = completedPhase;
711         while (finishedPhase != null) {
712             if (phase.equals(finishedPhase)) {
713                 listener.phaseFinished(this, finishedPhase);
714                 return;
715             }
716             finishedPhase = finishedPhase.getPreviousPhase();
717         }
718         if (phaseListeners.isEmpty()) {
719             phaseListeners = newMultimap();
720         }
721
722         phaseListeners.put(phase, listener);
723     }
724
725     /**
726      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
727      *
728      * @throws IllegalStateException
729      *             when the mutation was registered after phase was completed
730      */
731     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
732         ModelProcessingPhase finishedPhase = completedPhase;
733         while (finishedPhase != null) {
734             checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
735                 getStatementSourceReference());
736             finishedPhase = finishedPhase.getPreviousPhase();
737         }
738
739         if (phaseMutation.isEmpty()) {
740             phaseMutation = newMultimap();
741         }
742         phaseMutation.put(phase, mutation);
743     }
744
745     @Override
746     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
747             final KT key,final StmtContext<?, ?, ?> stmt) {
748         addContextToNamespace(namespace, key, stmt);
749     }
750
751     @Override
752     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
753             final QNameModule targetModule) {
754         checkEffectiveModelCompleted(this);
755         return definition.support().copyAsChildOf(this, parent, type, targetModule);
756     }
757
758     @Override
759     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
760             final QNameModule targetModule) {
761         checkEffectiveModelCompleted(stmt);
762         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
763         return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
764     }
765
766     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
767             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
768         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
769             original.getPublicDefinition());
770
771         final StatementContextBase<X, Y, Z> result;
772         final InferredStatementContext<X, Y, Z> copy;
773
774         if (implicitParent.isPresent()) {
775             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
776             result = new SubstatementContext(this, def, original.getStatementSourceReference(),
777                 original.rawStatementArgument(), original.getStatementArgument(), type);
778
779             final CopyType childCopyType;
780             switch (type) {
781                 case ADDED_BY_AUGMENTATION:
782                     childCopyType = CopyType.ORIGINAL;
783                     break;
784                 case ADDED_BY_USES_AUGMENTATION:
785                     childCopyType = CopyType.ADDED_BY_USES;
786                     break;
787                 case ADDED_BY_USES:
788                 case ORIGINAL:
789                 default:
790                     childCopyType = type;
791             }
792
793             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
794             result.addEffectiveSubstatement(copy);
795         } else {
796             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
797         }
798
799         original.definition.onStatementAdded(copy);
800         return result;
801     }
802
803     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
804         final ModelProcessingPhase phase = stmt.getCompletedPhase();
805         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
806                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
807     }
808
809     @Beta
810     public final boolean hasImplicitParentSupport() {
811         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
812     }
813
814     @Beta
815     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
816         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
817             original.getPublicDefinition());
818         if (optImplicit.isEmpty()) {
819             return original;
820         }
821
822         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
823         final CopyType type = original.getCopyHistory().getLastOperation();
824         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
825             original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
826             type);
827
828         result.addEffectiveSubstatement(original.reparent(result));
829         result.setCompletedPhase(original.getCompletedPhase());
830         return result;
831     }
832
833     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
834
835     /**
836      * Config statements are not all that common which means we are performing a recursive search towards the root
837      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
838      * for the (usually non-existent) config statement.
839      *
840      * <p>
841      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
842      * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
843      *
844      * <p>
845      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
846      *       {@link #isIgnoringConfig(StatementContextBase)}.
847      */
848     final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
849         final int fl = flags & SET_CONFIGURATION;
850         if (fl != 0) {
851             return fl == SET_CONFIGURATION;
852         }
853         if (isIgnoringConfig(parent)) {
854             // Note: SET_CONFIGURATION has been stored in flags
855             return true;
856         }
857
858         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
859             ConfigStatement.class);
860         final boolean isConfig;
861         if (configStatement != null) {
862             isConfig = configStatement.coerceStatementArgument();
863             if (isConfig) {
864                 // Validity check: if parent is config=false this cannot be a config=true
865                 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
866                         "Parent node has config=false, this node must not be specifed as config=true");
867             }
868         } else {
869             // If "config" statement is not specified, the default is the same as the parent's "config" value.
870             isConfig = parent.isConfiguration();
871         }
872
873         // Resolved, make sure we cache this return
874         flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
875         return isConfig;
876     }
877
878     protected abstract boolean isIgnoringConfig();
879
880     /**
881      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
882      * keep on returning the same result without performing any lookups. Exists only to support
883      * {@link SubstatementContext#isIgnoringConfig()}.
884      *
885      * <p>
886      * Note: use of this method implies that {@link #isConfiguration()} is realized with
887      *       {@link #isConfiguration(StatementContextBase)}.
888      */
889     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
890         final int fl = flags & SET_IGNORE_CONFIG;
891         if (fl != 0) {
892             return fl == SET_IGNORE_CONFIG;
893         }
894         if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
895             flags |= SET_IGNORE_CONFIG;
896             return true;
897         }
898
899         flags |= HAVE_IGNORE_CONFIG;
900         return false;
901     }
902
903     protected abstract boolean isIgnoringIfFeatures();
904
905     /**
906      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
907      * keep on returning the same result without performing any lookups. Exists only to support
908      * {@link SubstatementContext#isIgnoringIfFeatures()}.
909      */
910     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
911         final int fl = flags & SET_IGNORE_IF_FEATURE;
912         if (fl != 0) {
913             return fl == SET_IGNORE_IF_FEATURE;
914         }
915         if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
916             flags |= SET_IGNORE_IF_FEATURE;
917             return true;
918         }
919
920         flags |= HAVE_IGNORE_IF_FEATURE;
921         return false;
922     }
923
924     // Exists only to support SubstatementContext/InferredStatementContext
925     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
926         SchemaPath local = schemaPath;
927         if (local == null) {
928             synchronized (this) {
929                 local = schemaPath;
930                 if (local == null) {
931                     local = createSchemaPath(coerceParentContext());
932                     schemaPath = local;
933                 }
934             }
935         }
936
937         return Optional.ofNullable(local);
938     }
939
940     private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
941         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
942         verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
943         final SchemaPath parentPath = maybeParentPath.get();
944
945         if (StmtContextUtils.isUnknownStatement(this)) {
946             return parentPath.createChild(getPublicDefinition().getStatementName());
947         }
948         final Object argument = getStatementArgument();
949         if (argument instanceof QName) {
950             final QName qname = (QName) argument;
951             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
952                 return maybeParentPath.orElse(null);
953             }
954
955             return parentPath.createChild(qname);
956         }
957         if (argument instanceof String) {
958             // FIXME: This may yield illegal argument exceptions
959             final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
960             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
961             return parentPath.createChild(qname);
962         }
963         if (argument instanceof SchemaNodeIdentifier
964                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
965                         || StmtContextUtils.producesDeclared(this, RefineStatement.class)
966                         || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
967
968             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
969         }
970
971         // FIXME: this does not look right
972         return maybeParentPath.orElse(null);
973     }
974
975     @Override
976     public final String toString() {
977         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
978     }
979
980     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
981         return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());
982     }
983 }