BUG-6522: create a specialized CopyHistory object
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.java
index 83356ed615814456088921510963fd803709a5c8..bb45a4a78ca968922f65b5602e85080de9a19fb4 100644 (file)
@@ -7,16 +7,14 @@
  */
 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
 
-import java.util.LinkedList;
-
-import java.util.List;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Throwables;
-import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Multimap;
+import com.google.common.collect.Multimaps;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.EnumMap;
 import java.util.EventListener;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
@@ -29,6 +27,8 @@ import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
@@ -47,19 +47,20 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      * event listener when an item is added to model namespace
      */
     interface OnNamespaceItemAdded extends EventListener {
-
-        void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value)
-                throws SourceException;
-
+        /**
+         * @throws SourceException
+         */
+        void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
     }
 
     /**
      * event listener when a parsing {@link ModelProcessingPhase} is completed
      */
     interface OnPhaseFinished extends EventListener {
-
-        boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase) throws SourceException;
-
+        /**
+         * @throws SourceException
+         */
+        boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
     }
 
     /**
@@ -68,40 +69,67 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     interface ContextMutation {
 
         boolean isFinished();
-
     }
 
     private final StatementDefinitionContext<A, D, E> definition;
     private final StatementIdentifier identifier;
     private final StatementSourceReference statementDeclSource;
+
+    private final Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners =
+            Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
+
+    private final Multimap<ModelProcessingPhase, ContextMutation> phaseMutation =
+            Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
+
+    private final Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>(1);
+
+    private final Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>(1);
+    private final Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>(1);
+    private final Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>(1);
+
+    private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
+    private CopyHistory copyHistory = CopyHistory.original();
+    private boolean isSupportedToBuildEffective = true;
+    private ModelProcessingPhase completedPhase = null;
+    private StatementContextBase<?, ?, ?> originalCtx;
+    private D declaredInstance;
+    private E effectiveInstance;
     private int order = 0;
 
-    private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>();
+    StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
+        this.definition = builder.getDefinition();
+        this.identifier = builder.createIdentifier();
+        this.statementDeclSource = builder.getStamementSource();
+    }
 
-    private Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
-    private Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
-    private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>();
+    StatementContextBase(final StatementContextBase<A, D, E> original) {
+        this.definition = Preconditions.checkNotNull(original.definition,
+                "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
+        this.identifier = Preconditions.checkNotNull(original.identifier,
+                "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
+        this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
+                "Statement context statementDeclSource cannot be null copying from: %s",
+                original.getStatementSourceReference());
+    }
 
+    @Override
     public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
         return effectOfStatement;
     }
 
-    public void addAsEffectOfStatement(StatementContextBase<?, ?, ?> ctx) {
+    @Override
+    public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
         effectOfStatement.add(ctx);
     }
+    @Override
+    public SupportedByFeatures getSupportedByFeatures() {
+        return supportedByFeatures;
+    }
 
-    private ModelProcessingPhase completedPhase;
-
-    private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = HashMultimap.create();
-    private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = HashMultimap.create();
-
-    private D declaredInstance;
-    private E effectiveInstance;
-
-    private StatementContextBase<?, ?, ?> originalCtx;
-    private List<TypeOfCopy> copyHistory;
-
-    private boolean isSupportedToBuildEffective = true;
+    @Override
+    public void setSupportedByFeatures(final boolean isSupported) {
+        this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
+    }
 
     @Override
     public boolean isSupportedToBuildEffective() {
@@ -109,23 +137,18 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     }
 
     @Override
-    public void setIsSupportedToBuildEffective(boolean isSupportedToBuildEffective) {
+    public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
     }
 
     @Override
-    public List<TypeOfCopy> getCopyHistory() {
+    public CopyHistory getCopyHistory() {
         return copyHistory;
     }
 
     @Override
-    public void addToCopyHistory(TypeOfCopy typeOfCopy) {
-        this.copyHistory.add(typeOfCopy);
-    }
-
-    @Override
-    public void addAllToCopyHistory(List<TypeOfCopy> typeOfCopyList) {
-        this.copyHistory.addAll(typeOfCopyList);
+    public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
+        copyHistory = copyHistory.append(typeOfCopy, toAppend);
     }
 
     @Override
@@ -134,12 +157,12 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     }
 
     @Override
-    public void setOriginalCtx(StatementContextBase<?, ?, ?> originalCtx) {
+    public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
         this.originalCtx = originalCtx;
     }
 
     @Override
-    public void setOrder(int order) {
+    public void setOrder(final int order) {
         this.order = order;
     }
 
@@ -154,34 +177,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     }
 
     @Override
-    public void setCompletedPhase(ModelProcessingPhase completedPhase) {
+    public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
         this.completedPhase = completedPhase;
     }
 
-    StatementContextBase(@Nonnull ContextBuilder<A, D, E> builder) throws SourceException {
-        this.definition = builder.getDefinition();
-        this.identifier = builder.createIdentifier();
-        this.statementDeclSource = builder.getStamementSource();
-        this.completedPhase = null;
-        initCopyHistory();
-    }
-
-    StatementContextBase(StatementContextBase<A, D, E> original) {
-        this.definition = Preconditions
-                .checkNotNull(original.definition, "Statement context definition cannot be null");
-        this.identifier = Preconditions
-                .checkNotNull(original.identifier, "Statement context identifier cannot be null");
-        this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
-                "Statement context statementDeclSource cannot be null");
-        this.completedPhase = null;
-        initCopyHistory();
-    }
-
-    private void initCopyHistory() {
-        this.copyHistory = new LinkedList<>();
-        this.copyHistory.add(TypeOfCopy.ORIGINAL);
-    }
-
     /**
      * @return context of parent of statement
      */
