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