Propagate @Nonnull and @Nullable annotations
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.java
index bb45a4a78ca968922f65b5602e85080de9a19fb4..61244458cd561d6581535248b6f9dfdb3626b17f 100644 (file)
@@ -7,8 +7,13 @@
  */
 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
 
+import com.google.common.base.MoreObjects;
+import com.google.common.base.MoreObjects.ToStringHelper;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMultimap;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Multimaps;
 import java.util.ArrayList;
@@ -17,11 +22,8 @@ import java.util.Collections;
 import java.util.EnumMap;
 import java.util.EventListener;
 import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
 import javax.annotation.Nonnull;
 import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
@@ -43,6 +45,37 @@ import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWit
 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
 
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    private final class SubContextBuilder extends ContextBuilder {
+        final int childId;
+
+        SubContextBuilder(final int childId, final StatementDefinitionContext def,
+            final StatementSourceReference sourceRef) {
+            super(def, sourceRef);
+            this.childId = childId;
+        }
+
+        @Override
+        public StatementContextBase build() {
+            StatementContextBase<?, ?, ?> potential = substatements.get(childId);
+            if (potential == null) {
+                potential = new SubstatementContext(StatementContextBase.this, this);
+                substatements = substatements.put(childId, potential);
+                getDefinition().onStatementAdded(potential);
+            }
+            potential.resetLists();
+            switch (this.getStamementSource().getStatementSource()) {
+            case DECLARATION:
+                addDeclaredSubstatement(potential);
+                break;
+            case CONTEXT:
+                addEffectiveSubstatement(potential);
+                break;
+            }
+            return potential;
+        }
+    }
+
     /**
      * event listener when an item is added to model namespace
      */
@@ -75,17 +108,12 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     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 Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
+    private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
+    private Collection<StatementContextBase<?, ?, ?>> declared = ImmutableList.of();
+    private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
+    private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
+    private StatementMap substatements = StatementMap.empty();
 
     private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
     private CopyHistory copyHistory = CopyHistory.original();
@@ -119,8 +147,24 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
 
     @Override
     public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
+        if (effectOfStatement.isEmpty()) {
+            effectOfStatement = new ArrayList<>(1);
+        }
         effectOfStatement.add(ctx);
     }
+
+    @Override
+    public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
+        if (ctxs.isEmpty()) {
+            return;
+        }
+
+        if (effectOfStatement.isEmpty()) {
+            effectOfStatement = new ArrayList<>(ctxs.size());
+        }
+        effectOfStatement.addAll(ctxs);
+    }
+
     @Override
     public SupportedByFeatures getSupportedByFeatures() {
         return supportedByFeatures;
@@ -190,6 +234,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     /**
      * @return root context of statement
      */
+    @Nonnull
     @Override
     public abstract RootStatementContext<?, ?, ?> getRoot();
 
@@ -204,6 +249,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     /**
      * @return origin of statement
      */
+    @Nonnull
     @Override
     public StatementSource getStatementSource() {
         return statementDeclSource.getStatementSource();
@@ -212,6 +258,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     /**
      * @return reference of statement source
      */
+    @Nonnull
     @Override
     public StatementSourceReference getStatementSourceReference() {
         return statementDeclSource;
@@ -225,35 +272,44 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         return identifier.getArgument();
     }
 
-    /**
-     * @return collection of declared substatements
-     */
-    @Override
-    public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
-        return Collections.unmodifiableCollection(declared);
+    private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
+        if (input instanceof ImmutableCollection) {
+            return input;
+        }
+
+        return Collections.unmodifiableCollection(input);
     }
 
-    /**
-     * @return collection of substatements
-     */
+    @Nonnull
     @Override
-    public Collection<StatementContextBase<?, ?, ?>> substatements() {
-        return Collections.unmodifiableCollection(substatements.values());
+    public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
+        return maybeWrap(declared);
     }
 
-    /**
-     * @return collection of effective substatements
-     */
+    @Nonnull
     @Override
     public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
-        return Collections.unmodifiableCollection(effective);
+        return maybeWrap(effective);
     }
 
     public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
-        effective.removeAll(substatements);
+        if (!effective.isEmpty()) {
+            effective.removeAll(substatements);
+            shrinkEffective();
+        }
+    }
+
+    private void shrinkEffective() {
+        if (effective.isEmpty()) {
+            effective = ImmutableList.of();
+        }
     }
 
     public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
+        if (effective.isEmpty()) {
+            return;
+        }
+
         final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
         while (iterator.hasNext()) {
             final StatementContextBase<?, ?, ?> next = iterator.next();
@@ -261,6 +317,8 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
                 iterator.remove();
             }
         }
+
+        shrinkEffective();
     }
 
     /**
@@ -273,14 +331,40 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      *             if statement parameter is null
      */
     public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
+        Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
+            getStatementSourceReference());
+        beforeAddEffectiveStatement(1);
+        effective.add(substatement);
+    }
 
