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