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;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
30 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
39 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
40 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
41 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
46 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
49 * event listener when an item is added to model namespace.
51 interface OnNamespaceItemAdded extends EventListener {
53 * @throws SourceException
55 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
59 * event listener when a parsing {@link ModelProcessingPhase} is completed.
61 interface OnPhaseFinished extends EventListener {
63 * @throws SourceException
65 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
69 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
71 interface ContextMutation {
76 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
78 private final StatementDefinitionContext<A, D, E> definition;
79 private final StatementSourceReference statementDeclSource;
80 private final String rawArgument;
82 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
83 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
84 private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
85 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
86 private StatementMap substatements = StatementMap.empty();
88 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
89 private CopyHistory copyHistory = CopyHistory.original();
90 private boolean isSupportedToBuildEffective = true;
91 private ModelProcessingPhase completedPhase = null;
92 private StatementContextBase<?, ?, ?> originalCtx;
93 private D declaredInstance;
94 private E effectiveInstance;
95 private int order = 0;
97 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
98 final String rawArgument) {
99 this.definition = Preconditions.checkNotNull(def);
100 this.statementDeclSource = Preconditions.checkNotNull(ref);
101 this.rawArgument = def.internArgument(rawArgument);
104 StatementContextBase(final StatementContextBase<A, D, E> original) {
105 this.definition = Preconditions.checkNotNull(original.definition,
106 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
107 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
108 "Statement context statementDeclSource cannot be null copying from: %s",
109 original.getStatementSourceReference());
110 this.rawArgument = original.rawArgument;
114 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
115 return effectOfStatement;
119 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
120 if (effectOfStatement.isEmpty()) {
121 effectOfStatement = new ArrayList<>(1);
123 effectOfStatement.add(ctx);
127 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
128 if (ctxs.isEmpty()) {
132 if (effectOfStatement.isEmpty()) {
133 effectOfStatement = new ArrayList<>(ctxs.size());
135 effectOfStatement.addAll(ctxs);
139 public SupportedByFeatures getSupportedByFeatures() {
140 return supportedByFeatures;
144 public void setSupportedByFeatures(final boolean isSupported) {
145 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
149 public boolean isSupportedToBuildEffective() {
150 return isSupportedToBuildEffective;
154 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
155 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
159 public CopyHistory getCopyHistory() {
164 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
165 copyHistory = copyHistory.append(typeOfCopy, toAppend);
169 public StatementContextBase<?, ?, ?> getOriginalCtx() {
174 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
175 this.originalCtx = originalCtx;
179 public void setOrder(final int order) {
184 public int getOrder() {
189 public ModelProcessingPhase getCompletedPhase() {
190 return completedPhase;
194 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
195 this.completedPhase = completedPhase;
199 public abstract StatementContextBase<?, ?, ?> getParentContext();
202 * @return root context of statement
206 public abstract RootStatementContext<?, ?, ?> getRoot();
209 * @return origin of statement
213 public StatementSource getStatementSource() {
214 return statementDeclSource.getStatementSource();
218 * @return reference of statement source
222 public StatementSourceReference getStatementSourceReference() {
223 return statementDeclSource;
227 public final String rawStatementArgument() {
233 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
234 return substatements.values();
239 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
240 if (effective instanceof ImmutableCollection) {
244 return Collections.unmodifiableCollection(effective);
247 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
248 if (!effective.isEmpty()) {
249 effective.removeAll(substatements);
254 private void shrinkEffective() {
255 if (effective.isEmpty()) {
256 effective = ImmutableList.of();
260 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
261 if (effective.isEmpty()) {
265 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
266 while (iterator.hasNext()) {
267 final StatementContextBase<?, ?, ?> next = iterator.next();
268 if (statementDef.equals(next.getPublicDefinition())) {
277 * Removes a statement context from the effective substatements
278 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
279 * The statement context is removed only if both statement definition and statement argument match with
280 * one of the effective substatements' statement definition and argument.
282 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
284 * @param statementDef statement definition of the statement context to remove
285 * @param statementArg statement argument of the statement context to remove
287 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
288 final String statementArg) {
289 if (statementArg == null) {
290 removeStatementFromEffectiveSubstatements(statementDef);
293 if (effective.isEmpty()) {
297 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
298 while (iterator.hasNext()) {
299 final StatementContextBase<?, ?, ?> next = iterator.next();
300 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
309 * adds effective statement to collection of substatements
311 * @param substatement substatement
312 * @throws IllegalStateException
313 * if added in declared phase
314 * @throws NullPointerException
315 * if statement parameter is null
317 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
318 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
319 getStatementSourceReference());
320 beforeAddEffectiveStatement(1);
321 effective.add(substatement);
325 * adds effective statement to collection of substatements
327 * @param substatements substatements
328 * @throws IllegalStateException
329 * if added in declared phase
330 * @throws NullPointerException
331 * if statement parameter is null
333 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
334 if (substatements.isEmpty()) {
338 substatements.forEach(Preconditions::checkNotNull);
339 beforeAddEffectiveStatement(substatements.size());
340 effective.addAll(substatements);
343 private void beforeAddEffectiveStatement(final int toAdd) {
344 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
345 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
346 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
347 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
349 if (effective.isEmpty()) {
350 effective = new ArrayList<>(toAdd);
355 * Create a new substatement at the specified offset.
357 * @param offset Substatement offset
358 * @param def definition context
359 * @param ref source reference
360 * @param argument statement argument
361 * @return A new substatement
363 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
364 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
365 final String argument) {
366 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
367 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
368 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
370 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
371 offset, def, ref, argument);
372 if(implicitStatement.isPresent()) {
373 final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
374 return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
377 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
378 substatements = substatements.put(offset, ret);
379 def.onStatementAdded(ret);
384 * Lookup substatement by its offset in this statement.
386 * @param offset Substatement offset
387 * @return Substatement, or null if substatement does not exist.
389 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
390 return substatements.get(offset);
394 public D buildDeclared() {
395 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
396 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
397 if (declaredInstance == null) {
398 declaredInstance = definition().getFactory().createDeclared(this);
400 return declaredInstance;
404 public E buildEffective() {
405 if (effectiveInstance == null) {
406 effectiveInstance = definition().getFactory().createEffective(this);
408 return effectiveInstance;
412 * tries to execute current {@link ModelProcessingPhase} of source parsing.
415 * to be executed (completed)
416 * @return if phase was successfully completed
417 * @throws SourceException
418 * when an error occured in source parsing
420 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
422 boolean finished = true;
423 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
424 if (!openMutations.isEmpty()) {
425 final Iterator<ContextMutation> it = openMutations.iterator();
426 while (it.hasNext()) {
427 final ContextMutation current = it.next();
428 if (current.isFinished()) {
435 if (openMutations.isEmpty()) {
436 phaseMutation.removeAll(phase);
437 if (phaseMutation.isEmpty()) {
438 phaseMutation = ImmutableMultimap.of();
443 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
444 finished &= child.tryToCompletePhase(phase);
446 for (final StatementContextBase<?, ?, ?> child : effective) {
447 finished &= child.tryToCompletePhase(phase);
451 onPhaseCompleted(phase);
458 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
461 * that was to be completed (finished)
462 * @throws SourceException
463 * when an error occurred in source parsing
465 private void onPhaseCompleted(final ModelProcessingPhase phase) {
466 completedPhase = phase;
468 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
469 if (listeners.isEmpty()) {
473 final Iterator<OnPhaseFinished> listener = listeners.iterator();
474 while (listener.hasNext()) {
475 final OnPhaseFinished next = listener.next();
476 if (next.phaseFinished(this, phase)) {
481 if (listeners.isEmpty()) {
482 phaseListeners.removeAll(phase);
483 if (phaseListeners.isEmpty()) {
484 phaseListeners = ImmutableMultimap.of();
490 * Ends declared section of current node.
493 * @throws SourceException
495 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
496 definition().onDeclarationFinished(this, phase);
500 * @return statement definition
502 protected final StatementDefinitionContext<A, D, E> definition() {
507 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
508 definition().checkNamespaceAllowed(type);
512 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
514 // definition().onNamespaceElementAdded(this, type, key, value);
517 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
518 final OnNamespaceItemAdded listener) throws SourceException {
519 final Object potential = getFromNamespace(type, key);
520 if (potential != null) {
521 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
522 listener.namespaceItemAdded(this, type, key, potential);
526 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
527 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
528 "Namespace {} does not support listeners", type);
530 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
531 casted.addValueListener(new ValueAddedListener<K>(this, key) {
533 void onValueAdded(final Object key, final Object value) {
534 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
540 * See {@link StatementSupport#getPublicView()}.
544 public StatementDefinition getPublicDefinition() {
545 return definition().getPublicView();
549 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
550 return getRoot().getSourceContext().newInferenceAction(phase);
553 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
554 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
558 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
560 * @throws SourceException
562 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
564 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
565 getStatementSourceReference());
566 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
567 getStatementSourceReference());
569 ModelProcessingPhase finishedPhase = completedPhase;
570 while (finishedPhase != null) {
571 if (phase.equals(finishedPhase)) {
572 listener.phaseFinished(this, finishedPhase);
575 finishedPhase = finishedPhase.getPreviousPhase();
577 if (phaseListeners.isEmpty()) {
578 phaseListeners = newMultimap();
581 phaseListeners.put(phase, listener);
585 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
587 * @throws IllegalStateException
588 * when the mutation was registered after phase was completed
590 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
591 ModelProcessingPhase finishedPhase = completedPhase;
592 while (finishedPhase != null) {
593 if (phase.equals(finishedPhase)) {
594 throw new IllegalStateException("Mutation registered after phase was completed at: " +
595 getStatementSourceReference());
597 finishedPhase = finishedPhase.getPreviousPhase();
600 if (phaseMutation.isEmpty()) {
601 phaseMutation = newMultimap();
603 phaseMutation.put(phase, mutation);
607 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
608 final KT key,final StmtContext<?, ?, ?> stmt) {
609 addContextToNamespace(namespace, key, stmt);
613 public final String toString() {
614 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
617 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
618 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);