Remove appendCopyHistory from public view
[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<Mutable<?, ?, ?>> 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     final void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
171         copyHistory = copyHistory.append(typeOfCopy, toAppend);
172     }
173
174     @Override
175     public StmtContext<?, ?, ?> getOriginalCtx() {
176         return originalCtx;
177     }
178
179     final void setOriginalCtx(final StmtContext<?, ?, ?> originalCtx) {
180         this.originalCtx = originalCtx;
181     }
182
183     @Override
184     public void setOrder(final int order) {
185         this.order = order;
186     }
187
188     @Override
189     public int getOrder() {
190         return order;
191     }
192
193     @Override
194     public ModelProcessingPhase getCompletedPhase() {
195         return completedPhase;
196     }
197
198     @Override
199     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
200         this.completedPhase = completedPhase;
201     }
202
203     @Override
204     public abstract StatementContextBase<?, ?, ?> getParentContext();
205
206     /**
207      * @return root context of statement
208      */
209     @Nonnull
210     @Override
211     public abstract RootStatementContext<?, ?, ?> getRoot();
212
213     /**
214      * @return origin of statement
215      */
216     @Nonnull
217     @Override
218     public StatementSource getStatementSource() {
219         return statementDeclSource.getStatementSource();
220     }
221
222     /**
223      * @return reference of statement source
224      */
225     @Nonnull
226     @Override
227     public StatementSourceReference getStatementSourceReference() {
228         return statementDeclSource;
229     }
230
231     @Override
232     public final String rawStatementArgument() {
233         return rawArgument;
234     }
235
236     @Nonnull
237     @Override
238     public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
239         return substatements.values();
240     }
241
242     @Nonnull
243     @Override
244     public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
245         return substatements.values();
246     }
247
248     @Override
249     public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
250         return mutableEffectiveSubstatements();
251     }
252
253     @Nonnull
254     @Override
255     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
256         if (effective instanceof ImmutableCollection) {
257             return effective;
258         }
259
260         return Collections.unmodifiableCollection(effective);
261     }
262
263     public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
264         if (!effective.isEmpty()) {
265             effective.removeAll(substatements);
266             shrinkEffective();
267         }
268     }
269
270     private void shrinkEffective() {
271         if (effective.isEmpty()) {
272             effective = ImmutableList.of();
273         }
274     }
275
276     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
277         if (effective.isEmpty()) {
278             return;
279         }
280
281         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
282         while (iterator.hasNext()) {
283             final StmtContext<?, ?, ?> next = iterator.next();
284             if (statementDef.equals(next.getPublicDefinition())) {
285                 iterator.remove();
286             }
287         }
288
289         shrinkEffective();
290     }
291
292     /**
293      * Removes a statement context from the effective substatements
294      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
295      * The statement context is removed only if both statement definition and statement argument match with
296      * one of the effective substatements' statement definition and argument.
297      *
298      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
299      *
300      * @param statementDef statement definition of the statement context to remove
301      * @param statementArg statement argument of the statement context to remove
302      */
303     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
304             final String statementArg) {
305         if (statementArg == null) {
306             removeStatementFromEffectiveSubstatements(statementDef);
307         }
308
309         if (effective.isEmpty()) {
310             return;
311         }
312
313         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
314         while (iterator.hasNext()) {
315             final Mutable<?, ?, ?> next = iterator.next();
316             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
317                 iterator.remove();
318             }
319         }
320
321         shrinkEffective();
322     }
323
324     /**
325      * adds effective statement to collection of substatements
326      *
327      * @param substatement substatement
328      * @throws IllegalStateException
329      *             if added in declared phase
330      * @throws NullPointerException
331      *             if statement parameter is null
332      */
333     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
334         beforeAddEffectiveStatement(1);
335         effective.add(substatement);
336     }
337
338     /**
339      * adds effective statement to collection of substatements
340      *
341      * @param substatements substatements
342      * @throws IllegalStateException
343      *             if added in declared phase
344      * @throws NullPointerException
345      *             if statement parameter is null
346      */
347     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
348         if (substatements.isEmpty()) {
349             return;
350         }
351
352         substatements.forEach(Preconditions::checkNotNull);
353         beforeAddEffectiveStatement(substatements.size());
354         effective.addAll(substatements);
355     }
356
357     private void beforeAddEffectiveStatement(final int toAdd) {
358         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
359         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
360                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
361                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
362
363         if (effective.isEmpty()) {
364             effective = new ArrayList<>(toAdd);
365         }
366     }
367
368     /**
369      * Create a new substatement at the specified offset.
370      *
371      * @param offset Substatement offset
372      * @param def definition context
373      * @param ref source reference
374      * @param argument statement argument
375      * @return A new substatement
376      */
377     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
378             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
379             final String argument) {
380         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
381         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
382                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
383
384         final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
385             offset, def, ref, argument);
386         if(implicitStatement.isPresent()) {
387             final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
388             return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
389         }
390
391         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
392         substatements = substatements.put(offset, ret);
393         def.onStatementAdded(ret);
394         return ret;
395     }
396
397     /**
398      * Lookup substatement by its offset in this statement.
399      *
400      * @param offset Substatement offset
401      * @return Substatement, or null if substatement does not exist.
402      */
403     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
404         return substatements.get(offset);
405     }
406
407     @Override
408     public D buildDeclared() {
409         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
410                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
411         if (declaredInstance == null) {
412             declaredInstance = definition().getFactory().createDeclared(this);
413         }
414         return declaredInstance;
415     }
416
417     @Override
418     public E buildEffective() {
419         if (effectiveInstance == null) {
420             effectiveInstance = definition().getFactory().createEffective(this);
421         }
422         return effectiveInstance;
423     }
424
425     /**
426      * tries to execute current {@link ModelProcessingPhase} of source parsing.
427      *
428      * @param phase
429      *            to be executed (completed)
430      * @return if phase was successfully completed
431      * @throws SourceException
432      *             when an error occured in source parsing
433      */
434     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
435
436         boolean finished = true;
437         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
438         if (!openMutations.isEmpty()) {
439             final Iterator<ContextMutation> it = openMutations.iterator();
440             while (it.hasNext()) {
441                 final ContextMutation current = it.next();
442                 if (current.isFinished()) {
443                     it.remove();
444                 } else {
445                     finished = false;
446                 }
447             }
448
449             if (openMutations.isEmpty()) {
450                 phaseMutation.removeAll(phase);
451                 if (phaseMutation.isEmpty()) {
452                     phaseMutation = ImmutableMultimap.of();
453                 }
454             }
455         }
456
457         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
458             finished &= child.tryToCompletePhase(phase);
459         }
460         for (final Mutable<?, ?, ?> child : effective) {
461             if (child instanceof StatementContextBase) {
462                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
463             }
464         }
465
466         if (finished) {
467             onPhaseCompleted(phase);
468             return true;
469         }
470         return false;
471     }
472
473     /**
474      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
475      *
476      * @param phase
477      *            that was to be completed (finished)
478      * @throws SourceException
479      *             when an error occurred in source parsing
480      */
481     private void onPhaseCompleted(final ModelProcessingPhase phase) {
482         completedPhase = phase;
483
484         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
485         if (listeners.isEmpty()) {
486             return;
487         }
488
489         final Iterator<OnPhaseFinished> listener = listeners.iterator();
490         while (listener.hasNext()) {
491             final OnPhaseFinished next = listener.next();
492             if (next.phaseFinished(this, phase)) {
493                 listener.remove();
494             }
495         }
496
497         if (listeners.isEmpty()) {
498             phaseListeners.removeAll(phase);
499             if (phaseListeners.isEmpty()) {
500                 phaseListeners = ImmutableMultimap.of();
501             }
502         }
503     }
504
505     /**
506      * Ends declared section of current node.
507      *
508      * @param ref
509      * @throws SourceException
510      */
511     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
512         definition().onDeclarationFinished(this, phase);
513     }
514
515     /**
516      * @return statement definition
517      */
518     protected final StatementDefinitionContext<A, D, E> definition() {
519         return definition;
520     }
521
522     @Override
523     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
524         definition().checkNamespaceAllowed(type);
525     }
526
527     @Override
528     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
529             final V value) {
530         // definition().onNamespaceElementAdded(this, type, key, value);
531     }
532
533     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
534             final OnNamespaceItemAdded listener) throws SourceException {
535         final Object potential = getFromNamespace(type, key);
536         if (potential != null) {
537             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
538             listener.namespaceItemAdded(this, type, key, potential);
539             return;
540         }
541
542         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
543         Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
544             "Namespace {} does not support listeners", type);
545
546         final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
547         casted.addValueListener(new ValueAddedListener<K>(this, key) {
548             @Override
549             void onValueAdded(final Object key, final Object value) {
550                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
551             }
552         });
553     }
554
555     /**
556      * See {@link StatementSupport#getPublicView()}.
557      */
558     @Nonnull
559     @Override
560     public StatementDefinition getPublicDefinition() {
561         return definition().getPublicView();
562     }
563
564     @Override
565     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
566         return getRoot().getSourceContext().newInferenceAction(phase);
567     }
568
569     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
570         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
571     }
572
573     /**
574      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
575      *
576      * @throws SourceException
577      */
578     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
579
580         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
581                 getStatementSourceReference());
582         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
583                 getStatementSourceReference());
584
585         ModelProcessingPhase finishedPhase = completedPhase;
586         while (finishedPhase != null) {
587             if (phase.equals(finishedPhase)) {
588                 listener.phaseFinished(this, finishedPhase);
589                 return;
590             }
591             finishedPhase = finishedPhase.getPreviousPhase();
592         }
593         if (phaseListeners.isEmpty()) {
594             phaseListeners = newMultimap();
595         }
596
597         phaseListeners.put(phase, listener);
598     }
599
600     /**
601      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
602      *
603      * @throws IllegalStateException
604      *             when the mutation was registered after phase was completed
605      */
606     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
607         ModelProcessingPhase finishedPhase = completedPhase;
608         while (finishedPhase != null) {
609             if (phase.equals(finishedPhase)) {
610                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
611                         getStatementSourceReference());
612             }
613             finishedPhase = finishedPhase.getPreviousPhase();
614         }
615
616         if (phaseMutation.isEmpty()) {
617             phaseMutation = newMultimap();
618         }
619         phaseMutation.put(phase, mutation);
620     }
621
622     @Override
623     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
624             final KT key,final StmtContext<?, ?, ?> stmt) {
625         addContextToNamespace(namespace, key, stmt);
626     }
627
628     @Override
629     public final String toString() {
630         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
631     }
632
633     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
634         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
635     }
636 }