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() {
170 final void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
171 copyHistory = copyHistory.append(typeOfCopy, toAppend);
175 public StmtContext<?, ?, ?> getOriginalCtx() {
179 final void setOriginalCtx(final StmtContext<?, ?, ?> originalCtx) {
180 this.originalCtx = originalCtx;
184 public void setOrder(final int order) {
189 public int getOrder() {
194 public ModelProcessingPhase getCompletedPhase() {
195 return completedPhase;
199 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
200 this.completedPhase = completedPhase;
204 public abstract StatementContextBase<?, ?, ?> getParentContext();
207 * @return root context of statement
211 public abstract RootStatementContext<?, ?, ?> getRoot();
214 * @return origin of statement
218 public StatementSource getStatementSource() {
219 return statementDeclSource.getStatementSource();
223 * @return reference of statement source
227 public StatementSourceReference getStatementSourceReference() {
228 return statementDeclSource;
232 public final String rawStatementArgument() {
238 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
239 return substatements.values();
244 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
245 return substatements.values();
249 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
250 return mutableEffectiveSubstatements();
255 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
256 if (effective instanceof ImmutableCollection) {
260 return Collections.unmodifiableCollection(effective);
263 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
264 if (!effective.isEmpty()) {
265 effective.removeAll(substatements);
270 private void shrinkEffective() {
271 if (effective.isEmpty()) {
272 effective = ImmutableList.of();
276 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
277 if (effective.isEmpty()) {
281 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
282 while (iterator.hasNext()) {
283 final StmtContext<?, ?, ?> next = iterator.next();
284 if (statementDef.equals(next.getPublicDefinition())) {
293 * Removes a statement context from the effective substatements
294 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
295 * The statement context is removed only if both statement definition and statement argument match with
296 * one of the effective substatements' statement definition and argument.
298 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
300 * @param statementDef statement definition of the statement context to remove
301 * @param statementArg statement argument of the statement context to remove
303 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
304 final String statementArg) {
305 if (statementArg == null) {
306 removeStatementFromEffectiveSubstatements(statementDef);
309 if (effective.isEmpty()) {
313 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
314 while (iterator.hasNext()) {
315 final Mutable<?, ?, ?> next = iterator.next();
316 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
325 * adds effective statement to collection of substatements
327 * @param substatement substatement
328 * @throws IllegalStateException
329 * if added in declared phase
330 * @throws NullPointerException
331 * if statement parameter is null
333 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
334 beforeAddEffectiveStatement(1);
335 effective.add(substatement);
339 * adds effective statement to collection of substatements
341 * @param substatements substatements
342 * @throws IllegalStateException
343 * if added in declared phase
344 * @throws NullPointerException
345 * if statement parameter is null
347 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
348 if (substatements.isEmpty()) {
352 substatements.forEach(Preconditions::checkNotNull);
353 beforeAddEffectiveStatement(substatements.size());
354 effective.addAll(substatements);
357 private void beforeAddEffectiveStatement(final int toAdd) {
358 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
359 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
360 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
361 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
363 if (effective.isEmpty()) {
364 effective = new ArrayList<>(toAdd);
369 * Create a new substatement at the specified offset.
371 * @param offset Substatement offset
372 * @param def definition context
373 * @param ref source reference
374 * @param argument statement argument
375 * @return A new substatement
377 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
378 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
379 final String argument) {
380 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
381 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
382 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
384 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
385 offset, def, ref, argument);
386 if(implicitStatement.isPresent()) {
387 final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
388 return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
391 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
392 substatements = substatements.put(offset, ret);
393 def.onStatementAdded(ret);
398 * Lookup substatement by its offset in this statement.
400 * @param offset Substatement offset
401 * @return Substatement, or null if substatement does not exist.
403 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
404 return substatements.get(offset);
408 public D buildDeclared() {
409 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
410 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
411 if (declaredInstance == null) {
412 declaredInstance = definition().getFactory().createDeclared(this);
414 return declaredInstance;
418 public E buildEffective() {
419 if (effectiveInstance == null) {
420 effectiveInstance = definition().getFactory().createEffective(this);
422 return effectiveInstance;
426 * tries to execute current {@link ModelProcessingPhase} of source parsing.
429 * to be executed (completed)
430 * @return if phase was successfully completed
431 * @throws SourceException
432 * when an error occured in source parsing
434 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
436 boolean finished = true;
437 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
438 if (!openMutations.isEmpty()) {
439 final Iterator<ContextMutation> it = openMutations.iterator();
440 while (it.hasNext()) {
441 final ContextMutation current = it.next();
442 if (current.isFinished()) {
449 if (openMutations.isEmpty()) {
450 phaseMutation.removeAll(phase);
451 if (phaseMutation.isEmpty()) {
452 phaseMutation = ImmutableMultimap.of();
457 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
458 finished &= child.tryToCompletePhase(phase);
460 for (final Mutable<?, ?, ?> child : effective) {
461 if (child instanceof StatementContextBase) {
462 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
467 onPhaseCompleted(phase);
474 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
477 * that was to be completed (finished)
478 * @throws SourceException
479 * when an error occurred in source parsing
481 private void onPhaseCompleted(final ModelProcessingPhase phase) {
482 completedPhase = phase;
484 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
485 if (listeners.isEmpty()) {
489 final Iterator<OnPhaseFinished> listener = listeners.iterator();
490 while (listener.hasNext()) {
491 final OnPhaseFinished next = listener.next();
492 if (next.phaseFinished(this, phase)) {
497 if (listeners.isEmpty()) {
498 phaseListeners.removeAll(phase);
499 if (phaseListeners.isEmpty()) {
500 phaseListeners = ImmutableMultimap.of();
506 * Ends declared section of current node.
509 * @throws SourceException
511 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
512 definition().onDeclarationFinished(this, phase);
516 * @return statement definition
518 protected final StatementDefinitionContext<A, D, E> definition() {
523 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
524 definition().checkNamespaceAllowed(type);
528 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
530 // definition().onNamespaceElementAdded(this, type, key, value);
533 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
534 final OnNamespaceItemAdded listener) throws SourceException {
535 final Object potential = getFromNamespace(type, key);
536 if (potential != null) {
537 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
538 listener.namespaceItemAdded(this, type, key, potential);
542 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
543 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
544 "Namespace {} does not support listeners", type);
546 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
547 casted.addValueListener(new ValueAddedListener<K>(this, key) {
549 void onValueAdded(final Object key, final Object value) {
550 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
556 * See {@link StatementSupport#getPublicView()}.
560 public StatementDefinition getPublicDefinition() {
561 return definition().getPublicView();
565 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
566 return getRoot().getSourceContext().newInferenceAction(phase);
569 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
570 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
574 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
576 * @throws SourceException
578 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
580 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
581 getStatementSourceReference());
582 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
583 getStatementSourceReference());
585 ModelProcessingPhase finishedPhase = completedPhase;
586 while (finishedPhase != null) {
587 if (phase.equals(finishedPhase)) {
588 listener.phaseFinished(this, finishedPhase);
591 finishedPhase = finishedPhase.getPreviousPhase();
593 if (phaseListeners.isEmpty()) {
594 phaseListeners = newMultimap();
597 phaseListeners.put(phase, listener);
601 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
603 * @throws IllegalStateException
604 * when the mutation was registered after phase was completed
606 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
607 ModelProcessingPhase finishedPhase = completedPhase;
608 while (finishedPhase != null) {
609 if (phase.equals(finishedPhase)) {
610 throw new IllegalStateException("Mutation registered after phase was completed at: " +
611 getStatementSourceReference());
613 finishedPhase = finishedPhase.getPreviousPhase();
616 if (phaseMutation.isEmpty()) {
617 phaseMutation = newMultimap();
619 phaseMutation.put(phase, mutation);
623 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
624 final KT key,final StmtContext<?, ?, ?> stmt) {
625 addContextToNamespace(namespace, key, stmt);
629 public final String toString() {
630 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
633 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
634 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);