Refactor argument adaptation
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SubstatementContext.java
index a6553fc893683c9793a8e5ab008b79ca7d9df6fe..002b9bc50cd32cb4e4391646a003b80f6086fe5e 100644 (file)
  */
 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Verify;
+import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import org.opendaylight.yangtools.util.OptionalBoolean;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.YangVersion;
+import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
 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.StatementDefinition;
 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
+import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
+import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
-import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.GroupingUtils;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
-        extends StatementContextBase<A, D, E> {
+final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
+        StatementContextBase<A, D, E> {
+    private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
 
     private final StatementContextBase<?, ?, ?> parent;
     private final A argument;
-    private volatile SchemaPath schemaPath;
 
-    SubstatementContext(final StatementContextBase<?, ?, ?> parent, final ContextBuilder<A, D, E> builder) {
-        super(builder);
-        this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
-        this.argument = builder.getDefinition().parseArgumentValue(this, builder.getRawArgument());
-    }
-
-    @SuppressWarnings("unchecked")
-    SubstatementContext(final SubstatementContext<A, D, E> original,
-            final QNameModule newQNameModule,
-            final StatementContextBase<?, ?, ?> newParent, final TypeOfCopy typeOfCopy) {
-        super(original);
-        this.parent = newParent;
-
-        if (newQNameModule != null) {
-            if (original.argument instanceof QName) {
-                QName originalQName = (QName) original.argument;
-                this.argument = (A)
-                        getFromNamespace(QNameCacheNamespace.class,
-                            QName.create(newQNameModule, originalQName.getLocalName()));
-            } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
-                this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
-                                (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original,
-                                newQNameModule);
-            } else {
-                this.argument = original.argument;
-            }
-        } else {
-            this.argument = original.argument;
-        }
-    }
+    /**
+     * config statements are not all that common which means we are performing a recursive search towards the root
+     * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
+     * for the (usually non-existent) config statement.
+     *
+     * This field maintains a resolution cache, so once we have returned a result, we will keep on returning the same
+     * result without performing any lookups.
+     */
+    // BooleanField value
+    private byte configuration;
+
+    /**
+     * This field maintains a resolution cache for ignore config, so once we have returned a result, we will
+     * keep on returning the same result without performing any lookups.
+     */
+    // BooleanField value
+    private byte ignoreConfig;
+
+    /**
+     * This field maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
+     * keep on returning the same result without performing any lookups.
+     */
+    // BooleanField value
+    private byte ignoreIfFeature;
 
+    private volatile SchemaPath schemaPath;
 
-    private void copyDeclaredStmts(final SubstatementContext<A, D, E> original,
-            final QNameModule newQNameModule, final TypeOfCopy typeOfCopy) {
-        Collection<? extends StatementContextBase<?, ?, ?>> originalDeclaredSubstatements = original
-                .declaredSubstatements();
-        for (StatementContextBase<?, ?, ?> stmtContext : originalDeclaredSubstatements) {
-            if (GroupingUtils.needToCopyByUses(stmtContext)) {
-                StatementContextBase<?, ?, ?> copy = stmtContext.createCopy(
-                        newQNameModule, this, typeOfCopy);
-                this.addEffectiveSubstatement(copy);
-            } else if (GroupingUtils.isReusedByUses(stmtContext)) {
-                this.addEffectiveSubstatement(stmtContext);
-            }
-        }
+    SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
+            final StatementSourceReference ref, final String rawArgument) {
+        super(def, ref, rawArgument);
+        this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
+        this.argument = def.parseArgumentValue(this, rawStatementArgument());
     }
 
-    private void copyEffectiveStmts(final SubstatementContext<A, D, E> original,
-            final QNameModule newQNameModule, final TypeOfCopy typeOfCopy) {
-        Collection<? extends StatementContextBase<?, ?, ?>> originalEffectiveSubstatements = original
-                .effectiveSubstatements();
-        for (StatementContextBase<?, ?, ?> stmtContext : originalEffectiveSubstatements) {
-            if (GroupingUtils.needToCopyByUses(stmtContext)) {
-                StatementContextBase<?, ?, ?> copy = stmtContext.createCopy(
-                        newQNameModule, this, typeOfCopy);
-                this.addEffectiveSubstatement(copy);
-            } else if (GroupingUtils.isReusedByUses(stmtContext)) {
-                this.addEffectiveSubstatement(stmtContext);
-            }
-        }
+    SubstatementContext(final StatementContextBase<A, D, E> original, final StatementContextBase<?, ?, ?> parent,
+            final A argument, final CopyType copyType) {
+        super(original, copyType);
+        this.parent = Preconditions.checkNotNull(parent);
+        this.argument = argument;
     }
 
     @Override
@@ -110,6 +101,11 @@ final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends Eff
         return parent;
     }
 
+    @Override
+    public StorageNodeType getStorageNodeType() {
+        return StorageNodeType.STATEMENT_LOCAL;
+    }
+
     @Override
     public NamespaceStorageNode getParentNamespaceStorage() {
         return parent;
@@ -120,6 +116,7 @@ final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends Eff
         return parent.getBehaviourRegistry();
     }
 
+    @Nonnull
     @Override
     public RootStatementContext<?, ?, ?> getRoot() {
         return parent.getRoot();
@@ -130,31 +127,80 @@ final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends Eff
         return argument;
     }
 
-    @Override
-    public StatementContextBase<?, ?, ?> createCopy(
-            final StatementContextBase<?, ?, ?> newParent, final TypeOfCopy typeOfCopy) {
-        return createCopy(null, newParent, typeOfCopy);
+    StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
+            final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
+        Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
+                "Attempted to copy statement %s which has completed phase %s", this, getCompletedPhase());
+
+        final A argumentCopy = newQNameModule == null ? argument
+                : definition().adaptArgumentValue(this, newQNameModule);
+        final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newParent, argumentCopy, typeOfCopy);
+
+        definition().onStatementAdded(copy);
+
+        copy.copyStatements(this, newQNameModule, typeOfCopy);
+        return copy;
     }
 
