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