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