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 StmtContext<?, ?, ?> originalCtx;
85 private final CopyHistory copyHistory;
86 private final String rawArgument;
88 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
89 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
90 private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
91 private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
92 private StatementMap substatements = StatementMap.empty();
94 private Boolean supportedByFeatures = null;
95 private boolean isSupportedToBuildEffective = true;
96 private ModelProcessingPhase completedPhase = null;
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);
106 this.copyHistory = CopyHistory.original();
107 this.originalCtx = null;
110 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
111 this.definition = Preconditions.checkNotNull(original.definition,
112 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
113 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
114 "Statement context statementDeclSource cannot be null copying from: %s",
115 original.getStatementSourceReference());
116 this.rawArgument = original.rawArgument;
117 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
118 this.originalCtx = original.getOriginalCtx().orElse(original);
122 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
123 return effectOfStatement;
127 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
128 if (effectOfStatement.isEmpty()) {
129 effectOfStatement = new ArrayList<>(1);
131 effectOfStatement.add(ctx);
135 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
136 if (ctxs.isEmpty()) {
140 if (effectOfStatement.isEmpty()) {
141 effectOfStatement = new ArrayList<>(ctxs.size());
143 effectOfStatement.addAll(ctxs);
147 public boolean isSupportedByFeatures() {
148 if (supportedByFeatures == null) {
149 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
150 SupportedFeatures.SUPPORTED_FEATURES);
151 // If the set of supported features has not been provided, all features are supported by default.
152 supportedByFeatures = supportedFeatures == null ? Boolean.TRUE
153 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
156 return supportedByFeatures.booleanValue();
160 public boolean isSupportedToBuildEffective() {
161 return isSupportedToBuildEffective;
165 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
166 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
170 public CopyHistory getCopyHistory() {
175 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
176 return Optional.ofNullable(originalCtx);
180 public void setOrder(final int order) {
185 public int getOrder() {
190 public ModelProcessingPhase getCompletedPhase() {
191 return completedPhase;
195 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
196 this.completedPhase = completedPhase;
200 public abstract StatementContextBase<?, ?, ?> getParentContext();
203 * @return root context of statement
207 public abstract RootStatementContext<?, ?, ?> getRoot();
210 * @return origin of statement
214 public StatementSource getStatementSource() {
215 return statementDeclSource.getStatementSource();
219 * @return reference of statement source
223 public StatementSourceReference getStatementSourceReference() {
224 return statementDeclSource;
228 public final String rawStatementArgument() {
234 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
235 return substatements.values();
240 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
241 return substatements.values();
245 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
246 return mutableEffectiveSubstatements();
251 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
252 if (effective instanceof ImmutableCollection) {
256 return Collections.unmodifiableCollection(effective);
259 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
260 if (!effective.isEmpty()) {
261 effective.removeAll(substatements);
266 private void shrinkEffective() {
267 if (effective.isEmpty()) {
268 effective = ImmutableList.of();
272 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
273 if (effective.isEmpty()) {
277 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
278 while (iterator.hasNext()) {
279 final StmtContext<?, ?, ?> next = iterator.next();
280 if (statementDef.equals(next.getPublicDefinition())) {
289 * Removes a statement context from the effective substatements
290 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
291 * The statement context is removed only if both statement definition and statement argument match with
292 * one of the effective substatements' statement definition and argument.
294 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
296 * @param statementDef statement definition of the statement context to remove
297 * @param statementArg statement argument of the statement context to remove
299 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
300 final String statementArg) {
301 if (statementArg == null) {
302 removeStatementFromEffectiveSubstatements(statementDef);
305 if (effective.isEmpty()) {
309 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
310 while (iterator.hasNext()) {
311 final Mutable<?, ?, ?> next = iterator.next();
312 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
321 * adds effective statement to collection of substatements
323 * @param substatement substatement
324 * @throws IllegalStateException
325 * if added in declared phase
326 * @throws NullPointerException
327 * if statement parameter is null
329 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
330 beforeAddEffectiveStatement(1);
331 effective.add(substatement);
335 * adds effective statement to collection of substatements
337 * @param substatements substatements
338 * @throws IllegalStateException
339 * if added in declared phase
340 * @throws NullPointerException
341 * if statement parameter is null
343 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
344 if (substatements.isEmpty()) {
348 substatements.forEach(Preconditions::checkNotNull);
349 beforeAddEffectiveStatement(substatements.size());
350 effective.addAll(substatements);
353 private void beforeAddEffectiveStatement(final int toAdd) {
354 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
355 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
356 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
357 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
359 if (effective.isEmpty()) {
360 effective = new ArrayList<>(toAdd);
365 * Create a new substatement at the specified offset.
367 * @param offset Substatement offset
368 * @param def definition context
369 * @param ref source reference
370 * @param argument statement argument
371 * @return A new substatement
373 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
374 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
375 final String argument) {
376 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
377 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
378 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
380 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
381 offset, def, ref, argument);
382 if (implicitStatement.isPresent()) {
383 return implicitStatement.get().createSubstatement(offset, def, ref, argument);
386 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
387 substatements = substatements.put(offset, ret);
388 def.onStatementAdded(ret);
393 * Lookup substatement by its offset in this statement.
395 * @param offset Substatement offset
396 * @return Substatement, or null if substatement does not exist.
398 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
399 return substatements.get(offset);
403 public D buildDeclared() {
404 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
405 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
406 if (declaredInstance == null) {
407 declaredInstance = definition().getFactory().createDeclared(this);
409 return declaredInstance;
413 public E buildEffective() {
414 if (effectiveInstance == null) {
415 effectiveInstance = definition().getFactory().createEffective(this);
417 return effectiveInstance;
421 * tries to execute current {@link ModelProcessingPhase} of source parsing.
424 * to be executed (completed)
425 * @return if phase was successfully completed
426 * @throws SourceException
427 * when an error occured in source parsing
429 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
431 boolean finished = true;
432 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
433 if (!openMutations.isEmpty()) {
434 final Iterator<ContextMutation> it = openMutations.iterator();
435 while (it.hasNext()) {
436 final ContextMutation current = it.next();
437 if (current.isFinished()) {
444 if (openMutations.isEmpty()) {
445 phaseMutation.removeAll(phase);
446 if (phaseMutation.isEmpty()) {
447 phaseMutation = ImmutableMultimap.of();
452 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
453 finished &= child.tryToCompletePhase(phase);
455 for (final Mutable<?, ?, ?> child : effective) {
456 if (child instanceof StatementContextBase) {
457 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
462 onPhaseCompleted(phase);
469 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
472 * that was to be completed (finished)
473 * @throws SourceException
474 * when an error occurred in source parsing
476 private void onPhaseCompleted(final ModelProcessingPhase phase) {
477 completedPhase = phase;
479 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
480 if (listeners.isEmpty()) {
484 final Iterator<OnPhaseFinished> listener = listeners.iterator();
485 while (listener.hasNext()) {
486 final OnPhaseFinished next = listener.next();
487 if (next.phaseFinished(this, phase)) {
492 if (listeners.isEmpty()) {
493 phaseListeners.removeAll(phase);
494 if (phaseListeners.isEmpty()) {
495 phaseListeners = ImmutableMultimap.of();
501 * Ends declared section of current node.
504 * @throws SourceException
506 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
507 definition().onDeclarationFinished(this, phase);
511 * @return statement definition
513 protected final StatementDefinitionContext<A, D, E> definition() {
518 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
519 definition().checkNamespaceAllowed(type);
523 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
525 // definition().onNamespaceElementAdded(this, type, key, value);
528 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
529 final OnNamespaceItemAdded listener) throws SourceException {
530 final Object potential = getFromNamespace(type, key);
531 if (potential != null) {
532 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
533 listener.namespaceItemAdded(this, type, key, potential);
537 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
538 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
539 "Namespace {} does not support listeners", type);
541 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
542 casted.addValueListener(new ValueAddedListener<K>(this, key) {
544 void onValueAdded(final Object key, final Object value) {
545 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
551 * See {@link StatementSupport#getPublicView()}.
555 public StatementDefinition getPublicDefinition() {
556 return definition().getPublicView();
560 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
561 return getRoot().getSourceContext().newInferenceAction(phase);
564 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
565 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
569 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
571 * @throws SourceException
573 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
575 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
576 getStatementSourceReference());
577 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
578 getStatementSourceReference());
580 ModelProcessingPhase finishedPhase = completedPhase;
581 while (finishedPhase != null) {
582 if (phase.equals(finishedPhase)) {
583 listener.phaseFinished(this, finishedPhase);
586 finishedPhase = finishedPhase.getPreviousPhase();
588 if (phaseListeners.isEmpty()) {
589 phaseListeners = newMultimap();
592 phaseListeners.put(phase, listener);
596 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
598 * @throws IllegalStateException
599 * when the mutation was registered after phase was completed
601 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
602 ModelProcessingPhase finishedPhase = completedPhase;
603 while (finishedPhase != null) {
604 if (phase.equals(finishedPhase)) {
605 throw new IllegalStateException("Mutation registered after phase was completed at: " +
606 getStatementSourceReference());
608 finishedPhase = finishedPhase.getPreviousPhase();
611 if (phaseMutation.isEmpty()) {
612 phaseMutation = newMultimap();
614 phaseMutation.put(phase, mutation);
618 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
619 final KT key,final StmtContext<?, ?, ?> stmt) {
620 addContextToNamespace(namespace, key, stmt);
624 public final String toString() {
625 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
628 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
629 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);