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