-    @Override
-    public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
-            final StatementContextBase<?, ?, ?> newParent, final TypeOfCopy typeOfCopy) {
-        SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
+    private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
+            final CopyType typeOfCopy) {
+        final Collection<? extends Mutable<?, ?, ?>> declared = original.mutableDeclaredSubstatements();
+        final Collection<? extends Mutable<?, ?, ?>> effective = original.mutableEffectiveSubstatements();
+        final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
+
+        for (final Mutable<?, ?, ?> stmtContext : declared) {
+            if (stmtContext.isSupportedByFeatures()) {
+                copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
+            }
+        }
+
+        for (final Mutable<?, ?, ?> stmtContext : effective) {
+            copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
+        }
 
-        copy.addAllToCopyHistory(this.getCopyHistory());
-        copy.addToCopyHistory(typeOfCopy);
+        addEffectiveSubstatements(buffer);
+    }
 
-        if (this.getOriginalCtx() != null) {
-            copy.setOriginalCtx(this.getOriginalCtx());
+    private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final QNameModule newQNameModule,
+            final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer) {
+        if (needToCopyByUses(stmtContext)) {
+            final Mutable<?, ?, ?> copy = childCopyOf(stmtContext, typeOfCopy, newQNameModule);
+            LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
+            buffer.add(copy);
+        } else if (isReusedByUses(stmtContext)) {
+            LOG.debug("Reusing substatement {} for {}", stmtContext, this);
+            buffer.add(stmtContext);
         } else {
-            copy.setOriginalCtx(this);
+            LOG.debug("Skipping statement {}", stmtContext);
         }
+    }
 
-        definition().onStatementAdded(copy);
+    // FIXME: revise this, as it seems to be wrong
+    private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
+        YangStmtMapping.DESCRIPTION,
+        YangStmtMapping.REFERENCE,
+        YangStmtMapping.STATUS);
+    private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
+        YangStmtMapping.TYPE,
+        YangStmtMapping.TYPEDEF,
+        YangStmtMapping.USES);
+
+    private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
+        final StatementDefinition def = stmtContext.getPublicDefinition();
+        if (REUSED_DEF_SET.contains(def)) {
+            LOG.debug("Will reuse {} statement {}", def, stmtContext);
+            return false;
+        }
+        if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
+            return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
+        }
 
-        copy.copyDeclaredStmts(this, newQNameModule, typeOfCopy);
-        copy.copyEffectiveStmts(this, newQNameModule, typeOfCopy);
-        return copy;
+        LOG.debug("Will copy {} statement {}", def, stmtContext);
+        return true;
+    }
+
+    private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
+        return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
     }
 
     private boolean isSupportedAsShorthandCase() {
@@ -168,10 +214,13 @@ final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends Eff
         Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
         final SchemaPath parentPath = maybeParentPath.get();
 
+        if (StmtContextUtils.isUnknownStatement(this)) {
+            return parentPath.createChild(getPublicDefinition().getStatementName());
+        }
         if (argument instanceof QName) {
-            QName qname = (QName) argument;
+            final QName qname = (QName) argument;
             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
-                return maybeParentPath.orNull();
+                return maybeParentPath.orElse(null);
             }
 
             final SchemaPath path;
@@ -186,25 +235,23 @@ final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends Eff
         }
         if (argument instanceof String) {
             // FIXME: This may yield illegal argument exceptions
-            final StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx();
-            final QName qname = (originalCtx != null) ? Utils.qNameFromArgument(originalCtx, (String) argument)
-                    : Utils.qNameFromArgument(this, (String) argument);
+            final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
+            final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
             return parentPath.createChild(qname);
         }
