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 java.util.Optional;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
30 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
40 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
41 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
42 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
44 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
45 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
48 * event listener when an item is added to model namespace
50 interface OnNamespaceItemAdded extends EventListener {
52 * @throws SourceException
54 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
58 * event listener when a parsing {@link ModelProcessingPhase} is completed
60 interface OnPhaseFinished extends EventListener {
62 * @throws SourceException
64 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
68 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
70 interface ContextMutation {
75 private final StatementDefinitionContext<A, D, E> definition;
76 private final StatementSourceReference statementDeclSource;
77 private final String rawArgument;
79 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
80 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
81 private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
82 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
83 private StatementMap substatements = StatementMap.empty();
85 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
86 private CopyHistory copyHistory = CopyHistory.original();
87 private boolean isSupportedToBuildEffective = true;
88 private ModelProcessingPhase completedPhase = null;
89 private StatementContextBase<?, ?, ?> originalCtx;
90 private D declaredInstance;
91 private E effectiveInstance;
92 private int order = 0;
94 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
95 final String rawArgument) {
96 this.definition = Preconditions.checkNotNull(def);
97 this.statementDeclSource = Preconditions.checkNotNull(ref);
98 this.rawArgument = rawArgument;
101 StatementContextBase(final StatementContextBase<A, D, E> original) {
102 this.definition = Preconditions.checkNotNull(original.definition,
103 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
104 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
105 "Statement context statementDeclSource cannot be null copying from: %s",
106 original.getStatementSourceReference());
107 this.rawArgument = original.rawArgument;
111 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
112 return effectOfStatement;
116 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
117 if (effectOfStatement.isEmpty()) {
118 effectOfStatement = new ArrayList<>(1);
120 effectOfStatement.add(ctx);
124 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
125 if (ctxs.isEmpty()) {
129 if (effectOfStatement.isEmpty()) {
130 effectOfStatement = new ArrayList<>(ctxs.size());
132 effectOfStatement.addAll(ctxs);
136 public SupportedByFeatures getSupportedByFeatures() {
137 return supportedByFeatures;
141 public void setSupportedByFeatures(final boolean isSupported) {
142 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
146 public boolean isSupportedToBuildEffective() {
147 return isSupportedToBuildEffective;
151 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
152 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
156 public CopyHistory getCopyHistory() {
161 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
162 copyHistory = copyHistory.append(typeOfCopy, toAppend);
166 public StatementContextBase<?, ?, ?> getOriginalCtx() {
171 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
172 this.originalCtx = originalCtx;
176 public void setOrder(final int order) {
181 public int getOrder() {
186 public ModelProcessingPhase getCompletedPhase() {
187 return completedPhase;
191 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
192 this.completedPhase = completedPhase;
196 public abstract StatementContextBase<?, ?, ?> getParentContext();
199 * @return root context of statement
203 public abstract RootStatementContext<?, ?, ?> getRoot();
206 * @return origin of statement
210 public StatementSource getStatementSource() {
211 return statementDeclSource.getStatementSource();
215 * @return reference of statement source
219 public StatementSourceReference getStatementSourceReference() {
220 return statementDeclSource;
224 public final String rawStatementArgument() {
230 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
231 return substatements.values();
236 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
237 if (effective instanceof ImmutableCollection) {
241 return Collections.unmodifiableCollection(effective);
244 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
245 if (!effective.isEmpty()) {
246 effective.removeAll(substatements);
251 private void shrinkEffective() {
252 if (effective.isEmpty()) {
253 effective = ImmutableList.of();
257 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
258 if (effective.isEmpty()) {
262 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
263 while (iterator.hasNext()) {
264 final StatementContextBase<?, ?, ?> next = iterator.next();
265 if (statementDef.equals(next.getPublicDefinition())) {
274 * Removes a statement context from the effective substatements
275 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
276 * The statement context is removed only if both statement definition and statement argument match with
277 * one of the effective substatements' statement definition and argument.
279 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
281 * @param statementDef statement definition of the statement context to remove
282 * @param statementArg statement argument of the statement context to remove
284 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
285 final String statementArg) {
286 if (statementArg == null) {
287 removeStatementFromEffectiveSubstatements(statementDef);
290 if (effective.isEmpty()) {
294 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
295 while (iterator.hasNext()) {
296 final StatementContextBase<?, ?, ?> next = iterator.next();
297 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
306 * adds effective statement to collection of substatements
308 * @param substatement substatement
309 * @throws IllegalStateException
310 * if added in declared phase
311 * @throws NullPointerException
312 * if statement parameter is null
314 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
315 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
316 getStatementSourceReference());
317 beforeAddEffectiveStatement(1);
318 effective.add(substatement);
322 * adds effective statement to collection of substatements
324 * @param substatements substatements
325 * @throws IllegalStateException
326 * if added in declared phase
327 * @throws NullPointerException
328 * if statement parameter is null
330 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
331 if (substatements.isEmpty()) {
335 substatements.forEach(Preconditions::checkNotNull);
336 beforeAddEffectiveStatement(substatements.size());
337 effective.addAll(substatements);
340 private void beforeAddEffectiveStatement(final int toAdd) {
341 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
342 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
343 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
344 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
346 if (effective.isEmpty()) {
347 effective = new ArrayList<>(toAdd);
352 * Create a new substatement at the specified offset.
354 * @param offset Substatement offset
355 * @param def definition context
356 * @param ref source reference
357 * @param argument statement argument
358 * @return A new substatement
360 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
361 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
362 final String argument) {
363 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
364 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
365 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
367 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this, offset, def, ref, argument);
368 if(implicitStatement.isPresent()) {
369 final StatementContextBase<?, ?, ?> presentImplicitStmt = implicitStatement.get();
370 return presentImplicitStmt.createSubstatement(offset, def, ref, argument);
373 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
374 substatements = substatements.put(offset, ret);
375 def.onStatementAdded(ret);
380 * Lookup substatement by its offset in this statement.
382 * @param offset Substatement offset
383 * @return Substatement, or null if substatement does not exist.
385 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
386 return substatements.get(offset);
390 * builds {@link DeclaredStatement} for statement context
393 public D buildDeclared() {
394 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
395 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
396 if (declaredInstance == null) {
397 declaredInstance = definition().getFactory().createDeclared(this);
399 return declaredInstance;
403 * builds {@link EffectiveStatement} for statement context
406 public E buildEffective() {
407 if (effectiveInstance == null) {
408 effectiveInstance = definition().getFactory().createEffective(this);
410 return effectiveInstance;
414 * tries to execute current {@link ModelProcessingPhase} of source parsing
417 * to be executed (completed)
418 * @return if phase was successfully completed
419 * @throws SourceException
420 * when an error occured in source parsing
422 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
424 boolean finished = true;
425 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
426 if (!openMutations.isEmpty()) {
427 final Iterator<ContextMutation> it = openMutations.iterator();
428 while (it.hasNext()) {
429 final ContextMutation current = it.next();
430 if (current.isFinished()) {
437 if (openMutations.isEmpty()) {
438 phaseMutation.removeAll(phase);
439 if (phaseMutation.isEmpty()) {
440 phaseMutation = ImmutableMultimap.of();
445 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
446 finished &= child.tryToCompletePhase(phase);
448 for (final StatementContextBase<?, ?, ?> child : effective) {
449 finished &= child.tryToCompletePhase(phase);
453 onPhaseCompleted(phase);
460 * Occurs on end of {@link ModelProcessingPhase} of source parsing
463 * that was to be completed (finished)
464 * @throws SourceException
465 * when an error occurred in source parsing
467 private void onPhaseCompleted(final ModelProcessingPhase phase) {
468 completedPhase = phase;
470 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
471 if (listeners.isEmpty()) {
475 final Iterator<OnPhaseFinished> listener = listeners.iterator();
476 while (listener.hasNext()) {
477 final OnPhaseFinished next = listener.next();
478 if (next.phaseFinished(this, phase)) {
483 if (listeners.isEmpty()) {
484 phaseListeners.removeAll(phase);
485 if (phaseListeners.isEmpty()) {
486 phaseListeners = ImmutableMultimap.of();
492 * Ends declared section of current node.
495 * @throws SourceException
497 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
498 definition().onDeclarationFinished(this, phase);
502 * @return statement definition
504 protected final StatementDefinitionContext<A, D, E> definition() {
509 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
510 definition().checkNamespaceAllowed(type);
514 * occurs when an item is added to model namespace
516 * @throws SourceException instance of SourceException
519 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
520 // definition().onNamespaceElementAdded(this, type, key, value);
523 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
524 final OnNamespaceItemAdded listener) throws SourceException {
525 final Object potential = getFromNamespace(type, key);
526 if (potential != null) {
527 listener.namespaceItemAdded(this, type, key, potential);
530 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
531 if (behaviour instanceof NamespaceBehaviourWithListeners) {
532 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
533 casted.addValueListener(new ValueAddedListener<K>(this, key) {
535 void onValueAdded(final Object key, final Object value) {
537 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
538 } catch (final SourceException e) {
539 throw Throwables.propagate(e);
547 * @see 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 * adds statement to namespace map with the key
617 * {@link StatementNamespace} child that determines namespace to be added to
619 * of type according to namespace class specification
621 * to be added to namespace map
624 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
625 final StmtContext<?, ?, ?> stmt) {
626 addContextToNamespace(namespace, key, stmt);
630 public final String toString() {
631 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
634 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
635 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);