a9aa4099c3c1ac48d09962bb526a19b5a00153b2
[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 com.google.common.base.Verify.verify;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import com.google.common.collect.ImmutableCollection;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMultimap;
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;
32 import java.util.Map.Entry;
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.common.YangVersion;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
42 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
43 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
44 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
45 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
46 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
51 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
52 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
69 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
70 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
71 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
72 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
73 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
75 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 /**
80  * Core reactor statement implementation of {@link Mutable}.
81  *
82  * @param <A> Argument type
83  * @param <D> Declared Statement representation
84  * @param <E> Effective Statement representation
85  */
86 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
87         extends NamespaceStorageSupport implements Mutable<A, D, E> {
88     /**
89      * Event listener when an item is added to model namespace.
90      */
91     interface OnNamespaceItemAdded extends EventListener {
92         /**
93          * Invoked whenever a new item is added to a namespace.
94          */
95         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
96     }
97
98     /**
99      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
100      */
101     interface OnPhaseFinished extends EventListener {
102         /**
103          * Invoked whenever a processing phase has finished.
104          */
105         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
106     }
107
108     /**
109      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
110      */
111     interface ContextMutation {
112
113         boolean isFinished();
114     }
115
116     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
117
118     // Flag bit assignments
119     private static final int IS_SUPPORTED_BY_FEATURES    = 0x01;
120     private static final int HAVE_SUPPORTED_BY_FEATURES  = 0x02;
121     private static final int IS_IGNORE_IF_FEATURE        = 0x04;
122     private static final int HAVE_IGNORE_IF_FEATURE      = 0x08;
123     // Note: these four are related
124     private static final int IS_IGNORE_CONFIG            = 0x10;
125     private static final int HAVE_IGNORE_CONFIG          = 0x20;
126     private static final int IS_CONFIGURATION            = 0x40;
127     private static final int HAVE_CONFIGURATION          = 0x80;
128
129     // Have-and-set flag constants, also used as masks
130     private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
131     private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
132     // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
133     private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
134     private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
135
136     private final CopyHistory copyHistory;
137     // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
138     //       operations, hence we want to keep it close by.
139     private final @NonNull StatementDefinitionContext<A, D, E> definition;
140
141     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
142     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
143
144     // Note: this field is accessed either directly, or under substatementsInitialized == true
145     private List<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
146
147     private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
148
149     private @Nullable ModelProcessingPhase completedPhase;
150     private @Nullable E effectiveInstance;
151
152     // Master flag controlling whether this context can yield an effective statement
153     // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
154     //        of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
155     private boolean isSupportedToBuildEffective = true;
156
157     // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
158     private boolean fullyDefined;
159
160     // Flag for InferredStatementContext. This is hiding in the alignment shadow created by above boolean.
161     private boolean substatementsInitialized;
162
163     // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
164     // hence improve memory layout.
165     private byte flags;
166
167     // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
168     // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
169     private SchemaPath schemaPath;
170
171     // Copy constructor used by subclasses to implement reparent()
172     StatementContextBase(final StatementContextBase<A, D, E> original) {
173         this.copyHistory = original.copyHistory;
174         this.definition = original.definition;
175
176         this.isSupportedToBuildEffective = original.isSupportedToBuildEffective;
177         this.fullyDefined = original.fullyDefined;
178         this.completedPhase = original.completedPhase;
179         this.flags = original.flags;
180     }
181
182     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
183         this.definition = requireNonNull(def);
184         this.copyHistory = CopyHistory.original();
185     }
186
187     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
188         this.definition = requireNonNull(def);
189         this.copyHistory = requireNonNull(copyHistory);
190     }
191
192     @Override
193     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
194         return effectOfStatement;
195     }
196
197     @Override
198     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
199         if (effectOfStatement.isEmpty()) {
200             effectOfStatement = new ArrayList<>(1);
201         }
202         effectOfStatement.add(ctx);
203     }
204
205     @Override
206     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
207         if (ctxs.isEmpty()) {
208             return;
209         }
210
211         if (effectOfStatement.isEmpty()) {
212             effectOfStatement = new ArrayList<>(ctxs.size());
213         }
214         effectOfStatement.addAll(ctxs);
215     }
216
217     @Override
218     public boolean isSupportedByFeatures() {
219         final int fl = flags & SET_SUPPORTED_BY_FEATURES;
220         if (fl != 0) {
221             return fl == SET_SUPPORTED_BY_FEATURES;
222         }
223         if (isIgnoringIfFeatures()) {
224             flags |= SET_SUPPORTED_BY_FEATURES;
225             return true;
226         }
227
228         /*
229          * If parent is supported, we need to check if-features statements of this context.
230          */
231         if (isParentSupportedByFeatures()) {
232             // If the set of supported features has not been provided, all features are supported by default.
233             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
234                     SupportedFeatures.SUPPORTED_FEATURES);
235             if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
236                 flags |= SET_SUPPORTED_BY_FEATURES;
237                 return true;
238             }
239         }
240
241         // Either parent is not supported or this statement is not supported
242         flags |= HAVE_SUPPORTED_BY_FEATURES;
243         return false;
244     }
245
246     protected abstract boolean isParentSupportedByFeatures();
247
248     @Override
249     public boolean isSupportedToBuildEffective() {
250         return isSupportedToBuildEffective;
251     }
252
253     @Override
254     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
255         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
256     }
257
258     @Override
259     public CopyHistory getCopyHistory() {
260         return copyHistory;
261     }
262
263     @Override
264     public ModelProcessingPhase getCompletedPhase() {
265         return completedPhase;
266     }
267
268     // FIXME: this should be propagated through a correct constructor
269     @Deprecated
270     final 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 final @NonNull Registry getBehaviourRegistry() {
287         return getRoot().getBehaviourRegistryImpl();
288     }
289
290     @Override
291     public final YangVersion getRootVersion() {
292         return getRoot().getRootVersionImpl();
293     }
294
295     @Override
296     public final void setRootVersion(final YangVersion version) {
297         getRoot().setRootVersionImpl(version);
298     }
299
300     @Override
301     public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
302         getRoot().addMutableStmtToSealImpl(mutableStatement);
303     }
304
305     @Override
306     public final void addRequiredSource(final SourceIdentifier dependency) {
307         getRoot().addRequiredSourceImpl(dependency);
308     }
309
310     @Override
311     public final void setRootIdentifier(final SourceIdentifier identifier) {
312         getRoot().setRootIdentifierImpl(identifier);
313     }
314
315     @Override
316     public final boolean isEnabledSemanticVersioning() {
317         return getRoot().isEnabledSemanticVersioningImpl();
318     }
319
320     @Override
321     public StatementSource getStatementSource() {
322         return getStatementSourceReference().getStatementSource();
323     }
324
325     @Override
326     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromCurrentStmtCtxNamespace(
327             final Class<N> type) {
328         return getLocalNamespace(type);
329     }
330
331     @Override
332     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromNamespace(final Class<N> type) {
333         return getNamespace(type);
334     }
335
336     /**
337      * Associate a value with a key within a namespace.
338      *
339      * @param type Namespace type
340      * @param key Key
341      * @param value value
342      * @param <K> namespace key type
343      * @param <V> namespace value type
344      * @param <N> namespace type
345      * @param <T> key type
346      * @param <U> value type
347      * @throws NamespaceNotAvailableException when the namespace is not available.
348      */
349     @Override
350     public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
351             final Class<@NonNull N> type, final T key, final U value) {
352         addToNamespace(type, key, value);
353     }
354
355     @Override
356     public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
357
358     /**
359      * Return a value associated with specified key within a namespace.
360      *
361      * @param type Namespace type
362      * @param key Key
363      * @param <K> namespace key type
364      * @param <V> namespace value type
365      * @param <N> namespace type
366      * @param <T> key type
367      * @return Value, or null if there is no element
368      * @throws NamespaceNotAvailableException when the namespace is not available.
369      */
370     @Override
371     public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V getFromNamespace(
372             final Class<@NonNull N> type, final T key) {
373         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
374     }
375
376     @Override
377     public final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
378         ensureEffectiveSubstatements();
379         if (effective instanceof ImmutableCollection) {
380             return effective;
381         }
382
383         return Collections.unmodifiableCollection(effective);
384     }
385
386     private void shrinkEffective() {
387         // Initialization guarded by all callers
388         if (effective.isEmpty()) {
389             effective = ImmutableList.of();
390         }
391     }
392
393     // Note: has side-effect of ensureEffectiveSubstatements()
394     public final void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
395         ensureEffectiveSubstatements();
396         if (effective.isEmpty()) {
397             return;
398         }
399
400         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
401         while (iterator.hasNext()) {
402             final StmtContext<?, ?, ?> next = iterator.next();
403             if (statementDef.equals(next.getPublicDefinition())) {
404                 iterator.remove();
405             }
406         }
407
408         shrinkEffective();
409     }
410
411     /**
412      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
413      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
414      * definition and statement argument match with one of the effective substatements' statement definition
415      * and argument.
416      *
417      * <p>
418      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
419      *
420      * @param statementDef statement definition of the statement context to remove
421      * @param statementArg statement argument of the statement context to remove
422      */
423     public final void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
424             final String statementArg) {
425         if (statementArg == null) {
426             // Note: has side-effect of ensureEffectiveSubstatements()
427             removeStatementFromEffectiveSubstatements(statementDef);
428         } else {
429             ensureEffectiveSubstatements();
430         }
431
432         if (effective.isEmpty()) {
433             return;
434         }
435
436         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
437         while (iterator.hasNext()) {
438             final Mutable<?, ?, ?> next = iterator.next();
439             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
440                 iterator.remove();
441             }
442         }
443
444         shrinkEffective();
445     }
446
447     // YANG example: RPC/action statements always have 'input' and 'output' defined
448     @Beta
449     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
450             appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
451         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
452         //                       StatementContextBase subclass.
453         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
454                 ImplicitSubstatement.of(getStatementSourceReference()), rawArg);
455         support.onStatementAdded(ret);
456         addEffectiveSubstatement(ret);
457         return ret;
458     }
459
460     /**
461      * Adds an effective statement to collection of substatements.
462      *
463      * @param substatement substatement
464      * @throws IllegalStateException
465      *             if added in declared phase
466      * @throws NullPointerException
467      *             if statement parameter is null
468      */
469     public final void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
470         verifyStatement(substatement);
471         ensureEffectiveSubstatements();
472         beforeAddEffectiveStatement(1);
473
474         final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
475         final ModelProcessingPhase phase = completedPhase;
476         if (phase != null) {
477             ensureCompletedPhase(stmt, phase);
478         }
479         effective.add(stmt);
480     }
481
482     /**
483      * Adds an effective statement to collection of substatements.
484      *
485      * @param statements substatements
486      * @throws IllegalStateException
487      *             if added in declared phase
488      * @throws NullPointerException
489      *             if statement parameter is null
490      */
491     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
492         if (!statements.isEmpty()) {
493             statements.forEach(StatementContextBase::verifyStatement);
494             ensureEffectiveSubstatements();
495             beforeAddEffectiveStatement(statements.size());
496             doAddEffectiveSubstatements(statements);
497         }
498     }
499
500     // exposed for InferredStatementContext, which we expect to initialize effective substatements
501     void ensureEffectiveSubstatements() {
502         // No-op for everything except InferredStatementContext
503     }
504
505     // Exposed for InferredStatementContextr only, others do not need initialization
506     Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete() {
507         return effective;
508     }
509
510     // exposed for InferredStatementContext only
511     final void addInitialEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
512         verify(!substatementsInitialized, "Attempted to re-initialized statement {} with {}", this, statements);
513         substatementsInitialized = true;
514
515         if (!statements.isEmpty()) {
516             statements.forEach(StatementContextBase::verifyStatement);
517             beforeAddEffectiveStatementUnsafe(statements.size());
518             doAddEffectiveSubstatements(statements);
519         }
520     }
521
522     private void doAddEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
523         final Collection<? extends StatementContextBase<?, ?, ?>> casted =
524             (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
525         final ModelProcessingPhase phase = completedPhase;
526         if (phase != null) {
527             for (StatementContextBase<?, ?, ?> stmt : casted) {
528                 ensureCompletedPhase(stmt, phase);
529             }
530         }
531
532         // Initialization guarded by all callers
533         effective.addAll(casted);
534     }
535
536     // Make sure target statement has transitioned at least to specified phase. This method is just before we take
537     // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
538     // any statements which did not complete the same phase as the root statement.
539     private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
540             final ModelProcessingPhase phase) {
541         verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
542     }
543
544     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
545         verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
546     }
547
548     private void beforeAddEffectiveStatement(final int toAdd) {
549         // We cannot allow statement to be further mutated
550         verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
551             getStatementSourceReference());
552         beforeAddEffectiveStatementUnsafe(toAdd);
553     }
554
555     private void beforeAddEffectiveStatementUnsafe(final int toAdd) {
556         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
557         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
558                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
559                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
560
561         // Initialization guarded by all callers
562         if (effective.isEmpty()) {
563             effective = new ArrayList<>(toAdd);
564         }
565     }
566
567     // These two exists only due to memory optimization, should live in AbstractResumedStatement
568     final boolean fullyDefined() {
569         return fullyDefined;
570     }
571
572     final void setFullyDefined() {
573         fullyDefined = true;
574     }
575
576     // These two exist only due to memory optimization, should live in InferredStatementContext
577     final boolean substatementsInitialized() {
578         return substatementsInitialized;
579     }
580
581     final void setSubstatementsInitialized() {
582         substatementsInitialized = true;
583     }
584
585     @Override
586     public E buildEffective() {
587         final E existing;
588         return (existing = effectiveInstance) != null ? existing : loadEffective();
589     }
590
591     private E loadEffective() {
592         return effectiveInstance = definition.getFactory().createEffective(this);
593     }
594
595     /**
596      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
597      * this method does nothing.
598      *
599      * @param phase to be executed (completed)
600      * @return true if phase was successfully completed
601      * @throws SourceException when an error occurred in source parsing
602      */
603     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
604         return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
605     }
606
607     private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
608         final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
609         if (completeChildren(phase) && finished) {
610             onPhaseCompleted(phase);
611             return true;
612         }
613         return false;
614     }
615
616     private boolean completeChildren(final ModelProcessingPhase phase) {
617         boolean finished = true;
618         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
619             finished &= child.tryToCompletePhase(phase);
620         }
621         for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
622             finished &= child.tryToCompletePhase(phase);
623         }
624         return finished;
625     }
626
627     private boolean runMutations(final ModelProcessingPhase phase) {
628         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
629         return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
630     }
631
632     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
633         boolean finished = true;
634         final Iterator<ContextMutation> it = openMutations.iterator();
635         while (it.hasNext()) {
636             final ContextMutation current = it.next();
637             if (current.isFinished()) {
638                 it.remove();
639             } else {
640                 finished = false;
641             }
642         }
643
644         if (openMutations.isEmpty()) {
645             phaseMutation.removeAll(phase);
646             cleanupPhaseMutation();
647         }
648         return finished;
649     }
650
651     private void cleanupPhaseMutation() {
652         if (phaseMutation.isEmpty()) {
653             phaseMutation = ImmutableMultimap.of();
654         }
655     }
656
657     /**
658      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
659      *
660      * @param phase
661      *            that was to be completed (finished)
662      * @throws SourceException
663      *             when an error occurred in source parsing
664      */
665     private void onPhaseCompleted(final ModelProcessingPhase phase) {
666         completedPhase = phase;
667
668         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
669         if (!listeners.isEmpty()) {
670             runPhaseListeners(phase, listeners);
671         }
672     }
673
674     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
675         final Iterator<OnPhaseFinished> listener = listeners.iterator();
676         while (listener.hasNext()) {
677             final OnPhaseFinished next = listener.next();
678             if (next.phaseFinished(this, phase)) {
679                 listener.remove();
680             }
681         }
682
683         if (listeners.isEmpty()) {
684             phaseListeners.removeAll(phase);
685             if (phaseListeners.isEmpty()) {
686                 phaseListeners = ImmutableMultimap.of();
687             }
688         }
689     }
690
691     /**
692      * Ends declared section of current node.
693      */
694     void endDeclared(final ModelProcessingPhase phase) {
695         definition.onDeclarationFinished(this, phase);
696     }
697
698     /**
699      * Return the context in which this statement was defined.
700      *
701      * @return statement definition
702      */
703     protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
704         return definition;
705     }
706
707     @Override
708     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
709         definition.checkNamespaceAllowed(type);
710     }
711
712     @Override
713     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
714             final V value) {
715         // definition().onNamespaceElementAdded(this, type, key, value);
716     }
717
718     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
719             final OnNamespaceItemAdded listener) {
720         final Object potential = getFromNamespace(type, key);
721         if (potential != null) {
722             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
723             listener.namespaceItemAdded(this, type, key, potential);
724             return;
725         }
726
727         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
728             @Override
729             void onValueAdded(final Object value) {
730                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
731             }
732         });
733     }
734
735     final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
736             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
737             final OnNamespaceItemAdded listener) {
738         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
739         if (existing.isPresent()) {
740             final Entry<K, V> entry = existing.get();
741             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
742             waitForPhase(entry.getValue(), type, phase, criterion, listener);
743             return;
744         }
745
746         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
747         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
748             @Override
749             boolean onValueAdded(final K key, final V value) {
750                 if (criterion.match(key)) {
751                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
752                     waitForPhase(value, type, phase, criterion, listener);
753                     return true;
754                 }
755
756                 return false;
757             }
758         });
759     }
760
761     final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
762             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
763         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
764         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
765             type, this);
766         final Entry<K, V> match = optMatch.get();
767         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
768     }
769
770     final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
771             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
772             final OnNamespaceItemAdded listener) {
773         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
774             (context, phaseCompleted) -> {
775                 selectMatch(type, criterion, listener);
776                 return true;
777             });
778     }
779
780     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
781             final Class<N> type) {
782         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
783         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
784             type);
785
786         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
787     }
788
789     @Override
790     public StatementDefinition getPublicDefinition() {
791         return definition.getPublicView();
792     }
793
794     @Override
795     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
796         return getRoot().getSourceContext().newInferenceAction(phase);
797     }
798
799     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
800         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
801     }
802
803     /**
804      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
805      * the listener is notified immediately.
806      *
807      * @param phase requested completion phase
808      * @param listener listener to invoke
809      * @throws NullPointerException if any of the arguments is null
810      */
811     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
812         checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
813         checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
814
815         ModelProcessingPhase finishedPhase = completedPhase;
816         while (finishedPhase != null) {
817             if (phase.equals(finishedPhase)) {
818                 listener.phaseFinished(this, finishedPhase);
819                 return;
820             }
821             finishedPhase = finishedPhase.getPreviousPhase();
822         }
823         if (phaseListeners.isEmpty()) {
824             phaseListeners = newMultimap();
825         }
826
827         phaseListeners.put(phase, listener);
828     }
829
830     /**
831      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
832      *
833      * @throws IllegalStateException when the mutation was registered after phase was completed
834      */
835     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
836         ModelProcessingPhase finishedPhase = completedPhase;
837         while (finishedPhase != null) {
838             checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
839                 getStatementSourceReference());
840             finishedPhase = finishedPhase.getPreviousPhase();
841         }
842
843         if (phaseMutation.isEmpty()) {
844             phaseMutation = newMultimap();
845         }
846         phaseMutation.put(phase, mutation);
847     }
848
849     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
850         if (!phaseMutation.isEmpty()) {
851             phaseMutation.remove(phase, mutation);
852             cleanupPhaseMutation();
853         }
854     }
855
856     @Override
857     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
858             final KT key,final StmtContext<?, ?, ?> stmt) {
859         addContextToNamespace(namespace, key, stmt);
860     }
861
862     @Override
863     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
864             final QNameModule targetModule) {
865         checkEffectiveModelCompleted(this);
866
867         final StatementSupport<A, D, E> support = definition.support();
868         final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
869         switch (policy) {
870             case CONTEXT_INDEPENDENT:
871                 if (hasEmptySubstatements()) {
872                     // This statement is context-independent and has no substatements -- hence it can be freely shared.
873                     return Optional.of(this);
874                 }
875                 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
876                 // fall through
877             case DECLARED_COPY:
878                 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
879                 //                       context, so that we can support building an effective statement without copying
880                 //                       anything -- we will typically end up not being inferred against. In that case,
881                 //                       this slim context should end up dealing with differences at buildContext()
882                 //                       time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
883                 //                       cannot be shared across instances).
884                 return Optional.of(parent.childCopyOf(this, type, targetModule));
885             case IGNORE:
886                 return Optional.empty();
887             case REJECT:
888                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
889             default:
890                 throw new IllegalStateException("Unhandled policy " + policy);
891         }
892     }
893
894     @Override
895     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
896             final QNameModule targetModule) {
897         checkEffectiveModelCompleted(stmt);
898         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
899         return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
900     }
901
902     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
903             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
904         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
905             original.getPublicDefinition());
906
907         final StatementContextBase<X, Y, Z> result;
908         final InferredStatementContext<X, Y, Z> copy;
909
910         if (implicitParent.isPresent()) {
911             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
912             result = new SubstatementContext(this, def, original.getStatementSourceReference(),
913                 original.rawStatementArgument(), original.getStatementArgument(), type);
914
915             final CopyType childCopyType;
916             switch (type) {
917                 case ADDED_BY_AUGMENTATION:
918                     childCopyType = CopyType.ORIGINAL;
919                     break;
920                 case ADDED_BY_USES_AUGMENTATION:
921                     childCopyType = CopyType.ADDED_BY_USES;
922                     break;
923                 case ADDED_BY_USES:
924                 case ORIGINAL:
925                 default:
926                     childCopyType = type;
927             }
928
929             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
930             result.addEffectiveSubstatement(copy);
931         } else {
932             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
933         }
934
935         original.definition.onStatementAdded(copy);
936         return result;
937     }
938
939     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
940         final ModelProcessingPhase phase = stmt.getCompletedPhase();
941         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
942                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
943     }
944
945     @Beta
946     public final boolean hasImplicitParentSupport() {
947         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
948     }
949
950     @Beta
951     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
952         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
953             original.getPublicDefinition());
954         if (optImplicit.isEmpty()) {
955             return original;
956         }
957
958         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
959         final CopyType type = original.getCopyHistory().getLastOperation();
960         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
961             original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
962             type);
963
964         result.addEffectiveSubstatement(original.reparent(result));
965         result.setCompletedPhase(original.getCompletedPhase());
966         return result;
967     }
968
969     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
970
971     /**
972      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
973      *
974      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
975      */
976     abstract boolean hasEmptySubstatements();
977
978     // Dual use method: AbstractResumedStatement does not use 'initialized' and InferredStatementContext ensures
979     //                  initialization.
980     // FIXME: 7.0.0: I think this warrants a separate subclasses, as InferredStatementContext wants to manage these
981     //               itself. Before we do that, though, we need to analyze size impacts
982     final boolean hasEmptyEffectiveSubstatements() {
983         return effective.isEmpty();
984     }
985
986     /**
987      * Config statements are not all that common which means we are performing a recursive search towards the root
988      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
989      * for the (usually non-existent) config statement.
990      *
991      * <p>
992      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
993      * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
994      *
995      * <p>
996      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
997      *       {@link #isIgnoringConfig(StatementContextBase)}.
998      */
999     final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
1000         final int fl = flags & SET_CONFIGURATION;
1001         if (fl != 0) {
1002             return fl == SET_CONFIGURATION;
1003         }
1004         if (isIgnoringConfig(parent)) {
1005             // Note: SET_CONFIGURATION has been stored in flags
1006             return true;
1007         }
1008
1009         final boolean isConfig;
1010         final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
1011         if (optConfig.isPresent()) {
1012             isConfig = optConfig.orElseThrow();
1013             if (isConfig) {
1014                 // Validity check: if parent is config=false this cannot be a config=true
1015                 InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
1016                         "Parent node has config=false, this node must not be specifed as config=true");
1017             }
1018         } else {
1019             // If "config" statement is not specified, the default is the same as the parent's "config" value.
1020             isConfig = parent.isConfiguration();
1021         }
1022
1023         // Resolved, make sure we cache this return
1024         flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
1025         return isConfig;
1026     }
1027
1028     protected abstract boolean isIgnoringConfig();
1029
1030     /**
1031      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
1032      * keep on returning the same result without performing any lookups. Exists only to support
1033      * {@link SubstatementContext#isIgnoringConfig()}.
1034      *
1035      * <p>
1036      * Note: use of this method implies that {@link #isConfiguration()} is realized with
1037      *       {@link #isConfiguration(StatementContextBase)}.
1038      */
1039     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
1040         final int fl = flags & SET_IGNORE_CONFIG;
1041         if (fl != 0) {
1042             return fl == SET_IGNORE_CONFIG;
1043         }
1044         if (definition.support().isIgnoringConfig() || parent.isIgnoringConfig()) {
1045             flags |= SET_IGNORE_CONFIG;
1046             return true;
1047         }
1048
1049         flags |= HAVE_IGNORE_CONFIG;
1050         return false;
1051     }
1052
1053     protected abstract boolean isIgnoringIfFeatures();
1054
1055     /**
1056      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
1057      * keep on returning the same result without performing any lookups. Exists only to support
1058      * {@link SubstatementContext#isIgnoringIfFeatures()}.
1059      */
1060     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
1061         final int fl = flags & SET_IGNORE_IF_FEATURE;
1062         if (fl != 0) {
1063             return fl == SET_IGNORE_IF_FEATURE;
1064         }
1065         if (definition.support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
1066             flags |= SET_IGNORE_IF_FEATURE;
1067             return true;
1068         }
1069
1070         flags |= HAVE_IGNORE_IF_FEATURE;
1071         return false;
1072     }
1073
1074     // Exists only to support {SubstatementContext,InferredStatementContext}.getSchemaPath()
1075     @Deprecated
1076     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
1077         if (schemaPath == null) {
1078             schemaPath = createSchemaPath(coerceParentContext());
1079         }
1080         return Optional.ofNullable(schemaPath);
1081     }
1082
1083     @Deprecated
1084     private SchemaPath createSchemaPath(final Mutable<?, ?, ?> parent) {
1085         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
1086         verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
1087         final SchemaPath parentPath = maybeParentPath.get();
1088
1089         if (StmtContextUtils.isUnknownStatement(this)) {
1090             return parentPath.createChild(getPublicDefinition().getStatementName());
1091         }
1092         final Object argument = getStatementArgument();
1093         if (argument instanceof QName) {
1094             final QName qname = (QName) argument;
1095             if (producesDeclared(UsesStatement.class)) {
1096                 return maybeParentPath.orElse(null);
1097             }
1098
1099             return parentPath.createChild(qname);
1100         }
1101         if (argument instanceof String) {
1102             // FIXME: This may yield illegal argument exceptions
1103             final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
1104             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
1105             return parentPath.createChild(qname);
1106         }
1107         if (argument instanceof SchemaNodeIdentifier
1108                 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
1109                         || producesDeclared(DeviationStatement.class))) {
1110
1111             return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
1112         }
1113
1114         // FIXME: this does not look right
1115         return maybeParentPath.orElse(null);
1116     }
1117
1118     @Override
1119     public final String toString() {
1120         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
1121     }
1122
1123     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
1124         return toStringHelper.add("definition", definition).add("rawArgument", rawStatementArgument());
1125     }
1126 }