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