-        if (argument instanceof SchemaNodeIdentifier &&
-                (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
-                   || StmtContextUtils.producesDeclared(this, RefineStatement.class))) {
+        if (argument instanceof SchemaNodeIdentifier
+                && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
+                        || StmtContextUtils.producesDeclared(this, RefineStatement.class)
+                        || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
 
             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
         }
-        if (Utils.isUnknownNode(this)) {
-            return parentPath.createChild(getPublicDefinition().getStatementName());
-        }
 
         // FIXME: this does not look right
-        return maybeParentPath.orNull();
+        return maybeParentPath.orElse(null);
     }
 
+    @Nonnull
     @Override
     public Optional<SchemaPath> getSchemaPath() {
         SchemaPath local = schemaPath;
@@ -219,50 +266,96 @@ final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends Eff
 
         }
 
-        return Optional.fromNullable(local);
-    }
-
-    @Override
-    public boolean isRootContext() {
-        return false;
+        return Optional.ofNullable(local);
     }
 
     @Override
     public boolean isConfiguration() {
-        StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils
-                .findFirstSubstatement(this, ConfigStatement.class);
-
-        /*
-         * If "config" statement is not specified, the default is the same as
-         * the parent schema node's "config" value.
-         */
-        if (configStatement == null) {
-            return parent.isConfiguration();
+        if (isIgnoringConfig()) {
+            return true;
         }
 
-        /*
-         * If a parent node has "config" set to "true", the node underneath it can
-         * have "config" set to "true" or "false".
-         */
-        if (parent.isConfiguration()) {
-            return configStatement.getStatementArgument();
+        if (OptionalBoolean.isPresent(configuration)) {
+            return OptionalBoolean.get(configuration);
         }
 
-        /*
-         * If a parent node has "config" set to "false", no node underneath it
-         * can have "config" set to "true", therefore only "false" is permitted.
-         */
-        if (!configStatement.getStatementArgument()) {
-            return false;
+        final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
+            ConfigStatement.class);
+        final boolean parentIsConfig = parent.isConfiguration();
+
+        final boolean isConfig;
+        if (configStatement != null) {
+            isConfig = configStatement.getStatementArgument();
+
+            // Validity check: if parent is config=false this cannot be a config=true
+            InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
+                    "Parent node has config=false, this node must not be specifed as config=true");
+        } else {
+            // If "config" statement is not specified, the default is the same as the parent's "config" value.
+            isConfig = parentIsConfig;
         }
 
-        throw new InferenceException(
-                "Parent node has config statement set to false, therefore no node underneath it can have config set to true",
-                getStatementSourceReference());
+        // Resolved, make sure we cache this return
+        configuration = OptionalBoolean.of(isConfig);
+        return isConfig;
     }
 
     @Override
     public boolean isEnabledSemanticVersioning() {
         return parent.isEnabledSemanticVersioning();
     }
+
+    @Override
+    public YangVersion getRootVersion() {
+        return getRoot().getRootVersion();
+    }
+
+    @Override
+    public void setRootVersion(final YangVersion version) {
+        getRoot().setRootVersion(version);
+    }
+
+    @Override
+    public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
+        getRoot().addMutableStmtToSeal(mutableStatement);
+    }
+
+    @Override
+    public void addRequiredModule(final ModuleIdentifier dependency) {
+        getRoot().addRequiredModule(dependency);
+    }
+
+    @Override
+    public void setRootIdentifier(final ModuleIdentifier identifier) {
+        getRoot().setRootIdentifier(identifier);
+    }
+
+    @Override
+    protected boolean isIgnoringIfFeatures() {
+        if (OptionalBoolean.isPresent(ignoreIfFeature)) {
+            return OptionalBoolean.get(ignoreIfFeature);
+        }
+
+        final boolean ret = definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures();
+        ignoreIfFeature = OptionalBoolean.of(ret);
+
+        return ret;
+    }
+
+    @Override
+    protected boolean isIgnoringConfig() {
+        if (OptionalBoolean.isPresent(ignoreConfig)) {
+            return OptionalBoolean.get(ignoreConfig);
+        }
+
+        final boolean ret = definition().isIgnoringConfig() || parent.isIgnoringConfig();
+        ignoreConfig = OptionalBoolean.of(ret);
+
+        return ret;
+    }
+
+    @Override
+    protected boolean isParentSupportedByFeatures() {
+        return parent.isSupportedByFeatures();
+    }
 }