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.Iterator;
26 import java.util.LinkedHashMap;
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> {
53 * event listener when an item is added to model namespace
55 interface OnNamespaceItemAdded extends EventListener {
57 * @throws SourceException
59 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
63 * event listener when a parsing {@link ModelProcessingPhase} is completed
65 interface OnPhaseFinished extends EventListener {
67 * @throws SourceException
69 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
73 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
75 interface ContextMutation {
80 private final StatementDefinitionContext<A, D, E> definition;
81 private final StatementIdentifier identifier;
82 private final StatementSourceReference statementDeclSource;
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();
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;
100 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
101 this.definition = builder.getDefinition();
102 this.identifier = builder.createIdentifier();
103 this.statementDeclSource = builder.getStamementSource();
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());
117 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
118 return effectOfStatement;
122 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
123 if (effectOfStatement.isEmpty()) {
124 effectOfStatement = new ArrayList<>(1);
126 effectOfStatement.add(ctx);
130 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
131 if (effectOfStatement.isEmpty()) {
132 effectOfStatement = new ArrayList<>(ctxs.size());
134 effectOfStatement.addAll(ctxs);
138 public SupportedByFeatures getSupportedByFeatures() {
139 return supportedByFeatures;
143 public void setSupportedByFeatures(final boolean isSupported) {
144 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
148 public boolean isSupportedToBuildEffective() {
149 return isSupportedToBuildEffective;
153 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
154 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
158 public CopyHistory getCopyHistory() {
163 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
164 copyHistory = copyHistory.append(typeOfCopy, toAppend);
168 public StatementContextBase<?, ?, ?> getOriginalCtx() {
173 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
174 this.originalCtx = originalCtx;
178 public void setOrder(final int order) {
183 public int getOrder() {
188 public ModelProcessingPhase getCompletedPhase() {
189 return completedPhase;
193 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
194 this.completedPhase = completedPhase;
198 * @return context of parent of statement
201 public abstract StatementContextBase<?, ?, ?> getParentContext();
204 * @return root context of statement
207 public abstract RootStatementContext<?, ?, ?> getRoot();
210 * @return statement identifier
213 public StatementIdentifier getIdentifier() {
218 * @return origin of statement
221 public StatementSource getStatementSource() {
222 return statementDeclSource.getStatementSource();
226 * @return reference of statement source
229 public StatementSourceReference getStatementSourceReference() {
230 return statementDeclSource;
234 * @return raw statement argument string
237 public String rawStatementArgument() {
238 return identifier.getArgument();
241 private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
242 if (input instanceof ImmutableCollection) {
246 return Collections.unmodifiableCollection(input);
250 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
251 return maybeWrap(declared);
255 * @return collection of all substatements
258 public Collection<StatementContextBase<?, ?, ?>> substatements() {
259 return maybeWrap(substatements.values());
263 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
264 return maybeWrap(effective);
267 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
268 if (!effective.isEmpty()) {
269 effective.removeAll(substatements);
274 private void shrinkEffective() {
275 if (effective.isEmpty()) {
276 effective = ImmutableList.of();
280 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
281 if (effective.isEmpty()) {
285 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
286 while (iterator.hasNext()) {
287 final StatementContextBase<?, ?, ?> next = iterator.next();
288 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
297 * adds effective statement to collection of substatements
299 * @param substatement substatement
300 * @throws IllegalStateException
301 * if added in declared phase
302 * @throws NullPointerException
303 * if statement parameter is null
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);
313 * adds effective statement to collection of substatements
315 * @param substatements substatements
316 * @throws IllegalStateException
317 * if added in declared phase
318 * @throws NullPointerException
319 * if statement parameter is null
321 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
322 substatements.forEach(Preconditions::checkNotNull);
323 beforeAddEffectiveStatement(substatements.size());
324 effective.addAll(substatements);
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());
333 if (effective.isEmpty()) {
334 effective = new ArrayList<>(toAdd);
339 * adds declared statement to collection of substatements
341 * @param substatement substatement
342 * @throws IllegalStateException
343 * if added in effective phase
344 * @throws NullPointerException
345 * if statement parameter is null
347 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
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());
353 if (declared.isEmpty()) {
354 declared = new ArrayList<>(1);
356 declared.add(Preconditions.checkNotNull(substatement,
357 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
361 * builds a new substatement from statement definition context and statement source reference
363 * @param def definition context
364 * @param ref source reference
366 * @return instance of ContextBuilder
368 @SuppressWarnings({ "rawtypes", "unchecked" })
369 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
370 final StatementSourceReference ref) {
371 return new ContextBuilder(def, ref) {
374 public StatementContextBase build() throws SourceException {
375 StatementContextBase<?, ?, ?> potential = null;
377 final StatementDefinition stmtDef = getDefinition().getPublicView();
378 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
379 && stmtDef != Rfc6020Mapping.TYPE) {
380 potential = substatements.get(createIdentifier());
382 if (potential == null) {
383 potential = new SubstatementContext(StatementContextBase.this, this);
384 if (substatements.isEmpty()) {
385 substatements = new LinkedHashMap<>(1);
387 substatements.put(createIdentifier(), potential);
388 getDefinition().onStatementAdded(potential);
390 potential.resetLists();
391 switch (this.getStamementSource().getStatementSource()) {
393 addDeclaredSubstatement(potential);
396 addEffectiveSubstatement(potential);
405 * @return local namespace behaviour type {@link NamespaceBehaviour}
408 public StorageNodeType getStorageNodeType() {
409 return StorageNodeType.STATEMENT_LOCAL;
413 * builds {@link DeclaredStatement} for statement context
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);
422 return declaredInstance;
426 * builds {@link EffectiveStatement} for statement context
429 public E buildEffective() {
430 if (effectiveInstance == null) {
431 effectiveInstance = definition().getFactory().createEffective(this);
433 return effectiveInstance;
437 * clears collection of declared substatements
439 * @throws IllegalStateException
440 * if invoked in effective build phase
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());
448 declared = ImmutableList.of();
452 * tries to execute current {@link ModelProcessingPhase} of source parsing
455 * to be executed (completed)
456 * @return if phase was successfully completed
457 * @throws SourceException
458 * when an error occured in source parsing
460 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
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()) {
475 if (openMutations.isEmpty()) {
476 phaseMutation.removeAll(phase);
477 if (phaseMutation.isEmpty()) {
478 phaseMutation = ImmutableMultimap.of();
483 for (final StatementContextBase<?, ?, ?> child : declared) {
484 finished &= child.tryToCompletePhase(phase);
486 for (final StatementContextBase<?, ?, ?> child : effective) {
487 finished &= child.tryToCompletePhase(phase);
491 onPhaseCompleted(phase);
498 * occurs on end of {@link ModelProcessingPhase} of source parsing
501 * that was to be completed (finished)
502 * @throws SourceException
503 * when an error occured in source parsing
505 private void onPhaseCompleted(final ModelProcessingPhase phase) {
506 completedPhase = phase;
508 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
509 if (listeners.isEmpty()) {
513 final Iterator<OnPhaseFinished> listener = listeners.iterator();
514 while (listener.hasNext()) {
515 final OnPhaseFinished next = listener.next();
516 if (next.phaseFinished(this, phase)) {
521 if (listeners.isEmpty()) {
522 phaseListeners.removeAll(phase);
523 if (phaseListeners.isEmpty()) {
524 phaseListeners = ImmutableMultimap.of();
530 * Ends declared section of current node.
533 * @throws SourceException
535 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
536 definition().onDeclarationFinished(this, phase);
540 * @return statement definition
542 protected final StatementDefinitionContext<A, D, E> definition() {
547 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
548 definition().checkNamespaceAllowed(type);
552 * occurs when an item is added to model namespace
554 * @throws SourceException instance of SourceException
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);
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);
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) {
573 void onValueAdded(final Object key, final Object value) {
575 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
576 } catch (final SourceException e) {
577 throw Throwables.propagate(e);
585 * @see StatementSupport#getPublicView()
588 public StatementDefinition getPublicDefinition() {
589 return definition().getPublicView();
593 * @return new {@link ModelActionBuilder} for the phase
596 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
597 return getRoot().getSourceContext().newInferenceAction(phase);
600 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
601 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
605 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
607 * @throws SourceException
609 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
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());
616 ModelProcessingPhase finishedPhase = completedPhase;
617 while (finishedPhase != null) {
618 if (phase.equals(finishedPhase)) {
619 listener.phaseFinished(this, finishedPhase);
622 finishedPhase = finishedPhase.getPreviousPhase();
624 if (phaseListeners.isEmpty()) {
625 phaseListeners = newMultimap();
628 phaseListeners.put(phase, listener);
632 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
634 * @throws IllegalStateException
635 * when the mutation was registered after phase was completed
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());
644 finishedPhase = finishedPhase.getPreviousPhase();
647 if (phaseMutation.isEmpty()) {
648 phaseMutation = newMultimap();
650 phaseMutation.put(phase, mutation);
654 * adds statement to namespace map with the key
657 * {@link StatementNamespace} child that determines namespace to be added to
659 * of type according to namespace class specification
661 * to be added to namespace map
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);
670 public final String toString() {
671 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
674 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
675 return toStringHelper.add("definition", definition).add("id", identifier);