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