@@ -234,6 +233,14 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         return Collections.unmodifiableCollection(declared);
     }
 
+    /**
+     * @return collection of substatements
+     */
+    @Override
+    public Collection<StatementContextBase<?, ?, ?>> substatements() {
+        return Collections.unmodifiableCollection(substatements.values());
+    }
+
     /**
      * @return collection of effective substatements
      */
@@ -242,14 +249,14 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         return Collections.unmodifiableCollection(effective);
     }
 
-    public void removeStatementsFromEffectiveSubstatements(Collection<StatementContextBase<?, ?, ?>> substatements) {
+    public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
         effective.removeAll(substatements);
     }
 
-    public void removeStatementFromEffectiveSubstatements(StatementDefinition refineSubstatementDef) {
-        Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
+    public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
+        final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
         while (iterator.hasNext()) {
-            StatementContextBase<?, ?, ?> next = iterator.next();
+            final StatementContextBase<?, ?, ?> next = iterator.next();
             if (next.getPublicDefinition().equals(refineSubstatementDef)) {
                 iterator.remove();
             }
@@ -259,58 +266,68 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     /**
      * adds effective statement to collection of substatements
      *
+     * @param substatement substatement
      * @throws IllegalStateException
      *             if added in declared phase
      * @throws NullPointerException
      *             if statement parameter is null
      */
-    public void addEffectiveSubstatement(StatementContextBase<?, ?, ?> substatement) {
+    public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
 
         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
-                "Effective statement cannot be added in declared phase");
+                "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
 
         effective.add(Preconditions.checkNotNull(substatement,
-                "StatementContextBase effective substatement cannot be null"));
+                "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
     }
 
     /**
      * adds declared statement to collection of substatements
      *
+     * @param substatement substatement
      * @throws IllegalStateException
      *             if added in effective phase
      * @throws NullPointerException
      *             if statement parameter is null
      */
-    public void addDeclaredSubstatement(StatementContextBase<?, ?, ?> substatement) {
+    public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
 
         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
-                "Declared statement cannot be added in effective phase");
+                "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
 
         declared.add(Preconditions.checkNotNull(substatement,
-                "StatementContextBase declared substatement cannot be null"));
+                "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
     }
 
     /**
      * builds new substatement from statement definition context and statement source reference
+     *
+     * @param def definition context
+     * @param ref source reference
+     *
+     * @return instance of ContextBuilder
      */
     @SuppressWarnings({ "rawtypes", "unchecked" })
