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