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