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