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;
100 // BooleanFields value
101 private byte supportedByFeatures;
103 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
104 final String rawArgument) {
105 this.definition = Preconditions.checkNotNull(def);
106 this.statementDeclSource = Preconditions.checkNotNull(ref);
107 this.rawArgument = def.internArgument(rawArgument);
108 this.copyHistory = CopyHistory.original();
109 this.originalCtx = null;
112 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
113 this.definition = Preconditions.checkNotNull(original.definition,
114 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
115 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
116 "Statement context statementDeclSource cannot be null copying from: %s",
117 original.getStatementSourceReference());
118 this.rawArgument = original.rawArgument;
119 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
120 this.originalCtx = original.getOriginalCtx().orElse(original);
124 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
125 return effectOfStatement;
129 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
130 if (effectOfStatement.isEmpty()) {
131 effectOfStatement = new ArrayList<>(1);
133 effectOfStatement.add(ctx);
137 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
138 if (ctxs.isEmpty()) {
142 if (effectOfStatement.isEmpty()) {
143 effectOfStatement = new ArrayList<>(ctxs.size());
145 effectOfStatement.addAll(ctxs);
149 public boolean isSupportedByFeatures() {
150 if (OptionalBoolean.isPresent(supportedByFeatures)) {
151 return OptionalBoolean.get(supportedByFeatures);
154 if (isIgnoringIfFeatures()) {
155 supportedByFeatures = OptionalBoolean.of(true);
159 final boolean isParentSupported = isParentSupportedByFeatures();
161 * If parent is not supported, then this context is also not supported.
162 * So we do not need to check if-features statements of this context and
163 * we can return false immediately.
165 if (!isParentSupported) {
166 supportedByFeatures = OptionalBoolean.of(false);
171 * If parent is supported, we need to check if-features statements of
174 // If the set of supported features has not been provided, all features are supported by default.
175 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
176 SupportedFeatures.SUPPORTED_FEATURES);
177 final boolean ret = supportedFeatures == null ? true
178 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
180 supportedByFeatures = OptionalBoolean.of(ret);
184 protected abstract boolean isParentSupportedByFeatures();
186 protected abstract boolean isIgnoringIfFeatures();
188 protected abstract boolean isIgnoringConfig();
191 public boolean isSupportedToBuildEffective() {
192 return isSupportedToBuildEffective;
196 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
197 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
201 public CopyHistory getCopyHistory() {
206 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
207 return Optional.ofNullable(originalCtx);
211 public ModelProcessingPhase getCompletedPhase() {
212 return completedPhase;
216 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
217 this.completedPhase = completedPhase;
221 public abstract StatementContextBase<?, ?, ?> getParentContext();
224 * @return root context of statement
228 public abstract RootStatementContext<?, ?, ?> getRoot();
231 * @return origin of statement
235 public StatementSource getStatementSource() {
236 return statementDeclSource.getStatementSource();
240 * @return reference of statement source
244 public StatementSourceReference getStatementSourceReference() {
245 return statementDeclSource;
249 public final String rawStatementArgument() {
255 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
256 return substatements.values();
261 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
262 return substatements.values();
266 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
267 return mutableEffectiveSubstatements();
272 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
273 if (effective instanceof ImmutableCollection) {
277 return Collections.unmodifiableCollection(effective);
280 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
281 if (!effective.isEmpty()) {
282 effective.removeAll(substatements);
287 private void shrinkEffective() {
288 if (effective.isEmpty()) {
289 effective = ImmutableList.of();
293 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
294 if (effective.isEmpty()) {
298 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
299 while (iterator.hasNext()) {
300 final StmtContext<?, ?, ?> next = iterator.next();
301 if (statementDef.equals(next.getPublicDefinition())) {
310 * Removes a statement context from the effective substatements
311 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
312 * The statement context is removed only if both statement definition and statement argument match with
313 * one of the effective substatements' statement definition and argument.
315 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
317 * @param statementDef statement definition of the statement context to remove
318 * @param statementArg statement argument of the statement context to remove
320 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
321 final String statementArg) {
322 if (statementArg == null) {
323 removeStatementFromEffectiveSubstatements(statementDef);
326 if (effective.isEmpty()) {
330 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
331 while (iterator.hasNext()) {
332 final Mutable<?, ?, ?> next = iterator.next();
333 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
342 * adds effective statement to collection of substatements
344 * @param substatement substatement
345 * @throws IllegalStateException
346 * if added in declared phase
347 * @throws NullPointerException
348 * if statement parameter is null
350 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
351 beforeAddEffectiveStatement(1);
352 effective.add(substatement);
356 * adds effective statement to collection of substatements
358 * @param substatements substatements
359 * @throws IllegalStateException
360 * if added in declared phase
361 * @throws NullPointerException
362 * if statement parameter is null
364 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
365 if (substatements.isEmpty()) {
369 substatements.forEach(Preconditions::checkNotNull);
370 beforeAddEffectiveStatement(substatements.size());
371 effective.addAll(substatements);
374 private void beforeAddEffectiveStatement(final int toAdd) {
375 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
376 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
377 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
378 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
380 if (effective.isEmpty()) {
381 effective = new ArrayList<>(toAdd);
386 * Create a new substatement at the specified offset.
388 * @param offset Substatement offset
389 * @param def definition context
390 * @param ref source reference
391 * @param argument statement argument
392 * @return A new substatement
394 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
395 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
396 final String argument) {
397 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
398 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
399 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
401 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
402 offset, def, ref, argument);
403 if (implicitStatement.isPresent()) {
404 return implicitStatement.get().createSubstatement(offset, def, ref, argument);
407 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
408 substatements = substatements.put(offset, ret);
409 def.onStatementAdded(ret);
414 * Lookup substatement by its offset in this statement.
416 * @param offset Substatement offset
417 * @return Substatement, or null if substatement does not exist.
419 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
420 return substatements.get(offset);
424 public D buildDeclared() {
425 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
426 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
427 if (declaredInstance == null) {
428 declaredInstance = definition().getFactory().createDeclared(this);
430 return declaredInstance;
434 public E buildEffective() {
435 if (effectiveInstance == null) {
436 effectiveInstance = definition().getFactory().createEffective(this);
438 return effectiveInstance;
442 * tries to execute current {@link ModelProcessingPhase} of source parsing.
445 * to be executed (completed)
446 * @return if phase was successfully completed
447 * @throws SourceException
448 * when an error occured in source parsing
450 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
452 boolean finished = true;
453 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
454 if (!openMutations.isEmpty()) {
455 final Iterator<ContextMutation> it = openMutations.iterator();
456 while (it.hasNext()) {
457 final ContextMutation current = it.next();
458 if (current.isFinished()) {
465 if (openMutations.isEmpty()) {
466 phaseMutation.removeAll(phase);
467 if (phaseMutation.isEmpty()) {
468 phaseMutation = ImmutableMultimap.of();
473 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
474 finished &= child.tryToCompletePhase(phase);
476 for (final Mutable<?, ?, ?> child : effective) {
477 if (child instanceof StatementContextBase) {
478 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
483 onPhaseCompleted(phase);
490 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
493 * that was to be completed (finished)
494 * @throws SourceException
495 * when an error occurred in source parsing
497 private void onPhaseCompleted(final ModelProcessingPhase phase) {
498 completedPhase = phase;
500 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
501 if (listeners.isEmpty()) {
505 final Iterator<OnPhaseFinished> listener = listeners.iterator();
506 while (listener.hasNext()) {
507 final OnPhaseFinished next = listener.next();
508 if (next.phaseFinished(this, phase)) {
513 if (listeners.isEmpty()) {
514 phaseListeners.removeAll(phase);
515 if (phaseListeners.isEmpty()) {
516 phaseListeners = ImmutableMultimap.of();
522 * Ends declared section of current node.
525 * @throws SourceException
527 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
528 definition().onDeclarationFinished(this, phase);
532 * @return statement definition
534 protected final StatementDefinitionContext<A, D, E> definition() {
539 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
540 definition().checkNamespaceAllowed(type);
544 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
546 // definition().onNamespaceElementAdded(this, type, key, value);
549 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
550 final OnNamespaceItemAdded listener) throws SourceException {
551 final Object potential = getFromNamespace(type, key);
552 if (potential != null) {
553 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
554 listener.namespaceItemAdded(this, type, key, potential);
558 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
559 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
560 "Namespace {} does not support listeners", type);
562 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
563 casted.addValueListener(new ValueAddedListener<K>(this, key) {
565 void onValueAdded(final Object key, final Object value) {
566 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
572 * See {@link StatementSupport#getPublicView()}.
576 public StatementDefinition getPublicDefinition() {
577 return definition().getPublicView();
581 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
582 return getRoot().getSourceContext().newInferenceAction(phase);
585 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
586 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
590 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
592 * @throws SourceException
594 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
596 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
597 getStatementSourceReference());
598 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
599 getStatementSourceReference());
601 ModelProcessingPhase finishedPhase = completedPhase;
602 while (finishedPhase != null) {
603 if (phase.equals(finishedPhase)) {
604 listener.phaseFinished(this, finishedPhase);
607 finishedPhase = finishedPhase.getPreviousPhase();
609 if (phaseListeners.isEmpty()) {
610 phaseListeners = newMultimap();
613 phaseListeners.put(phase, listener);
617 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
619 * @throws IllegalStateException
620 * when the mutation was registered after phase was completed
622 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
623 ModelProcessingPhase finishedPhase = completedPhase;
624 while (finishedPhase != null) {
625 if (phase.equals(finishedPhase)) {
626 throw new IllegalStateException("Mutation registered after phase was completed at: " +
627 getStatementSourceReference());
629 finishedPhase = finishedPhase.getPreviousPhase();
632 if (phaseMutation.isEmpty()) {
633 phaseMutation = newMultimap();
635 phaseMutation.put(phase, mutation);
639 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
640 final KT key,final StmtContext<?, ?, ?> stmt) {
641 addContextToNamespace(namespace, key, stmt);
645 public final String toString() {
646 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
649 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
650 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);