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