+    /**
+     * adds effective statement to collection of substatements
+     *
+     * @param substatements substatements
+     * @throws IllegalStateException
+     *             if added in declared phase
+     * @throws NullPointerException
+     *             if statement parameter is null
+     */
+    public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
+        if (substatements.isEmpty()) {
+            return;
+        }
+
+        substatements.forEach(Preconditions::checkNotNull);
+        beforeAddEffectiveStatement(substatements.size());
+        effective.addAll(substatements);
+    }
+
+    private void beforeAddEffectiveStatement(final int toAdd) {
         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
 
-        effective.add(Preconditions.checkNotNull(substatement,
-                "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
+        if (effective.isEmpty()) {
+            effective = new ArrayList<>(toAdd);
+        }
     }
 
     /**
@@ -298,49 +382,24 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
 
+        if (declared.isEmpty()) {
+            declared = new ArrayList<>(1);
+        }
         declared.add(Preconditions.checkNotNull(substatement,
                 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
     }
 
     /**
-     * builds new substatement from statement definition context and statement source reference
+     * 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(final StatementDefinitionContext<?, ?, ?> def,
+    ContextBuilder<?, ?, ?> substatementBuilder(final int childId, final StatementDefinitionContext<?, ?, ?> def,
             final StatementSourceReference ref) {
-        return new ContextBuilder(def, ref) {
-
-            @Override
-            public StatementContextBase build() throws SourceException {
-                StatementContextBase<?, ?, ?> potential = null;
-
-                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()) {
-                case DECLARATION:
-                    addDeclaredSubstatement(potential);
-                    break;
-                case CONTEXT:
-                    addEffectiveSubstatement(potential);
-                    break;
-                }
-                return potential;
-            }
-        };
+        return new SubContextBuilder(childId, def, ref);
     }
 
     /**
@@ -387,7 +446,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
                 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
 
-        declared.clear();
+        declared = ImmutableList.of();
     }
 
     /**
@@ -400,16 +459,28 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      *             when an error occured in source parsing
      */
     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
-        final Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
+
         boolean finished = true;
-        while (openMutations.hasNext()) {
-            final ContextMutation current = openMutations.next();
-            if (current.isFinished()) {
-                openMutations.remove();
-            } else {
-                finished = false;
+        final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
+        if (!openMutations.isEmpty()) {
+            final Iterator<ContextMutation> it = openMutations.iterator();
+            while (it.hasNext()) {
+                final ContextMutation current = it.next();
+                if (current.isFinished()) {
+                    it.remove();
+                } else {
+                    finished = false;
+                }
+            }
+
+            if (openMutations.isEmpty()) {
+                phaseMutation.removeAll(phase);
+                if (phaseMutation.isEmpty()) {
+                    phaseMutation = ImmutableMultimap.of();
+                }
             }
         }
+
         for (final StatementContextBase<?, ?, ?> child : declared) {
             finished &= child.tryToCompletePhase(phase);
         }
@@ -434,13 +505,26 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
      */
     private void onPhaseCompleted(final ModelProcessingPhase phase) {
         completedPhase = phase;
-        final Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
+
+        final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
+        if (listeners.isEmpty()) {
+            return;
+        }
+
+        final Iterator<OnPhaseFinished> listener = listeners.iterator();
         while (listener.hasNext()) {
             final OnPhaseFinished next = listener.next();
             if (next.phaseFinished(this, phase)) {
                 listener.remove();
             }
         }
+
+        if (listeners.isEmpty()) {
+            phaseListeners.removeAll(phase);
+            if (phaseListeners.isEmpty()) {
+                phaseListeners = ImmutableMultimap.of();
+            }
+        }
     }
 
     /**
@@ -501,6 +585,7 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     /**
      * @see StatementSupport#getPublicView()
      */
+    @Nonnull
     @Override
     public StatementDefinition getPublicDefinition() {
         return definition().getPublicView();
@@ -514,6 +599,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
         return getRoot().getSourceContext().newInferenceAction(phase);
     }
 
+    private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
+        return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
+    }
+
     /**
      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
      *
@@ -534,6 +623,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
             }
             finishedPhase = finishedPhase.getPreviousPhase();
         }
+        if (phaseListeners.isEmpty()) {
+            phaseListeners = newMultimap();
+        }
+
         phaseListeners.put(phase, listener);
     }
 
@@ -552,6 +645,10 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
             }
             finishedPhase = finishedPhase.getPreviousPhase();
         }
+
+        if (phaseMutation.isEmpty()) {
+            phaseMutation = newMultimap();
+        }
         phaseMutation.put(phase, mutation);
     }
 
@@ -568,6 +665,15 @@ public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E
     @Override
     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);
+        addContextToNamespace(namespace, key, stmt);
+    }
+
+    @Override
+    public final String toString() {
+        return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
+    }
+
+    protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+        return toStringHelper.add("definition", definition).add("id", identifier);
     }
 }