Bug 8922 - Evaluation of if-features is done regardless of ancestors
[yangtools.git] / yang / yang-parser-impl / 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 com.google.common.base.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMultimap;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.EnumMap;
22 import java.util.EventListener;
23 import java.util.Iterator;
24 import java.util.Optional;
25 import java.util.Set;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.util.OptionalBoolean;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
53     /**
54      * event listener when an item is added to model namespace.
55      */
56     interface OnNamespaceItemAdded extends EventListener {
57         /**
58          * @throws SourceException
59          */
60         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
61     }
62
63     /**
64      * event listener when a parsing {@link ModelProcessingPhase} is completed.
65      */
66     interface OnPhaseFinished extends EventListener {
67         /**
68          * @throws SourceException
69          */
70         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
71     }
72
73     /**
74      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
75      */
76     interface ContextMutation {
77
78         boolean isFinished();
79     }
80
81     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
82
83     private final StatementDefinitionContext<A, D, E> definition;
84     private final StatementSourceReference statementDeclSource;
85     private final StmtContext<?, ?, ?> originalCtx;
86     private final CopyHistory copyHistory;
87     private final String rawArgument;
88
89     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
90     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
91     private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
92     private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
93     private StatementMap substatements = StatementMap.empty();
94
95     private boolean isSupportedToBuildEffective = true;
96     private ModelProcessingPhase completedPhase = null;
97     private D declaredInstance;
98     private E effectiveInstance;
99
100     // BooleanFields value
101     private byte supportedByFeatures;
102
103     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
104             final String rawArgument) {
105         this.definition = Preconditions.checkNotNull(def);
106         this.statementDeclSource = Preconditions.checkNotNull(ref);
107         this.rawArgument = def.internArgument(rawArgument);
108         this.copyHistory = CopyHistory.original();
109         this.originalCtx = null;
110     }
111
112     StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
113         this.definition = Preconditions.checkNotNull(original.definition,
114                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
115         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
116                 "Statement context statementDeclSource cannot be null copying from: %s",
117                 original.getStatementSourceReference());
118         this.rawArgument = original.rawArgument;
119         this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
120         this.originalCtx = original.getOriginalCtx().orElse(original);
121     }
122
123     @Override
124     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
125         return effectOfStatement;
126     }
127
128     @Override
129     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
130         if (effectOfStatement.isEmpty()) {
131             effectOfStatement = new ArrayList<>(1);
132         }
133         effectOfStatement.add(ctx);
134     }
135
136     @Override
137     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
138         if (ctxs.isEmpty()) {
139             return;
140         }
141
142         if (effectOfStatement.isEmpty()) {
143             effectOfStatement = new ArrayList<>(ctxs.size());
144         }
145         effectOfStatement.addAll(ctxs);
146     }
147
148     @Override
149     public boolean isSupportedByFeatures() {
150         if (OptionalBoolean.isPresent(supportedByFeatures)) {
151             return OptionalBoolean.get(supportedByFeatures);
152         }
153
154         if (isIgnoringIfFeatures()) {
155             supportedByFeatures = OptionalBoolean.of(true);
156             return true;
157         }
158
159         final boolean isParentSupported = isParentSupportedByFeatures();
160         /*
161          * If parent is not supported, then this context is also not supported.
162          * So we do not need to check if-features statements of this context and
163          * we can return false immediately.
164          */
165         if (!isParentSupported) {
166             supportedByFeatures = OptionalBoolean.of(false);
167             return false;
168         }
169
170         /*
171          * If parent is supported, we need to check if-features statements of
172          * this context.
173          */
174         // If the set of supported features has not been provided, all features are supported by default.
175         final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
176                 SupportedFeatures.SUPPORTED_FEATURES);
177         final boolean ret = supportedFeatures == null ? true
178                 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
179
180         supportedByFeatures = OptionalBoolean.of(ret);
181         return ret;
182     }
183
184     protected abstract boolean isParentSupportedByFeatures();
185
186     protected abstract boolean isIgnoringIfFeatures();
187
188     protected abstract boolean isIgnoringConfig();
189
190     @Override
191     public boolean isSupportedToBuildEffective() {
192         return isSupportedToBuildEffective;
193     }
194
195     @Override
196     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
197         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
198     }
199
200     @Override
201     public CopyHistory getCopyHistory() {
202         return copyHistory;
203     }
204
205     @Override
206     public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
207         return Optional.ofNullable(originalCtx);
208     }
209
210     @Override
211     public ModelProcessingPhase getCompletedPhase() {
212         return completedPhase;
213     }
214
215     @Override
216     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
217         this.completedPhase = completedPhase;
218     }
219
220     @Override
221     public abstract StatementContextBase<?, ?, ?> getParentContext();
222
223     /**
224      * @return root context of statement
225      */
226     @Nonnull
227     @Override
228     public abstract RootStatementContext<?, ?, ?> getRoot();
229
230     /**
231      * @return origin of statement
232      */
233     @Nonnull
234     @Override
235     public StatementSource getStatementSource() {
236         return statementDeclSource.getStatementSource();
237     }
238
239     /**
240      * @return reference of statement source
241      */
242     @Nonnull
243     @Override
244     public StatementSourceReference getStatementSourceReference() {
245         return statementDeclSource;
246     }
247
248     @Override
249     public final String rawStatementArgument() {
250         return rawArgument;
251     }
252
253     @Nonnull
254     @Override
255     public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
256         return substatements.values();
257     }
258
259     @Nonnull
260     @Override
261     public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
262         return substatements.values();
263     }
264
265     @Override
266     public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
267         return mutableEffectiveSubstatements();
268     }
269
270     @Nonnull
271     @Override
272     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
273         if (effective instanceof ImmutableCollection) {
274             return effective;
275         }
276
277         return Collections.unmodifiableCollection(effective);
278     }
279
280     public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
281         if (!effective.isEmpty()) {
282             effective.removeAll(substatements);
283             shrinkEffective();
284         }
285     }
286
287     private void shrinkEffective() {
288         if (effective.isEmpty()) {
289             effective = ImmutableList.of();
290         }
291     }
292
293     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
294         if (effective.isEmpty()) {
295             return;
296         }
297
298         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
299         while (iterator.hasNext()) {
300             final StmtContext<?, ?, ?> next = iterator.next();
301             if (statementDef.equals(next.getPublicDefinition())) {
302                 iterator.remove();
303             }
304         }
305
306         shrinkEffective();
307     }
308
309     /**
310      * Removes a statement context from the effective substatements
311      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
312      * The statement context is removed only if both statement definition and statement argument match with
313      * one of the effective substatements' statement definition and argument.
314      *
315      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
316      *
317      * @param statementDef statement definition of the statement context to remove
318      * @param statementArg statement argument of the statement context to remove
319      */
320     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
321             final String statementArg) {
322         if (statementArg == null) {
323             removeStatementFromEffectiveSubstatements(statementDef);
324         }
325
326         if (effective.isEmpty()) {
327             return;
328         }
329
330         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
331         while (iterator.hasNext()) {
332             final Mutable<?, ?, ?> next = iterator.next();
333             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
334                 iterator.remove();
335             }
336         }
337
338         shrinkEffective();
339     }
340
341     /**
342      * adds effective statement to collection of substatements
343      *
344      * @param substatement substatement
345      * @throws IllegalStateException
346      *             if added in declared phase
347      * @throws NullPointerException
348      *             if statement parameter is null
349      */
350     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
351         beforeAddEffectiveStatement(1);
352         effective.add(substatement);
353     }
354
355     /**
356      * adds effective statement to collection of substatements
357      *
358      * @param substatements substatements
359      * @throws IllegalStateException
360      *             if added in declared phase
361      * @throws NullPointerException
362      *             if statement parameter is null
363      */
364     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
365         if (substatements.isEmpty()) {
366             return;
367         }
368
369         substatements.forEach(Preconditions::checkNotNull);
370         beforeAddEffectiveStatement(substatements.size());
371         effective.addAll(substatements);
372     }
373
374     private void beforeAddEffectiveStatement(final int toAdd) {
375         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
376         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
377                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
378                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
379
380         if (effective.isEmpty()) {
381             effective = new ArrayList<>(toAdd);
382         }
383     }
384
385     /**
386      * Create a new substatement at the specified offset.
387      *
388      * @param offset Substatement offset
389      * @param def definition context
390      * @param ref source reference
391      * @param argument statement argument
392      * @return A new substatement
393      */
394     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
395             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
396             final String argument) {
397         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
398         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
399                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
400
401         final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
402             offset, def, ref, argument);
403         if (implicitStatement.isPresent()) {
404             return implicitStatement.get().createSubstatement(offset, def, ref, argument);
405         }
406
407         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
408         substatements = substatements.put(offset, ret);
409         def.onStatementAdded(ret);
410         return ret;
411     }
412
413     /**
414      * Lookup substatement by its offset in this statement.
415      *
416      * @param offset Substatement offset
417      * @return Substatement, or null if substatement does not exist.
418      */
419     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
420         return substatements.get(offset);
421     }
422
423     @Override
424     public D buildDeclared() {
425         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
426                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
427         if (declaredInstance == null) {
428             declaredInstance = definition().getFactory().createDeclared(this);
429         }
430         return declaredInstance;
431     }
432
433     @Override
434     public E buildEffective() {
435         if (effectiveInstance == null) {
436             effectiveInstance = definition().getFactory().createEffective(this);
437         }
438         return effectiveInstance;
439     }
440
441     /**
442      * tries to execute current {@link ModelProcessingPhase} of source parsing.
443      *
444      * @param phase
445      *            to be executed (completed)
446      * @return if phase was successfully completed
447      * @throws SourceException
448      *             when an error occured in source parsing
449      */
450     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
451
452         boolean finished = true;
453         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
454         if (!openMutations.isEmpty()) {
455             final Iterator<ContextMutation> it = openMutations.iterator();
456             while (it.hasNext()) {
457                 final ContextMutation current = it.next();
458                 if (current.isFinished()) {
459                     it.remove();
460                 } else {
461                     finished = false;
462                 }
463             }
464
465             if (openMutations.isEmpty()) {
466                 phaseMutation.removeAll(phase);
467                 if (phaseMutation.isEmpty()) {
468                     phaseMutation = ImmutableMultimap.of();
469                 }
470             }
471         }
472
473         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
474             finished &= child.tryToCompletePhase(phase);
475         }
476         for (final Mutable<?, ?, ?> child : effective) {
477             if (child instanceof StatementContextBase) {
478                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
479             }
480         }
481
482         if (finished) {
483             onPhaseCompleted(phase);
484             return true;
485         }
486         return false;
487     }
488
489     /**
490      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
491      *
492      * @param phase
493      *            that was to be completed (finished)
494      * @throws SourceException
495      *             when an error occurred in source parsing
496      */
497     private void onPhaseCompleted(final ModelProcessingPhase phase) {
498         completedPhase = phase;
499
500         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
501         if (listeners.isEmpty()) {
502             return;
503         }
504
505         final Iterator<OnPhaseFinished> listener = listeners.iterator();
506         while (listener.hasNext()) {
507             final OnPhaseFinished next = listener.next();
508             if (next.phaseFinished(this, phase)) {
509                 listener.remove();
510             }
511         }
512
513         if (listeners.isEmpty()) {
514             phaseListeners.removeAll(phase);
515             if (phaseListeners.isEmpty()) {
516                 phaseListeners = ImmutableMultimap.of();
517             }
518         }
519     }
520
521     /**
522      * Ends declared section of current node.
523      *
524      * @param ref
525      * @throws SourceException
526      */
527     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
528         definition().onDeclarationFinished(this, phase);
529     }
530
531     /**
532      * @return statement definition
533      */
534     protected final StatementDefinitionContext<A, D, E> definition() {
535         return definition;
536     }
537
538     @Override
539     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
540         definition().checkNamespaceAllowed(type);
541     }
542
543     @Override
544     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
545             final V value) {
546         // definition().onNamespaceElementAdded(this, type, key, value);
547     }
548
549     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
550             final OnNamespaceItemAdded listener) throws SourceException {
551         final Object potential = getFromNamespace(type, key);
552         if (potential != null) {
553             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
554             listener.namespaceItemAdded(this, type, key, potential);
555             return;
556         }
557
558         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
559         Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
560             "Namespace {} does not support listeners", type);
561
562         final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
563         casted.addValueListener(new ValueAddedListener<K>(this, key) {
564             @Override
565             void onValueAdded(final Object key, final Object value) {
566                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
567             }
568         });
569     }
570
571     /**
572      * See {@link StatementSupport#getPublicView()}.
573      */
574     @Nonnull
575     @Override
576     public StatementDefinition getPublicDefinition() {
577         return definition().getPublicView();
578     }
579
580     @Override
581     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
582         return getRoot().getSourceContext().newInferenceAction(phase);
583     }
584
585     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
586         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
587     }
588
589     /**
590      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
591      *
592      * @throws SourceException
593      */
594     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
595
596         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
597                 getStatementSourceReference());
598         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
599                 getStatementSourceReference());
600
601         ModelProcessingPhase finishedPhase = completedPhase;
602         while (finishedPhase != null) {
603             if (phase.equals(finishedPhase)) {
604                 listener.phaseFinished(this, finishedPhase);
605                 return;
606             }
607             finishedPhase = finishedPhase.getPreviousPhase();
608         }
609         if (phaseListeners.isEmpty()) {
610             phaseListeners = newMultimap();
611         }
612
613         phaseListeners.put(phase, listener);
614     }
615
616     /**
617      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
618      *
619      * @throws IllegalStateException
620      *             when the mutation was registered after phase was completed
621      */
622     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
623         ModelProcessingPhase finishedPhase = completedPhase;
624         while (finishedPhase != null) {
625             if (phase.equals(finishedPhase)) {
626                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
627                         getStatementSourceReference());
628             }
629             finishedPhase = finishedPhase.getPreviousPhase();
630         }
631
632         if (phaseMutation.isEmpty()) {
633             phaseMutation = newMultimap();
634         }
635         phaseMutation.put(phase, mutation);
636     }
637
638     @Override
639     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
640             final KT key,final StmtContext<?, ?, ?> stmt) {
641         addContextToNamespace(namespace, key, stmt);
642     }
643
644     @Override
645     public final String toString() {
646         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
647     }
648
649     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
650         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
651     }
652 }