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