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