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.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMultimap;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.EnumMap;
22 import java.util.EventListener;
23 import java.util.Iterator;
24 import java.util.Optional;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.util.OptionalBoolean;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
54 * event listener when an item is added to model namespace.
56 interface OnNamespaceItemAdded extends EventListener {
58 * @throws SourceException
60 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
64 * event listener when a parsing {@link ModelProcessingPhase} is completed.
66 interface OnPhaseFinished extends EventListener {
68 * @throws SourceException
70 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
74 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
76 interface ContextMutation {
81 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
83 private final StatementDefinitionContext<A, D, E> definition;
84 private final StatementSourceReference statementDeclSource;
85 private final StmtContext<?, ?, ?> originalCtx;
86 private final CopyHistory copyHistory;
87 private final String rawArgument;
89 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
90 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
91 private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
92 private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
93 private StatementMap substatements = StatementMap.empty();
95 private boolean isSupportedToBuildEffective = true;
96 private ModelProcessingPhase completedPhase = null;
97 private D declaredInstance;
98 private E effectiveInstance;
99 private int order = 0;
101 // BooleanFields value
102 private byte supportedByFeatures;
104 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
105 final String rawArgument) {
106 this.definition = Preconditions.checkNotNull(def);
107 this.statementDeclSource = Preconditions.checkNotNull(ref);
108 this.rawArgument = def.internArgument(rawArgument);
109 this.copyHistory = CopyHistory.original();
110 this.originalCtx = null;
113 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
114 this.definition = Preconditions.checkNotNull(original.definition,
115 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
116 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
117 "Statement context statementDeclSource cannot be null copying from: %s",
118 original.getStatementSourceReference());
119 this.rawArgument = original.rawArgument;
120 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
121 this.originalCtx = original.getOriginalCtx().orElse(original);
125 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
126 return effectOfStatement;
130 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
131 if (effectOfStatement.isEmpty()) {
132 effectOfStatement = new ArrayList<>(1);
134 effectOfStatement.add(ctx);
138 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
139 if (ctxs.isEmpty()) {
143 if (effectOfStatement.isEmpty()) {
144 effectOfStatement = new ArrayList<>(ctxs.size());
146 effectOfStatement.addAll(ctxs);
150 public boolean isSupportedByFeatures() {
151 if (OptionalBoolean.isPresent(supportedByFeatures)) {
152 return OptionalBoolean.get(supportedByFeatures);
155 // If the set of supported features has not been provided, all features are supported by default.
156 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
157 SupportedFeatures.SUPPORTED_FEATURES);
158 final boolean ret = supportedFeatures == null ? true
159 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
161 supportedByFeatures = OptionalBoolean.of(ret);
167 public boolean isSupportedToBuildEffective() {
168 return isSupportedToBuildEffective;
172 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
173 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
177 public CopyHistory getCopyHistory() {
182 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
183 return Optional.ofNullable(originalCtx);
187 public void setOrder(final int order) {
192 public int getOrder() {
197 public ModelProcessingPhase getCompletedPhase() {
198 return completedPhase;
202 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
203 this.completedPhase = completedPhase;
207 public abstract StatementContextBase<?, ?, ?> getParentContext();
210 * @return root context of statement
214 public abstract RootStatementContext<?, ?, ?> getRoot();
217 * @return origin of statement
221 public StatementSource getStatementSource() {
222 return statementDeclSource.getStatementSource();
226 * @return reference of statement source
230 public StatementSourceReference getStatementSourceReference() {
231 return statementDeclSource;
235 public final String rawStatementArgument() {
241 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
242 return substatements.values();
247 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
248 return substatements.values();
252 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
253 return mutableEffectiveSubstatements();
258 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
259 if (effective instanceof ImmutableCollection) {
263 return Collections.unmodifiableCollection(effective);
266 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
267 if (!effective.isEmpty()) {
268 effective.removeAll(substatements);
273 private void shrinkEffective() {
274 if (effective.isEmpty()) {
275 effective = ImmutableList.of();
279 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
280 if (effective.isEmpty()) {
284 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
285 while (iterator.hasNext()) {
286 final StmtContext<?, ?, ?> next = iterator.next();
287 if (statementDef.equals(next.getPublicDefinition())) {
296 * Removes a statement context from the effective substatements
297 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
298 * The statement context is removed only if both statement definition and statement argument match with
299 * one of the effective substatements' statement definition and argument.
301 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
303 * @param statementDef statement definition of the statement context to remove
304 * @param statementArg statement argument of the statement context to remove
306 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
307 final String statementArg) {
308 if (statementArg == null) {
309 removeStatementFromEffectiveSubstatements(statementDef);
312 if (effective.isEmpty()) {
316 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
317 while (iterator.hasNext()) {
318 final Mutable<?, ?, ?> next = iterator.next();
319 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
328 * adds effective statement to collection of substatements
330 * @param substatement substatement
331 * @throws IllegalStateException
332 * if added in declared phase
333 * @throws NullPointerException
334 * if statement parameter is null
336 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
337 beforeAddEffectiveStatement(1);
338 effective.add(substatement);
342 * adds effective statement to collection of substatements
344 * @param substatements substatements
345 * @throws IllegalStateException
346 * if added in declared phase
347 * @throws NullPointerException
348 * if statement parameter is null
350 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
351 if (substatements.isEmpty()) {
355 substatements.forEach(Preconditions::checkNotNull);
356 beforeAddEffectiveStatement(substatements.size());
357 effective.addAll(substatements);
360 private void beforeAddEffectiveStatement(final int toAdd) {
361 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
362 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
363 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
364 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
366 if (effective.isEmpty()) {
367 effective = new ArrayList<>(toAdd);
372 * Create a new substatement at the specified offset.
374 * @param offset Substatement offset
375 * @param def definition context
376 * @param ref source reference
377 * @param argument statement argument
378 * @return A new substatement
380 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
381 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
382 final String argument) {
383 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
384 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
385 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
387 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
388 offset, def, ref, argument);
389 if (implicitStatement.isPresent()) {
390 return implicitStatement.get().createSubstatement(offset, def, ref, argument);
393 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
394 substatements = substatements.put(offset, ret);
395 def.onStatementAdded(ret);
400 * Lookup substatement by its offset in this statement.
402 * @param offset Substatement offset
403 * @return Substatement, or null if substatement does not exist.
405 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
406 return substatements.get(offset);
410 public D buildDeclared() {
411 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
412 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
413 if (declaredInstance == null) {
414 declaredInstance = definition().getFactory().createDeclared(this);
416 return declaredInstance;
420 public E buildEffective() {
421 if (effectiveInstance == null) {
422 effectiveInstance = definition().getFactory().createEffective(this);
424 return effectiveInstance;
428 * tries to execute current {@link ModelProcessingPhase} of source parsing.
431 * to be executed (completed)
432 * @return if phase was successfully completed
433 * @throws SourceException
434 * when an error occured in source parsing
436 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
438 boolean finished = true;
439 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
440 if (!openMutations.isEmpty()) {
441 final Iterator<ContextMutation> it = openMutations.iterator();
442 while (it.hasNext()) {
443 final ContextMutation current = it.next();
444 if (current.isFinished()) {
451 if (openMutations.isEmpty()) {
452 phaseMutation.removeAll(phase);
453 if (phaseMutation.isEmpty()) {
454 phaseMutation = ImmutableMultimap.of();
459 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
460 finished &= child.tryToCompletePhase(phase);
462 for (final Mutable<?, ?, ?> child : effective) {
463 if (child instanceof StatementContextBase) {
464 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
469 onPhaseCompleted(phase);
476 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
479 * that was to be completed (finished)
480 * @throws SourceException
481 * when an error occurred in source parsing
483 private void onPhaseCompleted(final ModelProcessingPhase phase) {
484 completedPhase = phase;
486 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
487 if (listeners.isEmpty()) {
491 final Iterator<OnPhaseFinished> listener = listeners.iterator();
492 while (listener.hasNext()) {
493 final OnPhaseFinished next = listener.next();
494 if (next.phaseFinished(this, phase)) {
499 if (listeners.isEmpty()) {
500 phaseListeners.removeAll(phase);
501 if (phaseListeners.isEmpty()) {
502 phaseListeners = ImmutableMultimap.of();
508 * Ends declared section of current node.
511 * @throws SourceException
513 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
514 definition().onDeclarationFinished(this, phase);
518 * @return statement definition
520 protected final StatementDefinitionContext<A, D, E> definition() {
525 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
526 definition().checkNamespaceAllowed(type);
530 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
532 // definition().onNamespaceElementAdded(this, type, key, value);
535 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
536 final OnNamespaceItemAdded listener) throws SourceException {
537 final Object potential = getFromNamespace(type, key);
538 if (potential != null) {
539 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
540 listener.namespaceItemAdded(this, type, key, potential);
544 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
545 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
546 "Namespace {} does not support listeners", type);
548 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
549 casted.addValueListener(new ValueAddedListener<K>(this, key) {
551 void onValueAdded(final Object key, final Object value) {
552 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
558 * See {@link StatementSupport#getPublicView()}.
562 public StatementDefinition getPublicDefinition() {
563 return definition().getPublicView();
567 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
568 return getRoot().getSourceContext().newInferenceAction(phase);
571 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
572 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
576 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
578 * @throws SourceException
580 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
582 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
583 getStatementSourceReference());
584 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
585 getStatementSourceReference());
587 ModelProcessingPhase finishedPhase = completedPhase;
588 while (finishedPhase != null) {
589 if (phase.equals(finishedPhase)) {
590 listener.phaseFinished(this, finishedPhase);
593 finishedPhase = finishedPhase.getPreviousPhase();
595 if (phaseListeners.isEmpty()) {
596 phaseListeners = newMultimap();
599 phaseListeners.put(phase, listener);
603 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
605 * @throws IllegalStateException
606 * when the mutation was registered after phase was completed
608 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
609 ModelProcessingPhase finishedPhase = completedPhase;
610 while (finishedPhase != null) {
611 if (phase.equals(finishedPhase)) {
612 throw new IllegalStateException("Mutation registered after phase was completed at: " +
613 getStatementSourceReference());
615 finishedPhase = finishedPhase.getPreviousPhase();
618 if (phaseMutation.isEmpty()) {
619 phaseMutation = newMultimap();
621 phaseMutation.put(phase, mutation);
625 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
626 final KT key,final StmtContext<?, ?, ?> stmt) {
627 addContextToNamespace(namespace, key, stmt);
631 public final String toString() {
632 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
635 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
636 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);