Bug 6183 - Shorthand case should create case node in schema tree
[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.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableCollection;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMultimap;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multimaps;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.EnumMap;
23 import java.util.EventListener;
24 import java.util.Iterator;
25 import java.util.Optional;
26 import javax.annotation.Nonnull;
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.CopyHistory;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
40 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
41 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
42 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
43
44 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
45         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
46
47     /**
48      * event listener when an item is added to model namespace
49      */
50     interface OnNamespaceItemAdded extends EventListener {
51         /**
52          * @throws SourceException
53          */
54         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
55     }
56
57     /**
58      * event listener when a parsing {@link ModelProcessingPhase} is completed
59      */
60     interface OnPhaseFinished extends EventListener {
61         /**
62          * @throws SourceException
63          */
64         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
65     }
66
67     /**
68      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
69      */
70     interface ContextMutation {
71
72         boolean isFinished();
73     }
74
75     private final StatementDefinitionContext<A, D, E> definition;
76     private final StatementSourceReference statementDeclSource;
77     private final String rawArgument;
78
79     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
80     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
81     private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
82     private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
83     private StatementMap substatements = StatementMap.empty();
84
85     private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
86     private CopyHistory copyHistory = CopyHistory.original();
87     private boolean isSupportedToBuildEffective = true;
88     private ModelProcessingPhase completedPhase = null;
89     private StatementContextBase<?, ?, ?> originalCtx;
90     private D declaredInstance;
91     private E effectiveInstance;
92     private int order = 0;
93
94     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
95             final String rawArgument) {
96         this.definition = Preconditions.checkNotNull(def);
97         this.statementDeclSource = Preconditions.checkNotNull(ref);
98         this.rawArgument = rawArgument;
99     }
100
101     StatementContextBase(final StatementContextBase<A, D, E> original) {
102         this.definition = Preconditions.checkNotNull(original.definition,
103                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
104         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
105                 "Statement context statementDeclSource cannot be null copying from: %s",
106                 original.getStatementSourceReference());
107         this.rawArgument = original.rawArgument;
108     }
109
110     @Override
111     public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
112         return effectOfStatement;
113     }
114
115     @Override
116     public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
117         if (effectOfStatement.isEmpty()) {
118             effectOfStatement = new ArrayList<>(1);
119         }
120         effectOfStatement.add(ctx);
121     }
122
123     @Override
124     public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
125         if (ctxs.isEmpty()) {
126             return;
127         }
128
129         if (effectOfStatement.isEmpty()) {
130             effectOfStatement = new ArrayList<>(ctxs.size());
131         }
132         effectOfStatement.addAll(ctxs);
133     }
134
135     @Override
136     public SupportedByFeatures getSupportedByFeatures() {
137         return supportedByFeatures;
138     }
139
140     @Override
141     public void setSupportedByFeatures(final boolean isSupported) {
142         this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
143     }
144
145     @Override
146     public boolean isSupportedToBuildEffective() {
147         return isSupportedToBuildEffective;
148     }
149
150     @Override
151     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
152         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
153     }
154
155     @Override
156     public CopyHistory getCopyHistory() {
157         return copyHistory;
158     }
159
160     @Override
161     public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
162         copyHistory = copyHistory.append(typeOfCopy, toAppend);
163     }
164
165     @Override
166     public StatementContextBase<?, ?, ?> getOriginalCtx() {
167         return originalCtx;
168     }
169
170     @Override
171     public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
172         this.originalCtx = originalCtx;
173     }
174
175     @Override
176     public void setOrder(final int order) {
177         this.order = order;
178     }
179
180     @Override
181     public int getOrder() {
182         return order;
183     }
184
185     @Override
186     public ModelProcessingPhase getCompletedPhase() {
187         return completedPhase;
188     }
189
190     @Override
191     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
192         this.completedPhase = completedPhase;
193     }
194
195     @Override
196     public abstract StatementContextBase<?, ?, ?> getParentContext();
197
198     /**
199      * @return root context of statement
200      */
201     @Nonnull
202     @Override
203     public abstract RootStatementContext<?, ?, ?> getRoot();
204
205     /**
206      * @return origin of statement
207      */
208     @Nonnull
209     @Override
210     public StatementSource getStatementSource() {
211         return statementDeclSource.getStatementSource();
212     }
213
214     /**
215      * @return reference of statement source
216      */
217     @Nonnull
218     @Override
219     public StatementSourceReference getStatementSourceReference() {
220         return statementDeclSource;
221     }
222
223     @Override
224     public final String rawStatementArgument() {
225         return rawArgument;
226     }
227
228     @Nonnull
229     @Override
230     public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
231         return substatements.values();
232     }
233
234     @Nonnull
235     @Override
236     public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
237         if (effective instanceof ImmutableCollection) {
238             return effective;
239         }
240
241         return Collections.unmodifiableCollection(effective);
242     }
243
244     public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
245         if (!effective.isEmpty()) {
246             effective.removeAll(substatements);
247             shrinkEffective();
248         }
249     }
250
251     private void shrinkEffective() {
252         if (effective.isEmpty()) {
253             effective = ImmutableList.of();
254         }
255     }
256
257     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
258         if (effective.isEmpty()) {
259             return;
260         }
261
262         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
263         while (iterator.hasNext()) {
264             final StatementContextBase<?, ?, ?> next = iterator.next();
265             if (statementDef.equals(next.getPublicDefinition())) {
266                 iterator.remove();
267             }
268         }
269
270         shrinkEffective();
271     }
272
273     /**
274      * Removes a statement context from the effective substatements
275      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
276      * The statement context is removed only if both statement definition and statement argument match with
277      * one of the effective substatements' statement definition and argument.
278      *
279      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
280      *
281      * @param statementDef statement definition of the statement context to remove
282      * @param statementArg statement argument of the statement context to remove
283      */
284     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
285             final String statementArg) {
286         if (statementArg == null) {
287             removeStatementFromEffectiveSubstatements(statementDef);
288         }
289
290         if (effective.isEmpty()) {
291             return;
292         }
293
294         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
295         while (iterator.hasNext()) {
296             final StatementContextBase<?, ?, ?> next = iterator.next();
297             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
298                 iterator.remove();
299             }
300         }
301
302         shrinkEffective();
303     }
304
305     /**
306      * adds effective statement to collection of substatements
307      *
308      * @param substatement substatement
309      * @throws IllegalStateException
310      *             if added in declared phase
311      * @throws NullPointerException
312      *             if statement parameter is null
313      */
314     public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
315         Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
316             getStatementSourceReference());
317         beforeAddEffectiveStatement(1);
318         effective.add(substatement);
319     }
320
321     /**
322      * adds effective statement to collection of substatements
323      *
324      * @param substatements substatements
325      * @throws IllegalStateException
326      *             if added in declared phase
327      * @throws NullPointerException
328      *             if statement parameter is null
329      */
330     public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
331         if (substatements.isEmpty()) {
332             return;
333         }
334
335         substatements.forEach(Preconditions::checkNotNull);
336         beforeAddEffectiveStatement(substatements.size());
337         effective.addAll(substatements);
338     }
339
340     private void beforeAddEffectiveStatement(final int toAdd) {
341         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
342         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
343                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
344                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
345
346         if (effective.isEmpty()) {
347             effective = new ArrayList<>(toAdd);
348         }
349     }
350
351     /**
352      * Create a new substatement at the specified offset.
353      *
354      * @param offset Substatement offset
355      * @param def definition context
356      * @param ref source reference
357      * @param argument statement argument
358      * @return A new substatement
359      */
360     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
361             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
362             final String argument) {
363         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
364         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
365                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
366
367         final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this, offset, def, ref, argument);
368         if(implicitStatement.isPresent()) {
369             final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
370             return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
371         }
372
373         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
374         substatements = substatements.put(offset, ret);
375         def.onStatementAdded(ret);
376         return ret;
377     }
378
379     /**
380      * Lookup substatement by its offset in this statement.
381      *
382      * @param offset Substatement offset
383      * @return Substatement, or null if substatement does not exist.
384      */
385     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
386         return substatements.get(offset);
387     }
388
389     /**
390      * builds {@link DeclaredStatement} for statement context
391      */
392     @Override
393     public D buildDeclared() {
394         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
395                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
396         if (declaredInstance == null) {
397             declaredInstance = definition().getFactory().createDeclared(this);
398         }
399         return declaredInstance;
400     }
401
402     /**
403      * builds {@link EffectiveStatement} for statement context
404      */
405     @Override
406     public E buildEffective() {
407         if (effectiveInstance == null) {
408             effectiveInstance = definition().getFactory().createEffective(this);
409         }
410         return effectiveInstance;
411     }
412
413     /**
414      * tries to execute current {@link ModelProcessingPhase} of source parsing
415      *
416      * @param phase
417      *            to be executed (completed)
418      * @return if phase was successfully completed
419      * @throws SourceException
420      *             when an error occured in source parsing
421      */
422     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
423
424         boolean finished = true;
425         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
426         if (!openMutations.isEmpty()) {
427             final Iterator<ContextMutation> it = openMutations.iterator();
428             while (it.hasNext()) {
429                 final ContextMutation current = it.next();
430                 if (current.isFinished()) {
431                     it.remove();
432                 } else {
433                     finished = false;
434                 }
435             }
436
437             if (openMutations.isEmpty()) {
438                 phaseMutation.removeAll(phase);
439                 if (phaseMutation.isEmpty()) {
440                     phaseMutation = ImmutableMultimap.of();
441                 }
442             }
443         }
444
445         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
446             finished &= child.tryToCompletePhase(phase);
447         }
448         for (final StatementContextBase<?, ?, ?> child : effective) {
449             finished &= child.tryToCompletePhase(phase);
450         }
451
452         if (finished) {
453             onPhaseCompleted(phase);
454             return true;
455         }
456         return false;
457     }
458
459     /**
460      * Occurs on end of {@link ModelProcessingPhase} of source parsing
461      *
462      * @param phase
463      *            that was to be completed (finished)
464      * @throws SourceException
465      *             when an error occurred in source parsing
466      */
467     private void onPhaseCompleted(final ModelProcessingPhase phase) {
468         completedPhase = phase;
469
470         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
471         if (listeners.isEmpty()) {
472             return;
473         }
474
475         final Iterator<OnPhaseFinished> listener = listeners.iterator();
476         while (listener.hasNext()) {
477             final OnPhaseFinished next = listener.next();
478             if (next.phaseFinished(this, phase)) {
479                 listener.remove();
480             }
481         }
482
483         if (listeners.isEmpty()) {
484             phaseListeners.removeAll(phase);
485             if (phaseListeners.isEmpty()) {
486                 phaseListeners = ImmutableMultimap.of();
487             }
488         }
489     }
490
491     /**
492      * Ends declared section of current node.
493      *
494      * @param ref
495      * @throws SourceException
496      */
497     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
498         definition().onDeclarationFinished(this, phase);
499     }
500
501     /**
502      * @return statement definition
503      */
504     protected final StatementDefinitionContext<A, D, E> definition() {
505         return definition;
506     }
507
508     @Override
509     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
510         definition().checkNamespaceAllowed(type);
511     }
512
513     /**
514      * occurs when an item is added to model namespace
515      *
516      * @throws SourceException instance of SourceException
517      */
518     @Override
519     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
520         // definition().onNamespaceElementAdded(this, type, key, value);
521     }
522
523     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
524             final OnNamespaceItemAdded listener) throws SourceException {
525         final Object potential = getFromNamespace(type, key);
526         if (potential != null) {
527             listener.namespaceItemAdded(this, type, key, potential);
528             return;
529         }
530         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
531         if (behaviour instanceof NamespaceBehaviourWithListeners) {
532             final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
533             casted.addValueListener(new ValueAddedListener<K>(this, key) {
534                 @Override
535                 void onValueAdded(final Object key, final Object value) {
536                     try {
537                         listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
538                     } catch (final SourceException e) {
539                         throw Throwables.propagate(e);
540                     }
541                 }
542             });
543         }
544     }
545
546     /**
547      * @see StatementSupport#getPublicView()
548      */
549     @Nonnull
550     @Override
551     public StatementDefinition getPublicDefinition() {
552         return definition().getPublicView();
553     }
554
555     @Override
556     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
557         return getRoot().getSourceContext().newInferenceAction(phase);
558     }
559
560     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
561         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
562     }
563
564     /**
565      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
566      *
567      * @throws SourceException
568      */
569     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
570
571         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
572                 getStatementSourceReference());
573         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
574                 getStatementSourceReference());
575
576         ModelProcessingPhase finishedPhase = completedPhase;
577         while (finishedPhase != null) {
578             if (phase.equals(finishedPhase)) {
579                 listener.phaseFinished(this, finishedPhase);
580                 return;
581             }
582             finishedPhase = finishedPhase.getPreviousPhase();
583         }
584         if (phaseListeners.isEmpty()) {
585             phaseListeners = newMultimap();
586         }
587
588         phaseListeners.put(phase, listener);
589     }
590
591     /**
592      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
593      *
594      * @throws IllegalStateException
595      *             when the mutation was registered after phase was completed
596      */
597     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
598         ModelProcessingPhase finishedPhase = completedPhase;
599         while (finishedPhase != null) {
600             if (phase.equals(finishedPhase)) {
601                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
602                         getStatementSourceReference());
603             }
604             finishedPhase = finishedPhase.getPreviousPhase();
605         }
606
607         if (phaseMutation.isEmpty()) {
608             phaseMutation = newMultimap();
609         }
610         phaseMutation.put(phase, mutation);
611     }
612
613     /**
614      * adds statement to namespace map with the key
615      *
616      * @param namespace
617      *            {@link StatementNamespace} child that determines namespace to be added to
618      * @param key
619      *            of type according to namespace class specification
620      * @param stmt
621      *            to be added to namespace map
622      */
623     @Override
624     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
625             final StmtContext<?, ?, ?> stmt) {
626         addContextToNamespace(namespace, key, stmt);
627     }
628
629     @Override
630     public final String toString() {
631         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
632     }
633
634     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
635         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
636     }
637 }