BUG-6972: eliminate StmtContext.getOrder()
[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 java.util.Set;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.util.OptionalBoolean;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
53     /**
54      * event listener when an item is added to model namespace.
55      */
56     interface OnNamespaceItemAdded extends EventListener {
57         /**
58          * @throws SourceException
59          */
60         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
61     }
62
63     /**
64      * event listener when a parsing {@link ModelProcessingPhase} is completed.
65      */
66     interface OnPhaseFinished extends EventListener {
67         /**
68          * @throws SourceException
69          */
70         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
71     }
72
73     /**
74      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
75      */
76     interface ContextMutation {
77
78         boolean isFinished();
79     }
80
81     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
82
83     private final StatementDefinitionContext<A, D, E> definition;
84     private final StatementSourceReference statementDeclSource;
85     private final StmtContext<?, ?, ?> originalCtx;
86     private final CopyHistory copyHistory;
87     private final String rawArgument;
88
89     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
90     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
91     private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
92     private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
93     private StatementMap substatements = StatementMap.empty();
94
95     private boolean isSupportedToBuildEffective = true;
96     private ModelProcessingPhase completedPhase = null;
97     private D declaredInstance;
98     private E effectiveInstance;
99
100     // BooleanFields value
101     private byte supportedByFeatures;
102
103     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
104             final String rawArgument) {
105         this.definition = Preconditions.checkNotNull(def);
106         this.statementDeclSource = Preconditions.checkNotNull(ref);
107         this.rawArgument = def.internArgument(rawArgument);
108         this.copyHistory = CopyHistory.original();
109         this.originalCtx = null;
110     }
111
112     StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
113         this.definition = Preconditions.checkNotNull(original.definition,
114                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
115         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
116                 "Statement context statementDeclSource cannot be null copying from: %s",
117                 original.getStatementSourceReference());
118         this.rawArgument = original.rawArgument;
119         this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
120         this.originalCtx = original.getOriginalCtx().orElse(original);
121     }
122
123     @Override
124     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
125         return effectOfStatement;
126     }
127
128     @Override
129     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
130         if (effectOfStatement.isEmpty()) {
131             effectOfStatement = new ArrayList<>(1);
132         }
133         effectOfStatement.add(ctx);
134     }
135
136     @Override
137     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
138         if (ctxs.isEmpty()) {
139             return;
140         }
141
142         if (effectOfStatement.isEmpty()) {
143             effectOfStatement = new ArrayList<>(ctxs.size());
144         }
145         effectOfStatement.addAll(ctxs);
146     }
147
148     @Override
149     public boolean isSupportedByFeatures() {
150         if (OptionalBoolean.isPresent(supportedByFeatures)) {
151             return OptionalBoolean.get(supportedByFeatures);
152         }
153
154         // If the set of supported features has not been provided, all features are supported by default.
155         final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
156             SupportedFeatures.SUPPORTED_FEATURES);
157         final boolean ret = supportedFeatures == null ? true
158             : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
159
160         supportedByFeatures = OptionalBoolean.of(ret);
161         return ret;
162
163     }
164
165     @Override
166     public boolean isSupportedToBuildEffective() {
167         return isSupportedToBuildEffective;
168     }
169
170     @Override
171     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
172         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
173     }
174
175     @Override
176     public CopyHistory getCopyHistory() {
177         return copyHistory;
178     }
179
180     @Override
181     public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
182         return Optional.ofNullable(originalCtx);
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<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
231         return substatements.values();
232     }
233
234     @Nonnull
235     @Override
236     public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
237         return substatements.values();
238     }
239
240     @Override
241     public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
242         return mutableEffectiveSubstatements();
243     }
244
245     @Nonnull
246     @Override
247     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
248         if (effective instanceof ImmutableCollection) {
249             return effective;
250         }
251
252         return Collections.unmodifiableCollection(effective);
253     }
254
255     public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
256         if (!effective.isEmpty()) {
257             effective.removeAll(substatements);
258             shrinkEffective();
259         }
260     }
261
262     private void shrinkEffective() {
263         if (effective.isEmpty()) {
264             effective = ImmutableList.of();
265         }
266     }
267
268     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
269         if (effective.isEmpty()) {
270             return;
271         }
272
273         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
274         while (iterator.hasNext()) {
275             final StmtContext<?, ?, ?> next = iterator.next();
276             if (statementDef.equals(next.getPublicDefinition())) {
277                 iterator.remove();
278             }
279         }
280
281         shrinkEffective();
282     }
283
284     /**
285      * Removes a statement context from the effective substatements
286      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
287      * The statement context is removed only if both statement definition and statement argument match with
288      * one of the effective substatements' statement definition and argument.
289      *
290      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
291      *
292      * @param statementDef statement definition of the statement context to remove
293      * @param statementArg statement argument of the statement context to remove
294      */
295     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
296             final String statementArg) {
297         if (statementArg == null) {
298             removeStatementFromEffectiveSubstatements(statementDef);
299         }
300
301         if (effective.isEmpty()) {
302             return;
303         }
304
305         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
306         while (iterator.hasNext()) {
307             final Mutable<?, ?, ?> next = iterator.next();
308             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
309                 iterator.remove();
310             }
311         }
312
313         shrinkEffective();
314     }
315
316     /**
317      * adds effective statement to collection of substatements
318      *
319      * @param substatement substatement
320      * @throws IllegalStateException
321      *             if added in declared phase
322      * @throws NullPointerException
323      *             if statement parameter is null
324      */
325     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
326         beforeAddEffectiveStatement(1);
327         effective.add(substatement);
328     }
329
330     /**
331      * adds effective statement to collection of substatements
332      *
333      * @param substatements substatements
334      * @throws IllegalStateException
335      *             if added in declared phase
336      * @throws NullPointerException
337      *             if statement parameter is null
338      */
339     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
340         if (substatements.isEmpty()) {
341             return;
342         }
343
344         substatements.forEach(Preconditions::checkNotNull);
345         beforeAddEffectiveStatement(substatements.size());
346         effective.addAll(substatements);
347     }
348
349     private void beforeAddEffectiveStatement(final int toAdd) {
350         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
351         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
352                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
353                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
354
355         if (effective.isEmpty()) {
356             effective = new ArrayList<>(toAdd);
357         }
358     }
359
360     /**
361      * Create a new substatement at the specified offset.
362      *
363      * @param offset Substatement offset
364      * @param def definition context
365      * @param ref source reference
366      * @param argument statement argument
367      * @return A new substatement
368      */
369     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
370             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
371             final String argument) {
372         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
373         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
374                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
375
376         final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
377             offset, def, ref, argument);
378         if (implicitStatement.isPresent()) {
379             return implicitStatement.get().createSubstatement(offset, def, ref, argument);
380         }
381
382         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
383         substatements = substatements.put(offset, ret);
384         def.onStatementAdded(ret);
385         return ret;
386     }
387
388     /**
389      * Lookup substatement by its offset in this statement.
390      *
391      * @param offset Substatement offset
392      * @return Substatement, or null if substatement does not exist.
393      */
394     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
395         return substatements.get(offset);
396     }
397
398     @Override
399     public D buildDeclared() {
400         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
401                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
402         if (declaredInstance == null) {
403             declaredInstance = definition().getFactory().createDeclared(this);
404         }
405         return declaredInstance;
406     }
407
408     @Override
409     public E buildEffective() {
410         if (effectiveInstance == null) {
411             effectiveInstance = definition().getFactory().createEffective(this);
412         }
413         return effectiveInstance;
414     }
415
416     /**
417      * tries to execute current {@link ModelProcessingPhase} of source parsing.
418      *
419      * @param phase
420      *            to be executed (completed)
421      * @return if phase was successfully completed
422      * @throws SourceException
423      *             when an error occured in source parsing
424      */
425     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
426
427         boolean finished = true;
428         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
429         if (!openMutations.isEmpty()) {
430             final Iterator<ContextMutation> it = openMutations.iterator();
431             while (it.hasNext()) {
432                 final ContextMutation current = it.next();
433                 if (current.isFinished()) {
434                     it.remove();
435                 } else {
436                     finished = false;
437                 }
438             }
439
440             if (openMutations.isEmpty()) {
441                 phaseMutation.removeAll(phase);
442                 if (phaseMutation.isEmpty()) {
443                     phaseMutation = ImmutableMultimap.of();
444                 }
445             }
446         }
447
448         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
449             finished &= child.tryToCompletePhase(phase);
450         }
451         for (final Mutable<?, ?, ?> child : effective) {
452             if (child instanceof StatementContextBase) {
453                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
454             }
455         }
456
457         if (finished) {
458             onPhaseCompleted(phase);
459             return true;
460         }
461         return false;
462     }
463
464     /**
465      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
466      *
467      * @param phase
468      *            that was to be completed (finished)
469      * @throws SourceException
470      *             when an error occurred in source parsing
471      */
472     private void onPhaseCompleted(final ModelProcessingPhase phase) {
473         completedPhase = phase;
474
475         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
476         if (listeners.isEmpty()) {
477             return;
478         }
479
480         final Iterator<OnPhaseFinished> listener = listeners.iterator();
481         while (listener.hasNext()) {
482             final OnPhaseFinished next = listener.next();
483             if (next.phaseFinished(this, phase)) {
484                 listener.remove();
485             }
486         }
487
488         if (listeners.isEmpty()) {
489             phaseListeners.removeAll(phase);
490             if (phaseListeners.isEmpty()) {
491                 phaseListeners = ImmutableMultimap.of();
492             }
493         }
494     }
495
496     /**
497      * Ends declared section of current node.
498      *
499      * @param ref
500      * @throws SourceException
501      */
502     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
503         definition().onDeclarationFinished(this, phase);
504     }
505
506     /**
507      * @return statement definition
508      */
509     protected final StatementDefinitionContext<A, D, E> definition() {
510         return definition;
511     }
512
513     @Override
514     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
515         definition().checkNamespaceAllowed(type);
516     }
517
518     @Override
519     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
520             final V value) {
521         // definition().onNamespaceElementAdded(this, type, key, value);
522     }
523
524     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
525             final OnNamespaceItemAdded listener) throws SourceException {
526         final Object potential = getFromNamespace(type, key);
527         if (potential != null) {
528             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
529             listener.namespaceItemAdded(this, type, key, potential);
530             return;
531         }
532
533         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
534         Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
535             "Namespace {} does not support listeners", type);
536
537         final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
538         casted.addValueListener(new ValueAddedListener<K>(this, key) {
539             @Override
540             void onValueAdded(final Object key, final Object value) {
541                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
542             }
543         });
544     }
545
546     /**
547      * See {@link 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     @Override
614     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
615             final KT key,final StmtContext<?, ?, ?> stmt) {
616         addContextToNamespace(namespace, key, stmt);
617     }
618
619     @Override
620     public final String toString() {
621         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
622     }
623
624     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
625         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
626     }
627 }