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