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