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