Improve parser reactor logging
[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.base.Throwables;
14 import com.google.common.collect.ImmutableCollection;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableMultimap;
18 import com.google.common.collect.Multimap;
19 import com.google.common.collect.Multimaps;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.EnumMap;
24 import java.util.EventListener;
25 import java.util.Iterator;
26 import java.util.LinkedHashMap;
27 import java.util.Map;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.yangtools.concepts.Identifiable;
30 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
31 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
34 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
35 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
46 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
48
49 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
50         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
51
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 final StatementDefinitionContext<A, D, E> definition;
81     private final StatementIdentifier identifier;
82     private final StatementSourceReference statementDeclSource;
83
84     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
85     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
86     private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = ImmutableMap.of();
87     private Collection<StatementContextBase<?, ?, ?>> declared = ImmutableList.of();
88     private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
89     private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
90
91     private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
92     private CopyHistory copyHistory = CopyHistory.original();
93     private boolean isSupportedToBuildEffective = true;
94     private ModelProcessingPhase completedPhase = null;
95     private StatementContextBase<?, ?, ?> originalCtx;
96     private D declaredInstance;
97     private E effectiveInstance;
98     private int order = 0;
99
100     StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
101         this.definition = builder.getDefinition();
102         this.identifier = builder.createIdentifier();
103         this.statementDeclSource = builder.getStamementSource();
104     }
105
106     StatementContextBase(final StatementContextBase<A, D, E> original) {
107         this.definition = Preconditions.checkNotNull(original.definition,
108                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
109         this.identifier = Preconditions.checkNotNull(original.identifier,
110                 "Statement context identifier 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     }
115
116     @Override
117     public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
118         return effectOfStatement;
119     }
120
121     @Override
122     public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
123         if (effectOfStatement.isEmpty()) {
124             effectOfStatement = new ArrayList<>(1);
125         }
126         effectOfStatement.add(ctx);
127     }
128
129     @Override
130     public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
131         if (effectOfStatement.isEmpty()) {
132             effectOfStatement = new ArrayList<>(ctxs.size());
133         }
134         effectOfStatement.addAll(ctxs);
135     }
136
137     @Override
138     public SupportedByFeatures getSupportedByFeatures() {
139         return supportedByFeatures;
140     }
141
142     @Override
143     public void setSupportedByFeatures(final boolean isSupported) {
144         this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
145     }
146
147     @Override
148     public boolean isSupportedToBuildEffective() {
149         return isSupportedToBuildEffective;
150     }
151
152     @Override
153     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
154         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
155     }
156
157     @Override
158     public CopyHistory getCopyHistory() {
159         return copyHistory;
160     }
161
162     @Override
163     public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
164         copyHistory = copyHistory.append(typeOfCopy, toAppend);
165     }
166
167     @Override
168     public StatementContextBase<?, ?, ?> getOriginalCtx() {
169         return originalCtx;
170     }
171
172     @Override
173     public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
174         this.originalCtx = originalCtx;
175     }
176
177     @Override
178     public void setOrder(final int order) {
179         this.order = order;
180     }
181
182     @Override
183     public int getOrder() {
184         return order;
185     }
186
187     @Override
188     public ModelProcessingPhase getCompletedPhase() {
189         return completedPhase;
190     }
191
192     @Override
193     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
194         this.completedPhase = completedPhase;
195     }
196
197     /**
198      * @return context of parent of statement
199      */
200     @Override
201     public abstract StatementContextBase<?, ?, ?> getParentContext();
202
203     /**
204      * @return root context of statement
205      */
206     @Override
207     public abstract RootStatementContext<?, ?, ?> getRoot();
208
209     /**
210      * @return statement identifier
211      */
212     @Override
213     public StatementIdentifier getIdentifier() {
214         return identifier;
215     }
216
217     /**
218      * @return origin of statement
219      */
220     @Override
221     public StatementSource getStatementSource() {
222         return statementDeclSource.getStatementSource();
223     }
224
225     /**
226      * @return reference of statement source
227      */
228     @Override
229     public StatementSourceReference getStatementSourceReference() {
230         return statementDeclSource;
231     }
232
233     /**
234      * @return raw statement argument string
235      */
236     @Override
237     public String rawStatementArgument() {
238         return identifier.getArgument();
239     }
240
241     private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
242         if (input instanceof ImmutableCollection) {
243             return input;
244         }
245
246         return Collections.unmodifiableCollection(input);
247     }
248
249     @Override
250     public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
251         return maybeWrap(declared);
252     }
253
254     /**
255      * @return collection of all substatements
256      */
257     @Override
258     public Collection<StatementContextBase<?, ?, ?>> substatements() {
259         return maybeWrap(substatements.values());
260     }
261
262     @Override
263     public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
264         return maybeWrap(effective);
265     }
266
267     public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
268         if (!effective.isEmpty()) {
269             effective.removeAll(substatements);
270             shrinkEffective();
271         }
272     }
273
274     private void shrinkEffective() {
275         if (effective.isEmpty()) {
276             effective = ImmutableList.of();
277         }
278     }
279
280     public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
281         if (effective.isEmpty()) {
282             return;
283         }
284
285         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
286         while (iterator.hasNext()) {
287             final StatementContextBase<?, ?, ?> next = iterator.next();
288             if (next.getPublicDefinition().equals(refineSubstatementDef)) {
289                 iterator.remove();
290             }
291         }
292
293         shrinkEffective();
294     }
295
296     /**
297      * adds effective statement to collection of substatements
298      *
299      * @param substatement substatement
300      * @throws IllegalStateException
301      *             if added in declared phase
302      * @throws NullPointerException
303      *             if statement parameter is null
304      */
305     public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
306         Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
307             getStatementSourceReference());
308         beforeAddEffectiveStatement(1);
309         effective.add(substatement);
310     }
311
312     /**
313      * adds effective statement to collection of substatements
314      *
315      * @param substatements substatements
316      * @throws IllegalStateException
317      *             if added in declared phase
318      * @throws NullPointerException
319      *             if statement parameter is null
320      */
321     public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
322         substatements.forEach(Preconditions::checkNotNull);
323         beforeAddEffectiveStatement(substatements.size());
324         effective.addAll(substatements);
325     }
326
327     private void beforeAddEffectiveStatement(final int toAdd) {
328         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
329         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
330                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
331                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
332
333         if (effective.isEmpty()) {
334             effective = new ArrayList<>(toAdd);
335         }
336     }
337
338     /**
339      * adds declared statement to collection of substatements
340      *
341      * @param substatement substatement
342      * @throws IllegalStateException
343      *             if added in effective phase
344      * @throws NullPointerException
345      *             if statement parameter is null
346      */
347     public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
348
349         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
350         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
351                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
352
353         if (declared.isEmpty()) {
354             declared = new ArrayList<>(1);
355         }
356         declared.add(Preconditions.checkNotNull(substatement,
357                 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
358     }
359
360     /**
361      * builds a new substatement from statement definition context and statement source reference
362      *
363      * @param def definition context
364      * @param ref source reference
365      *
366      * @return instance of ContextBuilder
367      */
368     @SuppressWarnings({ "rawtypes", "unchecked" })
369     public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
370             final StatementSourceReference ref) {
371         return new ContextBuilder(def, ref) {
372
373             @Override
374             public StatementContextBase build() throws SourceException {
375                 StatementContextBase<?, ?, ?> potential = null;
376
377                 final StatementDefinition stmtDef = getDefinition().getPublicView();
378                 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
379                         && stmtDef != Rfc6020Mapping.TYPE) {
380                     potential = substatements.get(createIdentifier());
381                 }
382                 if (potential == null) {
383                     potential = new SubstatementContext(StatementContextBase.this, this);
384                     if (substatements.isEmpty()) {
385                         substatements = new LinkedHashMap<>(1);
386                     }
387                     substatements.put(createIdentifier(), potential);
388                     getDefinition().onStatementAdded(potential);
389                 }
390                 potential.resetLists();
391                 switch (this.getStamementSource().getStatementSource()) {
392                 case DECLARATION:
393                     addDeclaredSubstatement(potential);
394                     break;
395                 case CONTEXT:
396                     addEffectiveSubstatement(potential);
397                     break;
398                 }
399                 return potential;
400             }
401         };
402     }
403
404     /**
405      * @return local namespace behaviour type {@link NamespaceBehaviour}
406      */
407     @Override
408     public StorageNodeType getStorageNodeType() {
409         return StorageNodeType.STATEMENT_LOCAL;
410     }
411
412     /**
413      * builds {@link DeclaredStatement} for statement context
414      */
415     @Override
416     public D buildDeclared() {
417         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
418                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
419         if (declaredInstance == null) {
420             declaredInstance = definition().getFactory().createDeclared(this);
421         }
422         return declaredInstance;
423     }
424
425     /**
426      * builds {@link EffectiveStatement} for statement context
427      */
428     @Override
429     public E buildEffective() {
430         if (effectiveInstance == null) {
431             effectiveInstance = definition().getFactory().createEffective(this);
432         }
433         return effectiveInstance;
434     }
435
436     /**
437      * clears collection of declared substatements
438      *
439      * @throws IllegalStateException
440      *             if invoked in effective build phase
441      */
442     void resetLists() {
443
444         final SourceSpecificContext sourceContext = getRoot().getSourceContext();
445         Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
446                 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
447
448         declared = ImmutableList.of();
449     }
450
451     /**
452      * tries to execute current {@link ModelProcessingPhase} of source parsing
453      *
454      * @param phase
455      *            to be executed (completed)
456      * @return if phase was successfully completed
457      * @throws SourceException
458      *             when an error occured in source parsing
459      */
460     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
461
462         boolean finished = true;
463         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
464         if (!openMutations.isEmpty()) {
465             final Iterator<ContextMutation> it = openMutations.iterator();
466             while (it.hasNext()) {
467                 final ContextMutation current = it.next();
468                 if (current.isFinished()) {
469                     it.remove();
470                 } else {
471                     finished = false;
472                 }
473             }
474
475             if (openMutations.isEmpty()) {
476                 phaseMutation.removeAll(phase);
477                 if (phaseMutation.isEmpty()) {
478                     phaseMutation = ImmutableMultimap.of();
479                 }
480             }
481         }
482
483         for (final StatementContextBase<?, ?, ?> child : declared) {
484             finished &= child.tryToCompletePhase(phase);
485         }
486         for (final StatementContextBase<?, ?, ?> child : effective) {
487             finished &= child.tryToCompletePhase(phase);
488         }
489
490         if (finished) {
491             onPhaseCompleted(phase);
492             return true;
493         }
494         return false;
495     }
496
497     /**
498      * occurs on end of {@link ModelProcessingPhase} of source parsing
499      *
500      * @param phase
501      *            that was to be completed (finished)
502      * @throws SourceException
503      *             when an error occured in source parsing
504      */
505     private void onPhaseCompleted(final ModelProcessingPhase phase) {
506         completedPhase = phase;
507
508         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
509         if (listeners.isEmpty()) {
510             return;
511         }
512
513         final Iterator<OnPhaseFinished> listener = listeners.iterator();
514         while (listener.hasNext()) {
515             final OnPhaseFinished next = listener.next();
516             if (next.phaseFinished(this, phase)) {
517                 listener.remove();
518             }
519         }
520
521         if (listeners.isEmpty()) {
522             phaseListeners.removeAll(phase);
523             if (phaseListeners.isEmpty()) {
524                 phaseListeners = ImmutableMultimap.of();
525             }
526         }
527     }
528
529     /**
530      * Ends declared section of current node.
531      *
532      * @param ref
533      * @throws SourceException
534      */
535     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
536         definition().onDeclarationFinished(this, phase);
537     }
538
539     /**
540      * @return statement definition
541      */
542     protected final StatementDefinitionContext<A, D, E> definition() {
543         return definition;
544     }
545
546     @Override
547     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
548         definition().checkNamespaceAllowed(type);
549     }
550
551     /**
552      * occurs when an item is added to model namespace
553      *
554      * @throws SourceException instance of SourceException
555      */
556     @Override
557     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
558         // definition().onNamespaceElementAdded(this, type, key, value);
559     }
560
561     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
562             final OnNamespaceItemAdded listener) throws SourceException {
563         final Object potential = getFromNamespace(type, key);
564         if (potential != null) {
565             listener.namespaceItemAdded(this, type, key, potential);
566             return;
567         }
568         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
569         if (behaviour instanceof NamespaceBehaviourWithListeners) {
570             final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
571             casted.addValueListener(new ValueAddedListener<K>(this, key) {
572                 @Override
573                 void onValueAdded(final Object key, final Object value) {
574                     try {
575                         listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
576                     } catch (final SourceException e) {
577                         throw Throwables.propagate(e);
578                     }
579                 }
580             });
581         }
582     }
583
584     /**
585      * @see StatementSupport#getPublicView()
586      */
587     @Override
588     public StatementDefinition getPublicDefinition() {
589         return definition().getPublicView();
590     }
591
592     /**
593      * @return new {@link ModelActionBuilder} for the phase
594      */
595     @Override
596     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
597         return getRoot().getSourceContext().newInferenceAction(phase);
598     }
599
600     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
601         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
602     }
603
604     /**
605      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
606      *
607      * @throws SourceException
608      */
609     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
610
611         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
612                 getStatementSourceReference());
613         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
614                 getStatementSourceReference());
615
616         ModelProcessingPhase finishedPhase = completedPhase;
617         while (finishedPhase != null) {
618             if (phase.equals(finishedPhase)) {
619                 listener.phaseFinished(this, finishedPhase);
620                 return;
621             }
622             finishedPhase = finishedPhase.getPreviousPhase();
623         }
624         if (phaseListeners.isEmpty()) {
625             phaseListeners = newMultimap();
626         }
627
628         phaseListeners.put(phase, listener);
629     }
630
631     /**
632      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
633      *
634      * @throws IllegalStateException
635      *             when the mutation was registered after phase was completed
636      */
637     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
638         ModelProcessingPhase finishedPhase = completedPhase;
639         while (finishedPhase != null) {
640             if (phase.equals(finishedPhase)) {
641                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
642                         getStatementSourceReference());
643             }
644             finishedPhase = finishedPhase.getPreviousPhase();
645         }
646
647         if (phaseMutation.isEmpty()) {
648             phaseMutation = newMultimap();
649         }
650         phaseMutation.put(phase, mutation);
651     }
652
653     /**
654      * adds statement to namespace map with the key
655      *
656      * @param namespace
657      *            {@link StatementNamespace} child that determines namespace to be added to
658      * @param key
659      *            of type according to namespace class specification
660      * @param stmt
661      *            to be added to namespace map
662      */
663     @Override
664     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
665             final StmtContext<?, ?, ?> stmt) {
666         addContextToNamespace(namespace, (K) key, stmt);
667     }
668
669     @Override
670     public final String toString() {
671         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
672     }
673
674     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
675         return toStringHelper.add("definition", definition).add("id", identifier);
676     }
677 }