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