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