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