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