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.util.OptionalBoolean;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
54 * event listener when an item is added to model namespace.
56 interface OnNamespaceItemAdded extends EventListener {
58 * @throws SourceException
60 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
64 * event listener when a parsing {@link ModelProcessingPhase} is completed.
66 interface OnPhaseFinished extends EventListener {
68 * @throws SourceException
70 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
74 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
76 interface ContextMutation {
81 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
83 private final StatementDefinitionContext<A, D, E> definition;
84 private final StatementSourceReference statementDeclSource;
85 private final StmtContext<?, ?, ?> originalCtx;
86 private final CopyHistory copyHistory;
87 private final String rawArgument;
89 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
90 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
91 private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
92 private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
93 private StatementMap substatements = StatementMap.empty();
95 private boolean isSupportedToBuildEffective = true;
96 private ModelProcessingPhase completedPhase = null;
97 private D declaredInstance;
98 private E effectiveInstance;
100 // BooleanFields value
101 private byte supportedByFeatures;
103 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
104 final String rawArgument) {
105 this.definition = Preconditions.checkNotNull(def);
106 this.statementDeclSource = Preconditions.checkNotNull(ref);
107 this.rawArgument = def.internArgument(rawArgument);
108 this.copyHistory = CopyHistory.original();
109 this.originalCtx = null;
112 StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
113 this.definition = Preconditions.checkNotNull(original.definition,
114 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
115 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
116 "Statement context statementDeclSource cannot be null copying from: %s",
117 original.getStatementSourceReference());
118 this.rawArgument = original.rawArgument;
119 this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
120 this.originalCtx = original.getOriginalCtx().orElse(original);
124 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
125 return effectOfStatement;
129 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
130 if (effectOfStatement.isEmpty()) {
131 effectOfStatement = new ArrayList<>(1);
133 effectOfStatement.add(ctx);
137 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
138 if (ctxs.isEmpty()) {
142 if (effectOfStatement.isEmpty()) {
143 effectOfStatement = new ArrayList<>(ctxs.size());
145 effectOfStatement.addAll(ctxs);
149 public boolean isSupportedByFeatures() {
150 if (isIgnoringIfFeatures()) {
153 if (OptionalBoolean.isPresent(supportedByFeatures)) {
154 return OptionalBoolean.get(supportedByFeatures);
157 // If the set of supported features has not been provided, all features are supported by default.
158 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
159 SupportedFeatures.SUPPORTED_FEATURES);
160 final boolean ret = supportedFeatures == null ? true
161 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
163 supportedByFeatures = OptionalBoolean.of(ret);
168 protected abstract boolean isIgnoringIfFeatures();
170 protected abstract boolean isIgnoringConfig();
173 public boolean isSupportedToBuildEffective() {
174 return isSupportedToBuildEffective;
178 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
179 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
183 public CopyHistory getCopyHistory() {
188 public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
189 return Optional.ofNullable(originalCtx);
193 public ModelProcessingPhase getCompletedPhase() {
194 return completedPhase;
198 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
199 this.completedPhase = completedPhase;
203 public abstract StatementContextBase<?, ?, ?> getParentContext();
206 * @return root context of statement
210 public abstract RootStatementContext<?, ?, ?> getRoot();
213 * @return origin of statement
217 public StatementSource getStatementSource() {
218 return statementDeclSource.getStatementSource();
222 * @return reference of statement source
226 public StatementSourceReference getStatementSourceReference() {
227 return statementDeclSource;
231 public final String rawStatementArgument() {
237 public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
238 return substatements.values();
243 public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
244 return substatements.values();
248 public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
249 return mutableEffectiveSubstatements();
254 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
255 if (effective instanceof ImmutableCollection) {
259 return Collections.unmodifiableCollection(effective);
262 public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
263 if (!effective.isEmpty()) {
264 effective.removeAll(substatements);
269 private void shrinkEffective() {
270 if (effective.isEmpty()) {
271 effective = ImmutableList.of();
275 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
276 if (effective.isEmpty()) {
280 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
281 while (iterator.hasNext()) {
282 final StmtContext<?, ?, ?> next = iterator.next();
283 if (statementDef.equals(next.getPublicDefinition())) {
292 * Removes a statement context from the effective substatements
293 * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
294 * The statement context is removed only if both statement definition and statement argument match with
295 * one of the effective substatements' statement definition and argument.
297 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
299 * @param statementDef statement definition of the statement context to remove
300 * @param statementArg statement argument of the statement context to remove
302 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
303 final String statementArg) {
304 if (statementArg == null) {
305 removeStatementFromEffectiveSubstatements(statementDef);
308 if (effective.isEmpty()) {
312 final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
313 while (iterator.hasNext()) {
314 final Mutable<?, ?, ?> next = iterator.next();
315 if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
324 * adds effective statement to collection of substatements
326 * @param substatement substatement
327 * @throws IllegalStateException
328 * if added in declared phase
329 * @throws NullPointerException
330 * if statement parameter is null
332 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
333 beforeAddEffectiveStatement(1);
334 effective.add(substatement);
338 * adds effective statement to collection of substatements
340 * @param substatements substatements
341 * @throws IllegalStateException
342 * if added in declared phase
343 * @throws NullPointerException
344 * if statement parameter is null
346 public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
347 if (substatements.isEmpty()) {
351 substatements.forEach(Preconditions::checkNotNull);
352 beforeAddEffectiveStatement(substatements.size());
353 effective.addAll(substatements);
356 private void beforeAddEffectiveStatement(final int toAdd) {
357 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
358 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
359 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
360 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
362 if (effective.isEmpty()) {
363 effective = new ArrayList<>(toAdd);
368 * Create a new substatement at the specified offset.
370 * @param offset Substatement offset
371 * @param def definition context
372 * @param ref source reference
373 * @param argument statement argument
374 * @return A new substatement
376 public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
377 final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
378 final String argument) {
379 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
380 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
381 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
383 final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
384 offset, def, ref, argument);
385 if (implicitStatement.isPresent()) {
386 return implicitStatement.get().createSubstatement(offset, def, ref, argument);
389 final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
390 substatements = substatements.put(offset, ret);
391 def.onStatementAdded(ret);
396 * Lookup substatement by its offset in this statement.
398 * @param offset Substatement offset
399 * @return Substatement, or null if substatement does not exist.
401 final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
402 return substatements.get(offset);
406 public D buildDeclared() {
407 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
408 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
409 if (declaredInstance == null) {
410 declaredInstance = definition().getFactory().createDeclared(this);
412 return declaredInstance;
416 public E buildEffective() {
417 if (effectiveInstance == null) {
418 effectiveInstance = definition().getFactory().createEffective(this);
420 return effectiveInstance;
424 * tries to execute current {@link ModelProcessingPhase} of source parsing.
427 * to be executed (completed)
428 * @return if phase was successfully completed
429 * @throws SourceException
430 * when an error occured in source parsing
432 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
434 boolean finished = true;
435 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
436 if (!openMutations.isEmpty()) {
437 final Iterator<ContextMutation> it = openMutations.iterator();
438 while (it.hasNext()) {
439 final ContextMutation current = it.next();
440 if (current.isFinished()) {
447 if (openMutations.isEmpty()) {
448 phaseMutation.removeAll(phase);
449 if (phaseMutation.isEmpty()) {
450 phaseMutation = ImmutableMultimap.of();
455 for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
456 finished &= child.tryToCompletePhase(phase);
458 for (final Mutable<?, ?, ?> child : effective) {
459 if (child instanceof StatementContextBase) {
460 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
465 onPhaseCompleted(phase);
472 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
475 * that was to be completed (finished)
476 * @throws SourceException
477 * when an error occurred in source parsing
479 private void onPhaseCompleted(final ModelProcessingPhase phase) {
480 completedPhase = phase;
482 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
483 if (listeners.isEmpty()) {
487 final Iterator<OnPhaseFinished> listener = listeners.iterator();
488 while (listener.hasNext()) {
489 final OnPhaseFinished next = listener.next();
490 if (next.phaseFinished(this, phase)) {
495 if (listeners.isEmpty()) {
496 phaseListeners.removeAll(phase);
497 if (phaseListeners.isEmpty()) {
498 phaseListeners = ImmutableMultimap.of();
504 * Ends declared section of current node.
507 * @throws SourceException
509 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
510 definition().onDeclarationFinished(this, phase);
514 * @return statement definition
516 protected final StatementDefinitionContext<A, D, E> definition() {
521 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
522 definition().checkNamespaceAllowed(type);
526 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
528 // definition().onNamespaceElementAdded(this, type, key, value);
531 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
532 final OnNamespaceItemAdded listener) throws SourceException {
533 final Object potential = getFromNamespace(type, key);
534 if (potential != null) {
535 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
536 listener.namespaceItemAdded(this, type, key, potential);
540 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
541 Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
542 "Namespace {} does not support listeners", type);
544 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
545 casted.addValueListener(new ValueAddedListener<K>(this, key) {
547 void onValueAdded(final Object key, final Object value) {
548 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
554 * See {@link StatementSupport#getPublicView()}.
558 public StatementDefinition getPublicDefinition() {
559 return definition().getPublicView();
563 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
564 return getRoot().getSourceContext().newInferenceAction(phase);
567 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
568 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
572 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
574 * @throws SourceException
576 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
578 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
579 getStatementSourceReference());
580 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
581 getStatementSourceReference());
583 ModelProcessingPhase finishedPhase = completedPhase;
584 while (finishedPhase != null) {
585 if (phase.equals(finishedPhase)) {
586 listener.phaseFinished(this, finishedPhase);
589 finishedPhase = finishedPhase.getPreviousPhase();
591 if (phaseListeners.isEmpty()) {
592 phaseListeners = newMultimap();
595 phaseListeners.put(phase, listener);
599 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
601 * @throws IllegalStateException
602 * when the mutation was registered after phase was completed
604 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
605 ModelProcessingPhase finishedPhase = completedPhase;
606 while (finishedPhase != null) {
607 if (phase.equals(finishedPhase)) {
608 throw new IllegalStateException("Mutation registered after phase was completed at: " +
609 getStatementSourceReference());
611 finishedPhase = finishedPhase.getPreviousPhase();
614 if (phaseMutation.isEmpty()) {
615 phaseMutation = newMultimap();
617 phaseMutation.put(phase, mutation);
621 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
622 final KT key,final StmtContext<?, ?, ?> stmt) {
623 addContextToNamespace(namespace, key, stmt);
627 public final String toString() {
628 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
631 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
632 return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);