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 the set of supported features has not been provided, all features are supported by default.
155 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
156 SupportedFeatures.SUPPORTED_FEATURES);
157 final boolean ret = supportedFeatures == null ? true
158 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
160 supportedByFeatures = OptionalBoolean.of(ret);
166 public boolean isSupportedToBuildEffective() {
167 return isSupportedToBuildEffective;
171 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
172 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
176 public CopyHistory getCopyHistory() {
181 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
182 return Optional.ofNullable(originalCtx);
186 public ModelProcessingPhase getCompletedPhase() {
187 return completedPhase;
191 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
192 this.completedPhase = completedPhase;
196 public abstract StatementContextBase<?, ?, ?> getParentContext();
199 * @return root context of statement
203 public abstract RootStatementContext<?, ?, ?> getRoot();
206 * @return origin of statement
210 public StatementSource getStatementSource() {
211 return statementDeclSource.getStatementSource();
215 * @return reference of statement source
219 public StatementSourceReference getStatementSourceReference() {
220 return statementDeclSource;
224 public final String rawStatementArgument() {
230 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
231 return substatements.values();
236 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
237 return substatements.values();
241 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
242 return mutableEffectiveSubstatements();
247 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
248 if (effective instanceof ImmutableCollection) {
252 return Collections.unmodifiableCollection(effective);
255 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
256 if (!effective.isEmpty()) {
257 effective.removeAll(substatements);
262 private void shrinkEffective() {
263 if (effective.isEmpty()) {
264 effective = ImmutableList.of();
268 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
269 if (effective.isEmpty()) {
273 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
274 while (iterator.hasNext()) {
275 final StmtContext<?, ?, ?> next = iterator.next();
276 if (statementDef.equals(next.getPublicDefinition())) {
285 * Removes a statement context from the effective substatements
286 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
287 * The statement context is removed only if both statement definition and statement argument match with
288 * one of the effective substatements' statement definition and argument.
290 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
292 * @param statementDef statement definition of the statement context to remove
293 * @param statementArg statement argument of the statement context to remove
295 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
296 final String statementArg) {
297 if (statementArg == null) {
298 removeStatementFromEffectiveSubstatements(statementDef);
301 if (effective.isEmpty()) {
305 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
306 while (iterator.hasNext()) {
307 final Mutable<?, ?, ?> next = iterator.next();
308 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
317 * adds effective statement to collection of substatements
319 * @param substatement substatement
320 * @throws IllegalStateException
321 * if added in declared phase
322 * @throws NullPointerException
323 * if statement parameter is null
325 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
326 beforeAddEffectiveStatement(1);
327 effective.add(substatement);
331 * adds effective statement to collection of substatements
333 * @param substatements substatements
334 * @throws IllegalStateException
335 * if added in declared phase
336 * @throws NullPointerException
337 * if statement parameter is null
339 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
340 if (substatements.isEmpty()) {
344 substatements.forEach(Preconditions::checkNotNull);
345 beforeAddEffectiveStatement(substatements.size());
346 effective.addAll(substatements);
349 private void beforeAddEffectiveStatement(final int toAdd) {
350 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
351 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
352 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
353 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
355 if (effective.isEmpty()) {
356 effective = new ArrayList<>(toAdd);
361 * Create a new substatement at the specified offset.
363 * @param offset Substatement offset
364 * @param def definition context
365 * @param ref source reference
366 * @param argument statement argument
367 * @return A new substatement
369 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
370 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
371 final String argument) {
372 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
373 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
374 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
376 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
377 offset, def, ref, argument);
378 if (implicitStatement.isPresent()) {
379 return implicitStatement.get().createSubstatement(offset, def, ref, argument);
382 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
383 substatements = substatements.put(offset, ret);
384 def.onStatementAdded(ret);
389 * Lookup substatement by its offset in this statement.
391 * @param offset Substatement offset
392 * @return Substatement, or null if substatement does not exist.
394 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
395 return substatements.get(offset);
399 public D buildDeclared() {
400 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
401 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
402 if (declaredInstance == null) {
403 declaredInstance = definition().getFactory().createDeclared(this);
405 return declaredInstance;
409 public E buildEffective() {
410 if (effectiveInstance == null) {
411 effectiveInstance = definition().getFactory().createEffective(this);
413 return effectiveInstance;
417 * tries to execute current {@link ModelProcessingPhase} of source parsing.
420 * to be executed (completed)
421 * @return if phase was successfully completed
422 * @throws SourceException
423 * when an error occured in source parsing
425 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
427 boolean finished = true;
428 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
429 if (!openMutations.isEmpty()) {
430 final Iterator<ContextMutation> it = openMutations.iterator();
431 while (it.hasNext()) {
432 final ContextMutation current = it.next();
433 if (current.isFinished()) {
440 if (openMutations.isEmpty()) {
441 phaseMutation.removeAll(phase);
442 if (phaseMutation.isEmpty()) {
443 phaseMutation = ImmutableMultimap.of();
448 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
449 finished &= child.tryToCompletePhase(phase);
451 for (final Mutable<?, ?, ?> child : effective) {
452 if (child instanceof StatementContextBase) {
453 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
458 onPhaseCompleted(phase);
465 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
468 * that was to be completed (finished)
469 * @throws SourceException
470 * when an error occurred in source parsing
472 private void onPhaseCompleted(final ModelProcessingPhase phase) {
473 completedPhase = phase;
475 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
476 if (listeners.isEmpty()) {
480 final Iterator<OnPhaseFinished> listener = listeners.iterator();
481 while (listener.hasNext()) {
482 final OnPhaseFinished next = listener.next();
483 if (next.phaseFinished(this, phase)) {
488 if (listeners.isEmpty()) {
489 phaseListeners.removeAll(phase);
490 if (phaseListeners.isEmpty()) {
491 phaseListeners = ImmutableMultimap.of();
497 * Ends declared section of current node.
500 * @throws SourceException
502 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
503 definition().onDeclarationFinished(this, phase);
507 * @return statement definition
509 protected final StatementDefinitionContext<A, D, E> definition() {
514 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
515 definition().checkNamespaceAllowed(type);
519 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
521 // definition().onNamespaceElementAdded(this, type, key, value);
524 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
525 final OnNamespaceItemAdded listener) throws SourceException {
526 final Object potential = getFromNamespace(type, key);
527 if (potential != null) {
528 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
529 listener.namespaceItemAdded(this, type, key, potential);
533 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
534 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
535 "Namespace {} does not support listeners", type);
537 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
538 casted.addValueListener(new ValueAddedListener<K>(this, key) {
540 void onValueAdded(final Object key, final Object value) {
541 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
547 * See {@link StatementSupport#getPublicView()}.
551 public StatementDefinition getPublicDefinition() {
552 return definition().getPublicView();
556 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
557 return getRoot().getSourceContext().newInferenceAction(phase);
560 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
561 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
565 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
567 * @throws SourceException
569 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
571 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
572 getStatementSourceReference());
573 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
574 getStatementSourceReference());
576 ModelProcessingPhase finishedPhase = completedPhase;
577 while (finishedPhase != null) {
578 if (phase.equals(finishedPhase)) {
579 listener.phaseFinished(this, finishedPhase);
582 finishedPhase = finishedPhase.getPreviousPhase();
584 if (phaseListeners.isEmpty()) {
585 phaseListeners = newMultimap();
588 phaseListeners.put(phase, listener);
592 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
594 * @throws IllegalStateException
595 * when the mutation was registered after phase was completed
597 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
598 ModelProcessingPhase finishedPhase = completedPhase;
599 while (finishedPhase != null) {
600 if (phase.equals(finishedPhase)) {
601 throw new IllegalStateException("Mutation registered after phase was completed at: " +
602 getStatementSourceReference());
604 finishedPhase = finishedPhase.getPreviousPhase();
607 if (phaseMutation.isEmpty()) {
608 phaseMutation = newMultimap();
610 phaseMutation.put(phase, mutation);
614 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
615 final KT key,final StmtContext<?, ?, ?> stmt) {
616 addContextToNamespace(namespace, key, stmt);
620 public final String toString() {
621 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
624 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
625 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);