BUG-7052: reduce StatementContextBase proliferation
[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.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
42 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
46 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
51         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
52     /**
53      * event listener when an item is added to model namespace.
54      */
55     interface OnNamespaceItemAdded extends EventListener {
56         /**
57          * @throws SourceException
58          */
59         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
60     }
61
62     /**
63      * event listener when a parsing {@link ModelProcessingPhase} is completed.
64      */
65     interface OnPhaseFinished extends EventListener {
66         /**
67          * @throws SourceException
68          */
69         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
70     }
71
72     /**
73      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
74      */
75     interface ContextMutation {
76
77         boolean isFinished();
78     }
79
80     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
81
82     private final StatementDefinitionContext<A, D, E> definition;
83     private final StatementSourceReference statementDeclSource;
84     private final String rawArgument;
85
86     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
87     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
88     private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
89     private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
90     private StatementMap substatements = StatementMap.empty();
91
92     private Boolean supportedByFeatures = null;
93     private CopyHistory copyHistory = CopyHistory.original();
94     private boolean isSupportedToBuildEffective = true;
95     private ModelProcessingPhase completedPhase = null;
96     private StmtContext<?, ?, ?> originalCtx;
97     private D declaredInstance;
98     private E effectiveInstance;
99     private int order = 0;
100
101     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
102             final String rawArgument) {
103         this.definition = Preconditions.checkNotNull(def);
104         this.statementDeclSource = Preconditions.checkNotNull(ref);
105         this.rawArgument = def.internArgument(rawArgument);
106     }
107
108     StatementContextBase(final StatementContextBase<A, D, E> original) {
109         this.definition = Preconditions.checkNotNull(original.definition,
110                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
111         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
112                 "Statement context statementDeclSource cannot be null copying from: %s",
113                 original.getStatementSourceReference());
114         this.rawArgument = original.rawArgument;
115     }
116
117     @Override
118     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
119         return effectOfStatement;
120     }
121
122     @Override
123     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
124         if (effectOfStatement.isEmpty()) {
125             effectOfStatement = new ArrayList<>(1);
126         }
127         effectOfStatement.add(ctx);
128     }
129
130     @Override
131     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
132         if (ctxs.isEmpty()) {
133             return;
134         }
135
136         if (effectOfStatement.isEmpty()) {
137             effectOfStatement = new ArrayList<>(ctxs.size());
138         }
139         effectOfStatement.addAll(ctxs);
140     }
141
142     @Override
143     public boolean isSupportedByFeatures() {
144         if (supportedByFeatures == null) {
145             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
146                 SupportedFeatures.SUPPORTED_FEATURES);
147             // If the set of supported features has not been provided, all features are supported by default.
148             supportedByFeatures = supportedFeatures == null ? Boolean.TRUE
149                     : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
150         }
151
152         return supportedByFeatures.booleanValue();
153     }
154
155     @Override
156     public boolean isSupportedToBuildEffective() {
157         return isSupportedToBuildEffective;
158     }
159
160     @Override
161     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
162         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
163     }
164
165     @Override
166     public CopyHistory getCopyHistory() {
167         return copyHistory;
168     }
169
170     @Override
171     public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
172         copyHistory = copyHistory.append(typeOfCopy, toAppend);
173     }
174
175     @Override
176     public StmtContext<?, ?, ?> getOriginalCtx() {
177         return originalCtx;
178     }
179
180     @Override
181     public void setOriginalCtx(final StmtContext<?, ?, ?> originalCtx) {
182         this.originalCtx = originalCtx;
183     }
184
185     @Override
186     public void setOrder(final int order) {
187         this.order = order;
188     }
189
190     @Override
191     public int getOrder() {
192         return order;
193     }
194
195     @Override
196     public ModelProcessingPhase getCompletedPhase() {
197         return completedPhase;
198     }
199
200     @Override
201     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
202         this.completedPhase = completedPhase;
203     }
204
205     @Override
206     public abstract StatementContextBase<?, ?, ?> getParentContext();
207
208     /**
209      * @return root context of statement
210      */
211     @Nonnull
212     @Override
213     public abstract RootStatementContext<?, ?, ?> getRoot();
214
215     /**
216      * @return origin of statement
217      */
218     @Nonnull
219     @Override
220     public StatementSource getStatementSource() {
221         return statementDeclSource.getStatementSource();
222     }
223
224     /**
225      * @return reference of statement source
226      */
227     @Nonnull
228     @Override
229     public StatementSourceReference getStatementSourceReference() {
230         return statementDeclSource;
231     }
232
233     @Override
234     public final String rawStatementArgument() {
235         return rawArgument;
236     }
237
238     @Nonnull
239     @Override
240     public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
241         return substatements.values();
242     }
243
244     @Nonnull
245     @Override
246     public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
247         if (effective instanceof ImmutableCollection) {
248             return effective;
249         }
250
251         return Collections.unmodifiableCollection(effective);
252     }
253
254     public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
255         if (!effective.isEmpty()) {
256             effective.removeAll(substatements);
257             shrinkEffective();
258         }
259     }
260
261     private void shrinkEffective() {
262         if (effective.isEmpty()) {
263             effective = ImmutableList.of();
264         }
265     }
266
267     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
268         if (effective.isEmpty()) {
269             return;
270         }
271
272         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
273         while (iterator.hasNext()) {
274             final StatementContextBase<?, ?, ?> next = iterator.next();
275             if (statementDef.equals(next.getPublicDefinition())) {
276                 iterator.remove();
277             }
278         }
279
280         shrinkEffective();
281     }
282
283     /**
284      * Removes a statement context from the effective substatements
285      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
286      * The statement context is removed only if both statement definition and statement argument match with
287      * one of the effective substatements' statement definition and argument.
288      *
289      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
290      *
291      * @param statementDef statement definition of the statement context to remove
292      * @param statementArg statement argument of the statement context to remove
293      */
294     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
295             final String statementArg) {
296         if (statementArg == null) {
297             removeStatementFromEffectiveSubstatements(statementDef);
298         }
299
300         if (effective.isEmpty()) {
301             return;
302         }
303
304         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
305         while (iterator.hasNext()) {
306             final StatementContextBase<?, ?, ?> next = iterator.next();
307             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
308                 iterator.remove();
309             }
310         }
311
312         shrinkEffective();
313     }
314
315     /**
316      * adds effective statement to collection of substatements
317      *
318      * @param substatement substatement
319      * @throws IllegalStateException
320      *             if added in declared phase
321      * @throws NullPointerException
322      *             if statement parameter is null
323      */
324     public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
325         Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
326             getStatementSourceReference());
327         beforeAddEffectiveStatement(1);
328         effective.add(substatement);
329     }
330
331     /**
332      * adds effective statement to collection of substatements
333      *
334      * @param substatements substatements
335      * @throws IllegalStateException
336      *             if added in declared phase
337      * @throws NullPointerException
338      *             if statement parameter is null
339      */
340     public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
341         if (substatements.isEmpty()) {
342             return;
343         }
344
345         substatements.forEach(Preconditions::checkNotNull);
346         beforeAddEffectiveStatement(substatements.size());
347         effective.addAll(substatements);
348     }
349
350     private void beforeAddEffectiveStatement(final int toAdd) {
351         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
352         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
353                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
354                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
355
356         if (effective.isEmpty()) {
357             effective = new ArrayList<>(toAdd);
358         }
359     }
360
361     /**
362      * Create a new substatement at the specified offset.
363      *
364      * @param offset Substatement offset
365      * @param def definition context
366      * @param ref source reference
367      * @param argument statement argument
368      * @return A new substatement
369      */
370     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
371             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
372             final String argument) {
373         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
374         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
375                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
376
377         final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
378             offset, def, ref, argument);
379         if(implicitStatement.isPresent()) {
380             final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
381             return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
382         }
383
384         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
385         substatements = substatements.put(offset, ret);
386         def.onStatementAdded(ret);
387         return ret;
388     }
389
390     /**
391      * Lookup substatement by its offset in this statement.
392      *
393      * @param offset Substatement offset
394      * @return Substatement, or null if substatement does not exist.
395      */
396     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
397         return substatements.get(offset);
398     }
399
400     @Override
401     public D buildDeclared() {
402         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
403                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
404         if (declaredInstance == null) {
405             declaredInstance = definition().getFactory().createDeclared(this);
406         }
407         return declaredInstance;
408     }
409
410     @Override
411     public E buildEffective() {
412         if (effectiveInstance == null) {
413             effectiveInstance = definition().getFactory().createEffective(this);
414         }
415         return effectiveInstance;
416     }
417
418     /**
419      * tries to execute current {@link ModelProcessingPhase} of source parsing.
420      *
421      * @param phase
422      *            to be executed (completed)
423      * @return if phase was successfully completed
424      * @throws SourceException
425      *             when an error occured in source parsing
426      */
427     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
428
429         boolean finished = true;
430         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
431         if (!openMutations.isEmpty()) {
432             final Iterator<ContextMutation> it = openMutations.iterator();
433             while (it.hasNext()) {
434                 final ContextMutation current = it.next();
435                 if (current.isFinished()) {
436                     it.remove();
437                 } else {
438                     finished = false;
439                 }
440             }
441
442             if (openMutations.isEmpty()) {
443                 phaseMutation.removeAll(phase);
444                 if (phaseMutation.isEmpty()) {
445                     phaseMutation = ImmutableMultimap.of();
446                 }
447             }
448         }
449
450         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
451             finished &= child.tryToCompletePhase(phase);
452         }
453         for (final StatementContextBase<?, ?, ?> child : effective) {
454             finished &= child.tryToCompletePhase(phase);
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 }