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<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> declaredSubstatements() {
241 return substatements.values();
246 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
247 if (effective instanceof ImmutableCollection) {
251 return Collections.unmodifiableCollection(effective);
254 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
255 if (!effective.isEmpty()) {
256 effective.removeAll(substatements);
261 private void shrinkEffective() {
262 if (effective.isEmpty()) {
263 effective = ImmutableList.of();
267 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
268 if (effective.isEmpty()) {
272 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
273 while (iterator.hasNext()) {
274 final StatementContextBase<?, ?, ?> next = iterator.next();
275 if (statementDef.equals(next.getPublicDefinition())) {
284 * Removes a statement context from the effective substatements
285 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
286 * The statement context is removed only if both statement definition and statement argument match with
287 * one of the effective substatements' statement definition and argument.
289 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
291 * @param statementDef statement definition of the statement context to remove
292 * @param statementArg statement argument of the statement context to remove
294 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
295 final String statementArg) {
296 if (statementArg == null) {
297 removeStatementFromEffectiveSubstatements(statementDef);
300 if (effective.isEmpty()) {
304 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
305 while (iterator.hasNext()) {
306 final StatementContextBase<?, ?, ?> next = iterator.next();
307 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
316 * adds effective statement to collection of substatements
318 * @param substatement substatement
319 * @throws IllegalStateException
320 * if added in declared phase
321 * @throws NullPointerException
322 * if statement parameter is null
324 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
325 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
326 getStatementSourceReference());
327 beforeAddEffectiveStatement(1);
328 effective.add(substatement);
332 * adds effective statement to collection of substatements
334 * @param substatements substatements
335 * @throws IllegalStateException
336 * if added in declared phase
337 * @throws NullPointerException
338 * if statement parameter is null
340 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
341 if (substatements.isEmpty()) {
345 substatements.forEach(Preconditions::checkNotNull);
346 beforeAddEffectiveStatement(substatements.size());
347 effective.addAll(substatements);
350 private void beforeAddEffectiveStatement(final int toAdd) {
351 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
352 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
353 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
354 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
356 if (effective.isEmpty()) {
357 effective = new ArrayList<>(toAdd);
362 * Create a new substatement at the specified offset.
364 * @param offset Substatement offset
365 * @param def definition context
366 * @param ref source reference
367 * @param argument statement argument
368 * @return A new substatement
370 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
371 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
372 final String argument) {
373 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
374 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
375 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
377 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
378 offset, def, ref, argument);
379 if(implicitStatement.isPresent()) {
380 final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
381 return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
384 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
385 substatements = substatements.put(offset, ret);
386 def.onStatementAdded(ret);
391 * Lookup substatement by its offset in this statement.
393 * @param offset Substatement offset
394 * @return Substatement, or null if substatement does not exist.
396 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
397 return substatements.get(offset);
401 public D buildDeclared() {
402 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
403 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
404 if (declaredInstance == null) {
405 declaredInstance = definition().getFactory().createDeclared(this);
407 return declaredInstance;
411 public E buildEffective() {
412 if (effectiveInstance == null) {
413 effectiveInstance = definition().getFactory().createEffective(this);
415 return effectiveInstance;
419 * tries to execute current {@link ModelProcessingPhase} of source parsing.
422 * to be executed (completed)
423 * @return if phase was successfully completed
424 * @throws SourceException
425 * when an error occured in source parsing
427 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
429 boolean finished = true;
430 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
431 if (!openMutations.isEmpty()) {
432 final Iterator<ContextMutation> it = openMutations.iterator();
433 while (it.hasNext()) {
434 final ContextMutation current = it.next();
435 if (current.isFinished()) {
442 if (openMutations.isEmpty()) {
443 phaseMutation.removeAll(phase);
444 if (phaseMutation.isEmpty()) {
445 phaseMutation = ImmutableMultimap.of();
450 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
451 finished &= child.tryToCompletePhase(phase);
453 for (final StatementContextBase<?, ?, ?> child : effective) {
454 finished &= 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);