BUG-6522: 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     /**
250      * @return collection of declared substatements
251      */
252     @Override
253     public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
254         return maybeWrap(declared);
255     }
256
257     /**
258      * @return collection of substatements
259      */
260     @Override
261     public Collection<StatementContextBase<?, ?, ?>> substatements() {
262         return maybeWrap(substatements.values());
263     }
264
265     /**
266      * @return collection of effective substatements
267      */
268     @Override
269     public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
270         return maybeWrap(effective);
271     }
272
273     public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
274         if (!effective.isEmpty()) {
275             effective.removeAll(substatements);
276             shrinkEffective();
277         }
278     }
279
280     private void shrinkEffective() {
281         if (effective.isEmpty()) {
282             effective = ImmutableList.of();
283         }
284     }
285
286     public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
287         if (effective.isEmpty()) {
288             return;
289         }
290
291         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
292         while (iterator.hasNext()) {
293             final StatementContextBase<?, ?, ?> next = iterator.next();
294             if (next.getPublicDefinition().equals(refineSubstatementDef)) {
295                 iterator.remove();
296             }
297         }
298
299         shrinkEffective();
300     }
301
302     /**
303      * adds effective statement to collection of substatements
304      *
305      * @param substatement substatement
306      * @throws IllegalStateException
307      *             if added in declared phase
308      * @throws NullPointerException
309      *             if statement parameter is null
310      */
311     public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
312         Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
313             getStatementSourceReference());
314         beforeAddEffectiveStatement(1);
315         effective.add(substatement);
316     }
317
318     /**
319      * adds effective statement to collection of substatements
320      *
321      * @param substatements substatements
322      * @throws IllegalStateException
323      *             if added in declared phase
324      * @throws NullPointerException
325      *             if statement parameter is null
326      */
327     public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
328         substatements.forEach(Preconditions::checkNotNull);
329         beforeAddEffectiveStatement(substatements.size());
330         effective.addAll(substatements);
331     }
332
333     private void beforeAddEffectiveStatement(final int toAdd) {
334         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
335         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
336                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
337                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
338
339         if (effective.isEmpty()) {
340             effective = new ArrayList<>(toAdd);
341         }
342     }
343
344     /**
345      * adds declared statement to collection of substatements
346      *
347      * @param substatement substatement
348      * @throws IllegalStateException
349      *             if added in effective phase
350      * @throws NullPointerException
351      *             if statement parameter is null
352      */
353     public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
354
355         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
356         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
357                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
358
359         if (declared.isEmpty()) {
360             declared = new ArrayList<>(1);
361         }
362         declared.add(Preconditions.checkNotNull(substatement,
363                 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
364     }
365
366     /**
367      * builds a new substatement from statement definition context and statement source reference
368      *
369      * @param def definition context
370      * @param ref source reference
371      *
372      * @return instance of ContextBuilder
373      */
374     @SuppressWarnings({ "rawtypes", "unchecked" })
375     public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
376             final StatementSourceReference ref) {
377         return new ContextBuilder(def, ref) {
378
379             @Override
380             public StatementContextBase build() throws SourceException {
381                 StatementContextBase<?, ?, ?> potential = null;
382
383                 final StatementDefinition stmtDef = getDefinition().getPublicView();
384                 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
385                         && stmtDef != Rfc6020Mapping.TYPE) {
386                     potential = substatements.get(createIdentifier());
387                 }
388                 if (potential == null) {
389                     potential = new SubstatementContext(StatementContextBase.this, this);
390                     if (substatements.isEmpty()) {
391                         substatements = new LinkedHashMap<>(1);
392                     }
393                     substatements.put(createIdentifier(), potential);
394                     getDefinition().onStatementAdded(potential);
395                 }
396                 potential.resetLists();
397                 switch (this.getStamementSource().getStatementSource()) {
398                 case DECLARATION:
399                     addDeclaredSubstatement(potential);
400                     break;
401                 case CONTEXT:
402                     addEffectiveSubstatement(potential);
403                     break;
404                 }
405                 return potential;
406             }
407         };
408     }
409
410     /**
411      * @return local namespace behaviour type {@link NamespaceBehaviour}
412      */
413     @Override
414     public StorageNodeType getStorageNodeType() {
415         return StorageNodeType.STATEMENT_LOCAL;
416     }
417
418     /**
419      * builds {@link DeclaredStatement} for statement context
420      */
421     @Override
422     public D buildDeclared() {
423         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
424                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
425         if (declaredInstance == null) {
426             declaredInstance = definition().getFactory().createDeclared(this);
427         }
428         return declaredInstance;
429     }
430
431     /**
432      * builds {@link EffectiveStatement} for statement context
433      */
434     @Override
435     public E buildEffective() {
436         if (effectiveInstance == null) {
437             effectiveInstance = definition().getFactory().createEffective(this);
438         }
439         return effectiveInstance;
440     }
441
442     /**
443      * clears collection of declared substatements
444      *
445      * @throws IllegalStateException
446      *             if invoked in effective build phase
447      */
448     void resetLists() {
449
450         final SourceSpecificContext sourceContext = getRoot().getSourceContext();
451         Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
452                 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
453
454         declared = ImmutableList.of();
455     }
456
457     /**
458      * tries to execute current {@link ModelProcessingPhase} of source parsing
459      *
460      * @param phase
461      *            to be executed (completed)
462      * @return if phase was successfully completed
463      * @throws SourceException
464      *             when an error occured in source parsing
465      */
466     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
467
468         boolean finished = true;
469         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
470         if (!openMutations.isEmpty()) {
471             final Iterator<ContextMutation> it = openMutations.iterator();
472             while (it.hasNext()) {
473                 final ContextMutation current = it.next();
474                 if (current.isFinished()) {
475                     it.remove();
476                 } else {
477                     finished = false;
478                 }
479             }
480
481             if (openMutations.isEmpty()) {
482                 phaseMutation.removeAll(phase);
483                 if (phaseMutation.isEmpty()) {
484                     phaseMutation = ImmutableMultimap.of();
485                 }
486             }
487         }
488
489         for (final StatementContextBase<?, ?, ?> child : declared) {
490             finished &= child.tryToCompletePhase(phase);
491         }
492         for (final StatementContextBase<?, ?, ?> child : effective) {
493             finished &= child.tryToCompletePhase(phase);
494         }
495
496         if (finished) {
497             onPhaseCompleted(phase);
498             return true;
499         }
500         return false;
501     }
502
503     /**
504      * occurs on end of {@link ModelProcessingPhase} of source parsing
505      *
506      * @param phase
507      *            that was to be completed (finished)
508      * @throws SourceException
509      *             when an error occured in source parsing
510      */
511     private void onPhaseCompleted(final ModelProcessingPhase phase) {
512         completedPhase = phase;
513
514         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
515         if (listeners.isEmpty()) {
516             return;
517         }
518
519         final Iterator<OnPhaseFinished> listener = listeners.iterator();
520         while (listener.hasNext()) {
521             final OnPhaseFinished next = listener.next();
522             if (next.phaseFinished(this, phase)) {
523                 listener.remove();
524             }
525         }
526
527         if (listeners.isEmpty()) {
528             phaseListeners.removeAll(phase);
529             if (phaseListeners.isEmpty()) {
530                 phaseListeners = ImmutableMultimap.of();
531             }
532         }
533     }
534
535     /**
536      * Ends declared section of current node.
537      *
538      * @param ref
539      * @throws SourceException
540      */
541     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
542         definition().onDeclarationFinished(this, phase);
543     }
544
545     /**
546      * @return statement definition
547      */
548     protected final StatementDefinitionContext<A, D, E> definition() {
549         return definition;
550     }
551
552     @Override
553     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
554         definition().checkNamespaceAllowed(type);
555     }
556
557     /**
558      * occurs when an item is added to model namespace
559      *
560      * @throws SourceException instance of SourceException
561      */
562     @Override
563     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
564         // definition().onNamespaceElementAdded(this, type, key, value);
565     }
566
567     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
568             final OnNamespaceItemAdded listener) throws SourceException {
569         final Object potential = getFromNamespace(type, key);
570         if (potential != null) {
571             listener.namespaceItemAdded(this, type, key, potential);
572             return;
573         }
574         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
575         if (behaviour instanceof NamespaceBehaviourWithListeners) {
576             final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
577             casted.addValueListener(new ValueAddedListener<K>(this, key) {
578                 @Override
579                 void onValueAdded(final Object key, final Object value) {
580                     try {
581                         listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
582                     } catch (final SourceException e) {
583                         throw Throwables.propagate(e);
584                     }
585                 }
586             });
587         }
588     }
589
590     /**
591      * @see StatementSupport#getPublicView()
592      */
593     @Override
594     public StatementDefinition getPublicDefinition() {
595         return definition().getPublicView();
596     }
597
598     /**
599      * @return new {@link ModelActionBuilder} for the phase
600      */
601     @Override
602     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
603         return getRoot().getSourceContext().newInferenceAction(phase);
604     }
605
606     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
607         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
608     }
609
610     /**
611      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
612      *
613      * @throws SourceException
614      */
615     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
616
617         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
618                 getStatementSourceReference());
619         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
620                 getStatementSourceReference());
621
622         ModelProcessingPhase finishedPhase = completedPhase;
623         while (finishedPhase != null) {
624             if (phase.equals(finishedPhase)) {
625                 listener.phaseFinished(this, finishedPhase);
626                 return;
627             }
628             finishedPhase = finishedPhase.getPreviousPhase();
629         }
630         if (phaseListeners.isEmpty()) {
631             phaseListeners = newMultimap();
632         }
633
634         phaseListeners.put(phase, listener);
635     }
636
637     /**
638      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
639      *
640      * @throws IllegalStateException
641      *             when the mutation was registered after phase was completed
642      */
643     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
644         ModelProcessingPhase finishedPhase = completedPhase;
645         while (finishedPhase != null) {
646             if (phase.equals(finishedPhase)) {
647                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
648                         getStatementSourceReference());
649             }
650             finishedPhase = finishedPhase.getPreviousPhase();
651         }
652
653         if (phaseMutation.isEmpty()) {
654             phaseMutation = newMultimap();
655         }
656         phaseMutation.put(phase, mutation);
657     }
658
659     /**
660      * adds statement to namespace map with the key
661      *
662      * @param namespace
663      *            {@link StatementNamespace} child that determines namespace to be added to
664      * @param key
665      *            of type according to namespace class specification
666      * @param stmt
667      *            to be added to namespace map
668      */
669     @Override
670     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
671             final StmtContext<?, ?, ?> stmt) {
672         addContextToNamespace(namespace, (K) key, stmt);
673     }
674
675     @Override
676     public final String toString() {
677         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
678     }
679
680     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
681         return toStringHelper.add("definition", definition).add("id", identifier);
682     }
683 }