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