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.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
42 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
46 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
51 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
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 static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
82 private final StatementDefinitionContext<A, D, E> definition;
83 private final StatementSourceReference statementDeclSource;
84 private final String rawArgument;
86 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
87 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
88 private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
89 private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
90 private StatementMap substatements = StatementMap.empty();
92 private Boolean supportedByFeatures = null;
93 private CopyHistory copyHistory = CopyHistory.original();
94 private boolean isSupportedToBuildEffective = true;
95 private ModelProcessingPhase completedPhase = null;
96 private StmtContext<?, ?, ?> originalCtx;
97 private D declaredInstance;
98 private E effectiveInstance;
99 private int order = 0;
101 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
102 final String rawArgument) {
103 this.definition = Preconditions.checkNotNull(def);
104 this.statementDeclSource = Preconditions.checkNotNull(ref);
105 this.rawArgument = def.internArgument(rawArgument);
108 StatementContextBase(final StatementContextBase<A, D, E> original) {
109 this.definition = Preconditions.checkNotNull(original.definition,
110 "Statement context definition 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());
114 this.rawArgument = original.rawArgument;
118 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
119 return effectOfStatement;
123 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
124 if (effectOfStatement.isEmpty()) {
125 effectOfStatement = new ArrayList<>(1);
127 effectOfStatement.add(ctx);
131 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
132 if (ctxs.isEmpty()) {
136 if (effectOfStatement.isEmpty()) {
137 effectOfStatement = new ArrayList<>(ctxs.size());
139 effectOfStatement.addAll(ctxs);
143 public boolean isSupportedByFeatures() {
144 if (supportedByFeatures == null) {
145 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
146 SupportedFeatures.SUPPORTED_FEATURES);
147 // If the set of supported features has not been provided, all features are supported by default.
148 supportedByFeatures = supportedFeatures == null ? Boolean.TRUE
149 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
152 return supportedByFeatures.booleanValue();
156 public boolean isSupportedToBuildEffective() {
157 return isSupportedToBuildEffective;
161 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
162 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
166 public CopyHistory getCopyHistory() {
171 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
172 copyHistory = copyHistory.append(typeOfCopy, toAppend);
176 public StmtContext<?, ?, ?> getOriginalCtx() {
181 public void setOriginalCtx(final StmtContext<?, ?, ?> originalCtx) {
182 this.originalCtx = originalCtx;
186 public void setOrder(final int order) {
191 public int getOrder() {
196 public ModelProcessingPhase getCompletedPhase() {
197 return completedPhase;
201 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
202 this.completedPhase = completedPhase;
206 public abstract StatementContextBase<?, ?, ?> getParentContext();
209 * @return root context of statement
213 public abstract RootStatementContext<?, ?, ?> getRoot();
216 * @return origin of statement
220 public StatementSource getStatementSource() {
221 return statementDeclSource.getStatementSource();
225 * @return reference of statement source
229 public StatementSourceReference getStatementSourceReference() {
230 return statementDeclSource;
234 public final String rawStatementArgument() {
240 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
241 return substatements.values();
246 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
247 return substatements.values();
251 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
252 return mutableEffectiveSubstatements();
257 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
258 if (effective instanceof ImmutableCollection) {
262 return Collections.unmodifiableCollection(effective);
265 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
266 if (!effective.isEmpty()) {
267 effective.removeAll(substatements);
272 private void shrinkEffective() {
273 if (effective.isEmpty()) {
274 effective = ImmutableList.of();
278 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
279 if (effective.isEmpty()) {
283 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
284 while (iterator.hasNext()) {
285 final StmtContext<?, ?, ?> next = iterator.next();
286 if (statementDef.equals(next.getPublicDefinition())) {
295 * Removes a statement context from the effective substatements
296 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
297 * The statement context is removed only if both statement definition and statement argument match with
298 * one of the effective substatements' statement definition and argument.
300 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
302 * @param statementDef statement definition of the statement context to remove
303 * @param statementArg statement argument of the statement context to remove
305 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
306 final String statementArg) {
307 if (statementArg == null) {
308 removeStatementFromEffectiveSubstatements(statementDef);
311 if (effective.isEmpty()) {
315 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
316 while (iterator.hasNext()) {
317 final Mutable<?, ?, ?> next = iterator.next();
318 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
327 * adds effective statement to collection of substatements
329 * @param substatement substatement
330 * @throws IllegalStateException
331 * if added in declared phase
332 * @throws NullPointerException
333 * if statement parameter is null
335 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
336 beforeAddEffectiveStatement(1);
337 effective.add(substatement);
341 * adds effective statement to collection of substatements
343 * @param substatements substatements
344 * @throws IllegalStateException
345 * if added in declared phase
346 * @throws NullPointerException
347 * if statement parameter is null
349 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
350 if (substatements.isEmpty()) {
354 substatements.forEach(Preconditions::checkNotNull);
355 beforeAddEffectiveStatement(substatements.size());
356 effective.addAll(substatements);
359 private void beforeAddEffectiveStatement(final int toAdd) {
360 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
361 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
362 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
363 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
365 if (effective.isEmpty()) {
366 effective = new ArrayList<>(toAdd);
371 * Create a new substatement at the specified offset.
373 * @param offset Substatement offset
374 * @param def definition context
375 * @param ref source reference
376 * @param argument statement argument
377 * @return A new substatement
379 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
380 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
381 final String argument) {
382 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
383 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
384 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
386 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
387 offset, def, ref, argument);
388 if(implicitStatement.isPresent()) {
389 final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
390 return presentImplicitStmt.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);