Merge "Make sure YangInstanceIdentifier.EMPTY is retained"
[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.HashMultimap;
13 import com.google.common.collect.Multimap;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.EventListener;
18 import java.util.Iterator;
19 import java.util.LinkedHashMap;
20 import javax.annotation.Nonnull;
21 import org.opendaylight.yangtools.concepts.Identifiable;
22 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
23 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
25 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
33 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
34 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
35 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
36
37 abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
38         NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
39
40     interface OnNamespaceItemAdded extends EventListener{
41
42         void namespaceItemAdded(StatementContextBase<?,?,?> context, Class<?> namespace, Object key, Object value) throws SourceException;
43
44     }
45
46     interface OnPhaseFinished extends EventListener{
47
48         void phaseFinished(StatementContextBase<?,?,?> context, ModelProcessingPhase phase) throws SourceException;
49
50     }
51
52     interface ContextMutation {
53
54         boolean isFinished();
55
56     }
57
58     abstract static class ContextBuilder<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> {
59
60         private final StatementDefinitionContext<A, D, E> definition;
61         private final StatementSourceReference stmtRef;
62         private String rawArg;
63         private StatementSourceReference argRef;
64
65         public ContextBuilder(StatementDefinitionContext<A, D, E> def, StatementSourceReference sourceRef) {
66             this.definition = def;
67             this.stmtRef = sourceRef;
68         }
69
70         public void setArgument(@Nonnull String argument, @Nonnull StatementSourceReference argumentSource) {
71             Preconditions.checkArgument(definition.hasArgument(), "Statement does not take argument.");
72             this.rawArg = Preconditions.checkNotNull(argument);
73             this.argRef = Preconditions.checkNotNull(argumentSource);
74         }
75
76         public String getRawArgument() {
77             return rawArg;
78         }
79
80         public StatementSourceReference getStamementSource() {
81             return stmtRef;
82         }
83
84         public StatementSourceReference getArgumentSource() {
85             return argRef;
86         }
87
88         public StatementDefinitionContext<A, D, E> getDefinition() {
89             return definition;
90         }
91
92         public StatementIdentifier getIdentifier() {
93             return new StatementIdentifier(definition.getStatementName(), rawArg);
94         }
95
96         public abstract StatementContextBase<A, D, E> build() throws SourceException;
97
98     }
99
100     private final StatementDefinitionContext<A, D, E> definition;
101     private final StatementIdentifier identifier;
102     private final StatementSourceReference statementDeclSource;
103     private final A argument;
104
105     private LinkedHashMap<StatementIdentifier, StatementContextBase<?, ?, ?> > substatements = new LinkedHashMap<>();
106
107     private Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
108     private Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
109
110     private ModelProcessingPhase completedPhase;
111
112     private Multimap<ModelProcessingPhase,OnPhaseFinished> phaseListeners = HashMultimap.create();
113     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = HashMultimap.create();
114
115     private D declaredInstance;
116     private E effectiveInstance;
117
118
119     StatementContextBase(@Nonnull ContextBuilder<A, D, E> builder) throws SourceException {
120         this.definition = builder.getDefinition();
121         this.identifier = builder.getIdentifier();
122         this.statementDeclSource = builder.getStamementSource();
123         this.argument = definition.parseArgumentValue(this, this.rawStatementArgument());
124         this.completedPhase = null;
125     }
126
127     @Override
128     public abstract StatementContextBase<?, ?, ?> getParentContext();
129
130     @Override
131     public abstract RootStatementContext<?, ?, ?> getRoot();
132
133
134     @Override
135     public StatementIdentifier getIdentifier() {
136         return identifier;
137     }
138
139     @Override
140     public StatementSource getStatementSource() {
141         return statementDeclSource.getStatementSource();
142     }
143
144     @Override
145     public StatementSourceReference getStatementSourceReference() {
146         return statementDeclSource;
147     }
148
149     @Override
150     public String rawStatementArgument() {
151         return identifier.getArgument();
152     }
153
154     @Override
155     public A getStatementArgument() {
156         return argument;
157     }
158
159     @Override
160     public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
161         return Collections.unmodifiableCollection(declared);
162     }
163
164     @SuppressWarnings({ "rawtypes", "unchecked" })
165     public ContextBuilder<?, ?, ?> substatementBuilder(StatementDefinitionContext<?, ?, ?> def,
166             StatementSourceReference ref) {
167         return new ContextBuilder(def, ref) {
168
169             @Override
170             public StatementContextBase build() throws SourceException {
171                 StatementContextBase<?, ?, ?> potential = substatements.get(getIdentifier());
172                 if(potential == null) {
173                     potential = new SubstatementContext(StatementContextBase.this, this);
174                     substatements.put(getIdentifier(), potential);
175                 }
176                 potential.resetLists();
177                 switch (this.getStamementSource().getStatementSource()) {
178                     case DECLARATION:
179                         declared.add(potential);
180                         break;
181                     case CONTEXT:
182                         effective.add(potential);
183                         break;
184                 }
185                 return potential;
186             }
187         };
188     }
189
190     @Override
191     public StorageNodeType getStorageNodeType() {
192         return StorageNodeType.StatementLocal;
193     }
194
195     @Override
196     public D buildDeclared() {
197         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FullDeclaration || completedPhase == ModelProcessingPhase.EffectiveModel);
198         if (declaredInstance == null) {
199             declaredInstance = definition().getFactory().createDeclared(this);
200         }
201         return declaredInstance;
202     }
203
204     @Override
205     public E buildEffective() {
206         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.EffectiveModel);
207         if (effectiveInstance == null) {
208             effectiveInstance = definition().getFactory().createEffective(this);
209         }
210         return effectiveInstance;
211     }
212
213
214     void resetLists() {
215         declared.clear();
216     }
217
218     boolean tryToCompletePhase(ModelProcessingPhase phase) throws SourceException {
219         if(phase.equals(completedPhase)) {
220             return true;
221         }
222         Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
223         boolean finished = true;
224         while(openMutations.hasNext()) {
225             ContextMutation current = openMutations.next();
226             if(current.isFinished()) {
227                 openMutations.remove();
228             } else {
229                 finished = false;
230             }
231         }
232         for(StatementContextBase<?, ?, ?> child: declared) {
233             finished &= child.tryToCompletePhase(phase);
234         }
235         if(finished) {
236             onPhaseCompleted(phase);
237             return true;
238         }
239         return false;
240     }
241
242
243     private void onPhaseCompleted(ModelProcessingPhase phase) throws SourceException {
244         completedPhase = phase;
245         Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
246         while(listener.hasNext()) {
247             listener.next().phaseFinished(this, phase);
248             listener.remove();
249         }
250     }
251
252     /**
253      *
254      * Ends declared section of current node.
255      *
256      * @param ref
257      * @throws SourceException
258      *
259      */
260     void endDeclared(StatementSourceReference ref,ModelProcessingPhase phase) throws SourceException {
261         definition().onDeclarationFinished(this,phase);
262     }
263
264     protected final StatementDefinitionContext<A, D, E> definition() {
265         return definition;
266     }
267
268     @Override
269     protected void checkLocalNamespaceAllowed(Class<? extends IdentifierNamespace<?, ?>> type) {
270         definition().checkNamespaceAllowed(type);
271     }
272
273     @Override
274     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(Class<N> type, K key, V value) {
275         //definition().onNamespaceElementAdded(this, type, key, value);
276     }
277
278     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, K key, final OnNamespaceItemAdded listener) throws SourceException {
279         Object potential = getFromNamespace(type, key);
280         if(potential != null) {
281             listener.namespaceItemAdded(this, type, key, potential);
282             return;
283         }
284         NamespaceBehaviour<K,V,N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
285         if(behaviour instanceof NamespaceBehaviourWithListeners) {
286             NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K,V,N>) behaviour;
287             casted.addValueListener(key, new ValueAddedListener(this) {
288                 @Override
289                 void onValueAdded(Object key, Object value) {
290                     try {
291                         listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
292                     } catch (SourceException e) {
293                         throw Throwables.propagate(e);
294                     }
295                 }
296             });
297         }
298     }
299
300     @Override
301     public StatementDefinition getPublicDefinition() {
302         return definition().getPublicView();
303     }
304
305     @Override
306     public ModelActionBuilder newInferenceAction(ModelProcessingPhase phase) {
307         return getRoot().getSourceContext().newInferenceAction(phase);
308     }
309
310     void addPhaseCompletedListener(ModelProcessingPhase phase, OnPhaseFinished listener) throws SourceException {
311         ModelProcessingPhase finishedPhase = completedPhase;
312         while (finishedPhase != null) {
313             if(phase.equals(finishedPhase)) {
314                 listener.phaseFinished(this, finishedPhase);
315                 return;
316             }
317             finishedPhase = finishedPhase.getPreviousPhase();
318         }
319         phaseListeners.put(phase, listener);
320     }
321
322     void addMutation(ModelProcessingPhase phase, ContextMutation mutation) {
323         ModelProcessingPhase finishedPhase = completedPhase;
324         while (finishedPhase != null) {
325             if(phase.equals(finishedPhase)) {
326                 throw new IllegalStateException("Mutation registered after phase was completed.");
327             }
328             finishedPhase = finishedPhase.getPreviousPhase();
329         }
330         phaseMutation.put(phase, mutation);
331     }
332
333     @Override
334     public <K,KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(
335             Class<N> namepsace, KT key, StmtContext<?, ?, ?> stmt) {
336         addContextToNamespace(namepsace,(K) key, stmt);
337     }
338 }