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.base.Throwables;
14 import com.google.common.collect.ImmutableCollection;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMultimap;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multimaps;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.EnumMap;
23 import java.util.EventListener;
24 import java.util.Iterator;
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;
43 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
44 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
47 * event listener when an item is added to model namespace
49 interface OnNamespaceItemAdded extends EventListener {
51 * @throws SourceException
53 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
57 * event listener when a parsing {@link ModelProcessingPhase} is completed
59 interface OnPhaseFinished extends EventListener {
61 * @throws SourceException
63 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
67 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
69 interface ContextMutation {
74 private final StatementDefinitionContext<A, D, E> definition;
75 private final StatementSourceReference statementDeclSource;
76 private final String rawArgument;
78 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
79 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
80 private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
81 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
82 private StatementMap substatements = StatementMap.empty();
84 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
85 private CopyHistory copyHistory = CopyHistory.original();
86 private boolean isSupportedToBuildEffective = true;
87 private ModelProcessingPhase completedPhase = null;
88 private StatementContextBase<?, ?, ?> originalCtx;
89 private D declaredInstance;
90 private E effectiveInstance;
91 private int order = 0;
93 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
94 final String rawArgument) {
95 this.definition = Preconditions.checkNotNull(def);
96 this.statementDeclSource = Preconditions.checkNotNull(ref);
97 this.rawArgument = rawArgument;
100 StatementContextBase(final StatementContextBase<A, D, E> original) {
101 this.definition = Preconditions.checkNotNull(original.definition,
102 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
103 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
104 "Statement context statementDeclSource cannot be null copying from: %s",
105 original.getStatementSourceReference());
106 this.rawArgument = original.rawArgument;
110 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
111 return effectOfStatement;
115 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
116 if (effectOfStatement.isEmpty()) {
117 effectOfStatement = new ArrayList<>(1);
119 effectOfStatement.add(ctx);
123 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
124 if (ctxs.isEmpty()) {
128 if (effectOfStatement.isEmpty()) {
129 effectOfStatement = new ArrayList<>(ctxs.size());
131 effectOfStatement.addAll(ctxs);
135 public SupportedByFeatures getSupportedByFeatures() {
136 return supportedByFeatures;
140 public void setSupportedByFeatures(final boolean isSupported) {
141 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
145 public boolean isSupportedToBuildEffective() {
146 return isSupportedToBuildEffective;
150 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
151 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
155 public CopyHistory getCopyHistory() {
160 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
161 copyHistory = copyHistory.append(typeOfCopy, toAppend);
165 public StatementContextBase<?, ?, ?> getOriginalCtx() {
170 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
171 this.originalCtx = originalCtx;
175 public void setOrder(final int order) {
180 public int getOrder() {
185 public ModelProcessingPhase getCompletedPhase() {
186 return completedPhase;
190 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
191 this.completedPhase = completedPhase;
195 public abstract StatementContextBase<?, ?, ?> getParentContext();
198 * @return root context of statement
202 public abstract RootStatementContext<?, ?, ?> getRoot();
205 * @return origin of statement
209 public StatementSource getStatementSource() {
210 return statementDeclSource.getStatementSource();
214 * @return reference of statement source
218 public StatementSourceReference getStatementSourceReference() {
219 return statementDeclSource;
223 public final String rawStatementArgument() {
229 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
230 return substatements.values();
235 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
236 if (effective instanceof ImmutableCollection) {
240 return Collections.unmodifiableCollection(effective);
243 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
244 if (!effective.isEmpty()) {
245 effective.removeAll(substatements);
250 private void shrinkEffective() {
251 if (effective.isEmpty()) {
252 effective = ImmutableList.of();
256 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
257 if (effective.isEmpty()) {
261 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
262 while (iterator.hasNext()) {
263 final StatementContextBase<?, ?, ?> next = iterator.next();
264 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
273 * adds effective statement to collection of substatements
275 * @param substatement substatement
276 * @throws IllegalStateException
277 * if added in declared phase
278 * @throws NullPointerException
279 * if statement parameter is null
281 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
282 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
283 getStatementSourceReference());
284 beforeAddEffectiveStatement(1);
285 effective.add(substatement);
289 * adds effective statement to collection of substatements
291 * @param substatements substatements
292 * @throws IllegalStateException
293 * if added in declared phase
294 * @throws NullPointerException
295 * if statement parameter is null
297 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
298 if (substatements.isEmpty()) {
302 substatements.forEach(Preconditions::checkNotNull);
303 beforeAddEffectiveStatement(substatements.size());
304 effective.addAll(substatements);
307 private void beforeAddEffectiveStatement(final int toAdd) {
308 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
309 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
310 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
311 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
313 if (effective.isEmpty()) {
314 effective = new ArrayList<>(toAdd);
319 * Create a new substatement at the specified offset.
321 * @param offset Substatement offset
322 * @param def definition context
323 * @param ref source reference
324 * @param argument statement argument
325 * @return A new substatement
327 final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE>
328 createSubstatement(final int offset, final StatementDefinitionContext<CA, CD, CE> def,
329 final StatementSourceReference ref, final String argument) {
330 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
331 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
332 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
334 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
335 substatements = substatements.put(offset, ret);
336 def.onStatementAdded(ret);
341 * Lookup substatement by its offset in this statement.
343 * @param offset Substatement offset
344 * @return Substatement, or null if substatement does not exist.
346 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
347 return substatements.get(offset);
351 * builds {@link DeclaredStatement} for statement context
354 public D buildDeclared() {
355 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
356 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
357 if (declaredInstance == null) {
358 declaredInstance = definition().getFactory().createDeclared(this);
360 return declaredInstance;
364 * builds {@link EffectiveStatement} for statement context
367 public E buildEffective() {
368 if (effectiveInstance == null) {
369 effectiveInstance = definition().getFactory().createEffective(this);
371 return effectiveInstance;
375 * tries to execute current {@link ModelProcessingPhase} of source parsing
378 * to be executed (completed)
379 * @return if phase was successfully completed
380 * @throws SourceException
381 * when an error occured in source parsing
383 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
385 boolean finished = true;
386 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
387 if (!openMutations.isEmpty()) {
388 final Iterator<ContextMutation> it = openMutations.iterator();
389 while (it.hasNext()) {
390 final ContextMutation current = it.next();
391 if (current.isFinished()) {
398 if (openMutations.isEmpty()) {
399 phaseMutation.removeAll(phase);
400 if (phaseMutation.isEmpty()) {
401 phaseMutation = ImmutableMultimap.of();
406 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
407 finished &= child.tryToCompletePhase(phase);
409 for (final StatementContextBase<?, ?, ?> child : effective) {
410 finished &= child.tryToCompletePhase(phase);
414 onPhaseCompleted(phase);
421 * Occurs on end of {@link ModelProcessingPhase} of source parsing
424 * that was to be completed (finished)
425 * @throws SourceException
426 * when an error occurred in source parsing
428 private void onPhaseCompleted(final ModelProcessingPhase phase) {
429 completedPhase = phase;
431 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
432 if (listeners.isEmpty()) {
436 final Iterator<OnPhaseFinished> listener = listeners.iterator();
437 while (listener.hasNext()) {
438 final OnPhaseFinished next = listener.next();
439 if (next.phaseFinished(this, phase)) {
444 if (listeners.isEmpty()) {
445 phaseListeners.removeAll(phase);
446 if (phaseListeners.isEmpty()) {
447 phaseListeners = ImmutableMultimap.of();
453 * Ends declared section of current node.
456 * @throws SourceException
458 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
459 definition().onDeclarationFinished(this, phase);
463 * @return statement definition
465 protected final StatementDefinitionContext<A, D, E> definition() {
470 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
471 definition().checkNamespaceAllowed(type);
475 * occurs when an item is added to model namespace
477 * @throws SourceException instance of SourceException
480 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
481 // definition().onNamespaceElementAdded(this, type, key, value);
484 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
485 final OnNamespaceItemAdded listener) throws SourceException {
486 final Object potential = getFromNamespace(type, key);
487 if (potential != null) {
488 listener.namespaceItemAdded(this, type, key, potential);
491 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
492 if (behaviour instanceof NamespaceBehaviourWithListeners) {
493 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
494 casted.addValueListener(new ValueAddedListener<K>(this, key) {
496 void onValueAdded(final Object key, final Object value) {
498 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
499 } catch (final SourceException e) {
500 throw Throwables.propagate(e);
508 * @see StatementSupport#getPublicView()
512 public StatementDefinition getPublicDefinition() {
513 return definition().getPublicView();
517 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
518 return getRoot().getSourceContext().newInferenceAction(phase);
521 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
522 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
526 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
528 * @throws SourceException
530 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
532 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
533 getStatementSourceReference());
534 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
535 getStatementSourceReference());
537 ModelProcessingPhase finishedPhase = completedPhase;
538 while (finishedPhase != null) {
539 if (phase.equals(finishedPhase)) {
540 listener.phaseFinished(this, finishedPhase);
543 finishedPhase = finishedPhase.getPreviousPhase();
545 if (phaseListeners.isEmpty()) {
546 phaseListeners = newMultimap();
549 phaseListeners.put(phase, listener);
553 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
555 * @throws IllegalStateException
556 * when the mutation was registered after phase was completed
558 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
559 ModelProcessingPhase finishedPhase = completedPhase;
560 while (finishedPhase != null) {
561 if (phase.equals(finishedPhase)) {
562 throw new IllegalStateException("Mutation registered after phase was completed at: " +
563 getStatementSourceReference());
565 finishedPhase = finishedPhase.getPreviousPhase();
568 if (phaseMutation.isEmpty()) {
569 phaseMutation = newMultimap();
571 phaseMutation.put(phase, mutation);
575 * adds statement to namespace map with the key
578 * {@link StatementNamespace} child that determines namespace to be added to
580 * of type according to namespace class specification
582 * to be added to namespace map
585 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
586 final StmtContext<?, ?, ?> stmt) {
587 addContextToNamespace(namespace, key, stmt);
591 public final String toString() {
592 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
595 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
596 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);