-    public ContextBuilder<?, ?, ?> substatementBuilder(StatementDefinitionContext<?, ?, ?> def,
-            StatementSourceReference ref) {
+    public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
+            final StatementSourceReference ref) {
         return new ContextBuilder(def, ref) {
 
             @Override
             public StatementContextBase build() throws SourceException {
                 StatementContextBase<?, ?, ?> potential = null;
 
-                if (getDefinition().getPublicView() != Rfc6020Mapping.AUGMENT) {
+                final StatementDefinition stmtDef = getDefinition().getPublicView();
+                if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
+                        && stmtDef != Rfc6020Mapping.TYPE) {
                     potential = substatements.get(createIdentifier());
                 }
                 if (potential == null) {
                     potential = new SubstatementContext(StatementContextBase.this, this);
                     substatements.put(createIdentifier(), potential);
+                    getDefinition().onStatementAdded(potential);
                 }
                 potential.resetLists();
                 switch (this.getStamementSource().getStatementSource()) {
@@ -368,7 +385,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
 
         final SourceSpecificContext sourceContext = getRoot().getSourceContext();
         Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
-                "Declared statements list cannot be cleared in effective phase");
+                "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
 
         declared.clear();
     }
@@ -382,21 +399,21 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      * @throws SourceException
      *             when an error occured in source parsing
      */
-    boolean tryToCompletePhase(ModelProcessingPhase phase) throws SourceException {
-        Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
+    boolean tryToCompletePhase(final ModelProcessingPhase phase) {
+        final Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
         boolean finished = true;
         while (openMutations.hasNext()) {
-            ContextMutation current = openMutations.next();
+            final ContextMutation current = openMutations.next();
             if (current.isFinished()) {
                 openMutations.remove();
             } else {
                 finished = false;
             }
         }
-        for (StatementContextBase<?, ?, ?> child : declared) {
+        for (final StatementContextBase<?, ?, ?> child : declared) {
             finished &= child.tryToCompletePhase(phase);
         }
-        for (StatementContextBase<?, ?, ?> child : effective) {
+        for (final StatementContextBase<?, ?, ?> child : effective) {
             finished &= child.tryToCompletePhase(phase);
         }
 
@@ -415,11 +432,11 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      * @throws SourceException
      *             when an error occured in source parsing
      */
-    private void onPhaseCompleted(ModelProcessingPhase phase) throws SourceException {
+    private void onPhaseCompleted(final ModelProcessingPhase phase) {
         completedPhase = phase;
-        Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
+        final Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
         while (listener.hasNext()) {
-            OnPhaseFinished next = listener.next();
+            final OnPhaseFinished next = listener.next();
             if (next.phaseFinished(this, phase)) {
                 listener.remove();
             }
@@ -432,7 +449,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      * @param ref
      * @throws SourceException
      */
-    void endDeclared(StatementSourceReference ref, ModelProcessingPhase phase) throws SourceException {
+    void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
         definition().onDeclarationFinished(this, phase);
     }
 
@@ -444,36 +461,36 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     }
 
     @Override
-    protected void checkLocalNamespaceAllowed(Class<? extends IdentifierNamespace<?, ?>> type) {
+    protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
         definition().checkNamespaceAllowed(type);
     }
 
     /**
      * occurs when an item is added to model namespace
      *
-     * @throws SourceException
+     * @throws SourceException instance of SourceException
      */
     @Override
-    protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(Class<N> type, K key, V value) {
+    protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
         // definition().onNamespaceElementAdded(this, type, key, value);
     }
 
-    <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, K key,
+    <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
             final OnNamespaceItemAdded listener) throws SourceException {
-        Object potential = getFromNamespace(type, key);
+        final Object potential = getFromNamespace(type, key);
         if (potential != null) {
             listener.namespaceItemAdded(this, type, key, potential);
             return;
         }
-        NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
+        final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
         if (behaviour instanceof NamespaceBehaviourWithListeners) {
-            NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
-            casted.addValueListener(key, new ValueAddedListener(this) {
+            final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
+            casted.addValueListener(new ValueAddedListener<K>(this, key) {
                 @Override
-                void onValueAdded(Object key, Object value) {
+                void onValueAdded(final Object key, final Object value) {
                     try {
                         listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
-                    } catch (SourceException e) {
+                    } catch (final SourceException e) {
                         throw Throwables.propagate(e);
                     }
                 }
@@ -493,7 +510,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      * @return new {@link ModelActionBuilder} for the phase
      */
     @Override
-    public ModelActionBuilder newInferenceAction(ModelProcessingPhase phase) {
+    public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
         return getRoot().getSourceContext().newInferenceAction(phase);
     }
 
@@ -502,10 +519,12 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      *
      * @throws SourceException
      */
-    void addPhaseCompletedListener(ModelProcessingPhase phase, OnPhaseFinished listener) throws SourceException {
+    void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
 
-        Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
-        Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
+        Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
+                getStatementSourceReference());
+        Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
+                getStatementSourceReference());
 
         ModelProcessingPhase finishedPhase = completedPhase;
         while (finishedPhase != null) {
@@ -524,11 +543,12 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      * @throws IllegalStateException
      *             when the mutation was registered after phase was completed
      */
-    void addMutation(ModelProcessingPhase phase, ContextMutation mutation) {
+    void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
         ModelProcessingPhase finishedPhase = completedPhase;
         while (finishedPhase != null) {
             if (phase.equals(finishedPhase)) {
-                throw new IllegalStateException("Mutation registered after phase was completed.");
+                throw new IllegalStateException("Mutation registered after phase was completed at: "  +
+                        getStatementSourceReference());
             }
             finishedPhase = finishedPhase.getPreviousPhase();
         }
@@ -546,8 +566,8 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      *            to be added to namespace map
      */
     @Override
-    public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(Class<N> namespace, KT key,
-            StmtContext<?, ?, ?> stmt) {
+    public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
+            final StmtContext<?, ?, ?> stmt) {
         addContextToNamespace(namespace, (K) key, stmt);
     }
 }