2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
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.HashMap;
26 import java.util.Iterator;
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;
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> {
52 @SuppressWarnings({ "rawtypes", "unchecked" })
53 private final class SubContextBuilder extends ContextBuilder {
54 SubContextBuilder(final StatementDefinitionContext def, final StatementSourceReference sourceRef) {
55 super(def, sourceRef);
59 public StatementContextBase build() {
60 StatementContextBase<?, ?, ?> potential = null;
62 final StatementDefinition stmtDef = getDefinition().getPublicView();
63 // FIXME: this is rather ugly. Rather than having an explicit blacklist, StatementDefinitionContext should
64 // give us information whether we should really bother with the substatements map.
65 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
66 && stmtDef != Rfc6020Mapping.IMPORT && stmtDef != Rfc6020Mapping.TYPE) {
67 potential = substatements.get(createIdentifier());
69 if (potential == null) {
70 potential = new SubstatementContext(StatementContextBase.this, this);
71 if (substatements.isEmpty()) {
72 substatements = new HashMap<>(1);
74 substatements.put(createIdentifier(), potential);
75 getDefinition().onStatementAdded(potential);
77 potential.resetLists();
78 switch (this.getStamementSource().getStatementSource()) {
80 addDeclaredSubstatement(potential);
83 addEffectiveSubstatement(potential);
91 * event listener when an item is added to model namespace
93 interface OnNamespaceItemAdded extends EventListener {
95 * @throws SourceException
97 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
101 * event listener when a parsing {@link ModelProcessingPhase} is completed
103 interface OnPhaseFinished extends EventListener {
105 * @throws SourceException
107 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
111 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
113 interface ContextMutation {
115 boolean isFinished();
118 private final StatementDefinitionContext<A, D, E> definition;
119 private final StatementIdentifier identifier;
120 private final StatementSourceReference statementDeclSource;
122 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
123 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
124 private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = ImmutableMap.of();
125 private Collection<StatementContextBase<?, ?, ?>> declared = ImmutableList.of();
126 private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
127 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
129 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
130 private CopyHistory copyHistory = CopyHistory.original();
131 private boolean isSupportedToBuildEffective = true;
132 private ModelProcessingPhase completedPhase = null;
133 private StatementContextBase<?, ?, ?> originalCtx;
134 private D declaredInstance;
135 private E effectiveInstance;
136 private int order = 0;
138 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
139 this.definition = builder.getDefinition();
140 this.identifier = builder.createIdentifier();
141 this.statementDeclSource = builder.getStamementSource();
144 StatementContextBase(final StatementContextBase<A, D, E> original) {
145 this.definition = Preconditions.checkNotNull(original.definition,
146 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
147 this.identifier = Preconditions.checkNotNull(original.identifier,
148 "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
149 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
150 "Statement context statementDeclSource cannot be null copying from: %s",
151 original.getStatementSourceReference());
155 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
156 return effectOfStatement;
160 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
161 if (effectOfStatement.isEmpty()) {
162 effectOfStatement = new ArrayList<>(1);
164 effectOfStatement.add(ctx);
168 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
169 if (ctxs.isEmpty()) {
173 if (effectOfStatement.isEmpty()) {
174 effectOfStatement = new ArrayList<>(ctxs.size());
176 effectOfStatement.addAll(ctxs);
180 public SupportedByFeatures getSupportedByFeatures() {
181 return supportedByFeatures;
185 public void setSupportedByFeatures(final boolean isSupported) {
186 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
190 public boolean isSupportedToBuildEffective() {
191 return isSupportedToBuildEffective;
195 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
196 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
200 public CopyHistory getCopyHistory() {
205 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
206 copyHistory = copyHistory.append(typeOfCopy, toAppend);
210 public StatementContextBase<?, ?, ?> getOriginalCtx() {
215 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
216 this.originalCtx = originalCtx;
220 public void setOrder(final int order) {
225 public int getOrder() {
230 public ModelProcessingPhase getCompletedPhase() {
231 return completedPhase;
235 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
236 this.completedPhase = completedPhase;
240 * @return context of parent of statement
243 public abstract StatementContextBase<?, ?, ?> getParentContext();
246 * @return root context of statement
249 public abstract RootStatementContext<?, ?, ?> getRoot();
252 * @return statement identifier
255 public StatementIdentifier getIdentifier() {
260 * @return origin of statement
263 public StatementSource getStatementSource() {
264 return statementDeclSource.getStatementSource();
268 * @return reference of statement source
271 public StatementSourceReference getStatementSourceReference() {
272 return statementDeclSource;
276 * @return raw statement argument string
279 public String rawStatementArgument() {
280 return identifier.getArgument();
283 private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
284 if (input instanceof ImmutableCollection) {
288 return Collections.unmodifiableCollection(input);
292 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
293 return maybeWrap(declared);
297 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
298 return maybeWrap(effective);
301 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
302 if (!effective.isEmpty()) {
303 effective.removeAll(substatements);
308 private void shrinkEffective() {
309 if (effective.isEmpty()) {
310 effective = ImmutableList.of();
314 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
315 if (effective.isEmpty()) {
319 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
320 while (iterator.hasNext()) {
321 final StatementContextBase<?, ?, ?> next = iterator.next();
322 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
331 * adds effective statement to collection of substatements
333 * @param substatement substatement
334 * @throws IllegalStateException
335 * if added in declared phase
336 * @throws NullPointerException
337 * if statement parameter is null
339 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
340 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
341 getStatementSourceReference());
342 beforeAddEffectiveStatement(1);
343 effective.add(substatement);
347 * adds effective statement to collection of substatements
349 * @param substatements substatements
350 * @throws IllegalStateException
351 * if added in declared phase
352 * @throws NullPointerException
353 * if statement parameter is null
355 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
356 if (substatements.isEmpty()) {
360 substatements.forEach(Preconditions::checkNotNull);
361 beforeAddEffectiveStatement(substatements.size());
362 effective.addAll(substatements);
365 private void beforeAddEffectiveStatement(final int toAdd) {
366 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
367 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
368 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
369 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
371 if (effective.isEmpty()) {
372 effective = new ArrayList<>(toAdd);
377 * adds declared statement to collection of substatements
379 * @param substatement substatement
380 * @throws IllegalStateException
381 * if added in effective phase
382 * @throws NullPointerException
383 * if statement parameter is null
385 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
387 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
388 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
389 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
391 if (declared.isEmpty()) {
392 declared = new ArrayList<>(1);
394 declared.add(Preconditions.checkNotNull(substatement,
395 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
399 * builds a new substatement from statement definition context and statement source reference
401 * @param def definition context
402 * @param ref source reference
404 * @return instance of ContextBuilder
406 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
407 final StatementSourceReference ref) {
408 return new SubContextBuilder(def, ref);
412 * @return local namespace behaviour type {@link NamespaceBehaviour}
415 public StorageNodeType getStorageNodeType() {
416 return StorageNodeType.STATEMENT_LOCAL;
420 * builds {@link DeclaredStatement} for statement context
423 public D buildDeclared() {
424 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
425 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
426 if (declaredInstance == null) {
427 declaredInstance = definition().getFactory().createDeclared(this);
429 return declaredInstance;
433 * builds {@link EffectiveStatement} for statement context
436 public E buildEffective() {
437 if (effectiveInstance == null) {
438 effectiveInstance = definition().getFactory().createEffective(this);
440 return effectiveInstance;
444 * clears collection of declared substatements
446 * @throws IllegalStateException
447 * if invoked in effective build phase
451 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
452 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
453 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
455 declared = ImmutableList.of();
459 * tries to execute current {@link ModelProcessingPhase} of source parsing
462 * to be executed (completed)
463 * @return if phase was successfully completed
464 * @throws SourceException
465 * when an error occured in source parsing
467 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
469 boolean finished = true;
470 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
471 if (!openMutations.isEmpty()) {
472 final Iterator<ContextMutation> it = openMutations.iterator();
473 while (it.hasNext()) {
474 final ContextMutation current = it.next();
475 if (current.isFinished()) {
482 if (openMutations.isEmpty()) {
483 phaseMutation.removeAll(phase);
484 if (phaseMutation.isEmpty()) {
485 phaseMutation = ImmutableMultimap.of();
490 for (final StatementContextBase<?, ?, ?> child : declared) {
491 finished &= child.tryToCompletePhase(phase);
493 for (final StatementContextBase<?, ?, ?> child : effective) {
494 finished &= child.tryToCompletePhase(phase);
498 onPhaseCompleted(phase);
505 * occurs on end of {@link ModelProcessingPhase} of source parsing
508 * that was to be completed (finished)
509 * @throws SourceException
510 * when an error occured in source parsing
512 private void onPhaseCompleted(final ModelProcessingPhase phase) {
513 completedPhase = phase;
515 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
516 if (listeners.isEmpty()) {
520 final Iterator<OnPhaseFinished> listener = listeners.iterator();
521 while (listener.hasNext()) {
522 final OnPhaseFinished next = listener.next();
523 if (next.phaseFinished(this, phase)) {
528 if (listeners.isEmpty()) {
529 phaseListeners.removeAll(phase);
530 if (phaseListeners.isEmpty()) {
531 phaseListeners = ImmutableMultimap.of();
537 * Ends declared section of current node.
540 * @throws SourceException
542 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
543 definition().onDeclarationFinished(this, phase);
547 * @return statement definition
549 protected final StatementDefinitionContext<A, D, E> definition() {
554 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
555 definition().checkNamespaceAllowed(type);
559 * occurs when an item is added to model namespace
561 * @throws SourceException instance of SourceException
564 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
565 // definition().onNamespaceElementAdded(this, type, key, value);
568 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
569 final OnNamespaceItemAdded listener) throws SourceException {
570 final Object potential = getFromNamespace(type, key);
571 if (potential != null) {
572 listener.namespaceItemAdded(this, type, key, potential);
575 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
576 if (behaviour instanceof NamespaceBehaviourWithListeners) {
577 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
578 casted.addValueListener(new ValueAddedListener<K>(this, key) {
580 void onValueAdded(final Object key, final Object value) {
582 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
583 } catch (final SourceException e) {
584 throw Throwables.propagate(e);
592 * @see StatementSupport#getPublicView()
595 public StatementDefinition getPublicDefinition() {
596 return definition().getPublicView();
600 * @return new {@link ModelActionBuilder} for the phase
603 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
604 return getRoot().getSourceContext().newInferenceAction(phase);
607 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
608 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
612 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
614 * @throws SourceException
616 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
618 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
619 getStatementSourceReference());
620 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
621 getStatementSourceReference());
623 ModelProcessingPhase finishedPhase = completedPhase;
624 while (finishedPhase != null) {
625 if (phase.equals(finishedPhase)) {
626 listener.phaseFinished(this, finishedPhase);
629 finishedPhase = finishedPhase.getPreviousPhase();
631 if (phaseListeners.isEmpty()) {
632 phaseListeners = newMultimap();
635 phaseListeners.put(phase, listener);
639 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
641 * @throws IllegalStateException
642 * when the mutation was registered after phase was completed
644 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
645 ModelProcessingPhase finishedPhase = completedPhase;
646 while (finishedPhase != null) {
647 if (phase.equals(finishedPhase)) {
648 throw new IllegalStateException("Mutation registered after phase was completed at: " +
649 getStatementSourceReference());
651 finishedPhase = finishedPhase.getPreviousPhase();
654 if (phaseMutation.isEmpty()) {
655 phaseMutation = newMultimap();
657 phaseMutation.put(phase, mutation);
661 * adds statement to namespace map with the key
664 * {@link StatementNamespace} child that determines namespace to be added to
666 * of type according to namespace class specification
668 * to be added to namespace map
671 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
672 final StmtContext<?, ?, ?> stmt) {
673 addContextToNamespace(namespace, key, stmt);
677 public final String toString() {
678 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
681 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
682 return toStringHelper.add("definition", definition).add("id", identifier);