Add SchemaInferenceStack.ofDataTreePath()
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / SchemaTracker.java
index 40e86f3ee8e7a5d2adc2e0b9c1f01c0e17cd331d..455c1fe23bcfc77c82d175fc65b5daa086fcddac 100644 (file)
@@ -8,17 +8,16 @@
 package org.opendaylight.yangtools.yang.data.impl.codec;
 
 import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Verify.verify;
 import static java.util.Objects.requireNonNull;
 
 import com.google.common.annotations.Beta;
 import com.google.common.collect.Iterables;
 import java.io.IOException;
 import java.util.ArrayDeque;
-import java.util.Collection;
 import java.util.Deque;
 import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyxmlSchemaNode;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
@@ -32,121 +31,168 @@ import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerLike;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
-import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
+import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
+import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Utility class for tracking the underlying state of the underlying
- * schema node.
+ * Utility class for tracking the underlying state of the underlying schema node.
  */
 @Beta
 public final class SchemaTracker {
     private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
+
     private final Deque<WithStatus> schemaStack = new ArrayDeque<>();
+    private final SchemaInferenceStack dataTree;
     private final DataNodeContainer root;
 
-    private SchemaTracker(final DataNodeContainer root) {
-        this.root = requireNonNull(root);
+    private SchemaTracker(final EffectiveModelContext context) {
+        root = requireNonNull(context);
+        dataTree = SchemaInferenceStack.of(context);
+    }
+
+    private SchemaTracker(final SchemaInferenceStack dataTree) {
+        this.dataTree = requireNonNull(dataTree);
+        if (!dataTree.isEmpty()) {
+            final EffectiveStatement<?, ?> current = dataTree.currentStatement();
+            checkArgument(current instanceof DataNodeContainer, "Cannot instantiate on %s", current);
+
+            root = (DataNodeContainer) current;
+        } else {
+            root = dataTree.getEffectiveModelContext();
+        }
+    }
+
+    /**
+     * Create a new writer with the specified inference state as its root.
+     *
+     * @param root Root inference state
+     * @return A new {@link NormalizedNodeStreamWriter}
+     * @throws NullPointerException if {@code root} is null
+     */
+    public static @NonNull SchemaTracker create(final EffectiveStatementInference root) {
+        return new SchemaTracker(SchemaInferenceStack.ofInference(root));
+    }
+
+    /**
+     * Create a new writer with the specified inference state as its root.
+     *
+     * @param root Root inference state
+     * @return A new {@link NormalizedNodeStreamWriter}
+     * @throws NullPointerException if {@code root} is null
+     */
+    public static @NonNull SchemaTracker create(final Inference root) {
+        return new SchemaTracker(root.toSchemaInferenceStack());
     }
 
     /**
-     * Create a new writer with the specified node as its root.
+     * Create a new writer at the root of specified {@link EffectiveModelContext}.
      *
-     * @param root Root node
+     * @param context effective model context
      * @return A new {@link NormalizedNodeStreamWriter}
+     * @throws NullPointerException if {@code context} is null
      */
-    public static @NonNull SchemaTracker create(final DataNodeContainer root) {
-        return new SchemaTracker(root);
+    public static @NonNull SchemaTracker create(final EffectiveModelContext context) {
+        return new SchemaTracker(context);
     }
 
     /**
      * Create a new writer with the specified context and rooted in the specified schema path.
      *
-     * @param context Associated {@link SchemaContext}
+     * @param context Associated {@link EffectiveModelContext}
      * @param path schema path
-     * @return A new {@link NormalizedNodeStreamWriter}
+     * @return A new {@link SchemaTracker}
+     * @throws NullPointerException if any argument is null
+     * @throws IllegalArgumentException if {@code path} does not point to a valid root
      */
-    public static @NonNull SchemaTracker create(final SchemaContext context, final SchemaPath path) {
-        final Collection<SchemaNode> schemaNodes = SchemaUtils.findParentSchemaNodesOnPath(context, path);
-        checkArgument(!schemaNodes.isEmpty(), "Unable to find schema node for supplied schema path: %s", path);
-        if (schemaNodes.size() > 1) {
-            LOG.warn("More possible schema nodes {} for supplied schema path {}", schemaNodes, path);
-        }
-        final Optional<DataNodeContainer> current = schemaNodes.stream()
-                .filter(node -> node instanceof DataNodeContainer).map(DataNodeContainer.class::cast)
-                .findFirst();
-        checkArgument(current.isPresent(),
-                "Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",
-                path, current);
-        return new SchemaTracker(current.get());
+    public static @NonNull SchemaTracker create(final EffectiveModelContext context, final Absolute path) {
+        return new SchemaTracker(SchemaInferenceStack.of(context, path));
     }
 
-    public Object getParent() {
-        if (schemaStack.isEmpty()) {
-            return root;
-        }
-        return schemaStack.peek();
+    /**
+     * Create a new writer with the specified context and rooted in the specified schema path.
+     *
+     * @param context Associated {@link EffectiveModelContext}
+     * @param path schema path
+     * @return A new {@link SchemaTracker}
+     * @throws NullPointerException if any argument is null
+     * @throws IllegalArgumentException if {@code path} does not point to a valid root
+     */
+    public static @NonNull SchemaTracker create(final EffectiveModelContext context, final SchemaPath path) {
+        return new SchemaTracker(SchemaInferenceStack.ofInstantiatedPath(context, path));
     }
 
-    private SchemaNode getSchema(final PathArgument name) {
-        final Object parent = getParent();
-        SchemaNode schema = null;
-        final QName qname = name.getNodeType();
-        if (parent instanceof DataNodeContainer) {
-            schema = ((DataNodeContainer)parent).getDataChildByName(qname);
-            if (schema == null) {
-                if (parent instanceof GroupingDefinition) {
-                    schema = (GroupingDefinition) parent;
-                } else if (parent instanceof NotificationDefinition) {
-                    schema = (NotificationDefinition) parent;
-                }
-            }
-        } else if (parent instanceof ChoiceSchemaNode) {
-            schema = findChildInCases((ChoiceSchemaNode) parent, qname);
-        } else {
-            throw new IllegalStateException("Unsupported schema type " + parent.getClass() + " on stack.");
-        }
+    /**
+     * Create a new writer with the specified context and rooted in the specified schema path.
+     *
+     * @param context Associated {@link EffectiveModelContext}
+     * @param operation Operation schema path
+     * @param qname Input/Output container QName
+     * @return A new {@link NormalizedNodeStreamWriter}
+     * @throws NullPointerException if any argument is null
+     * @throws IllegalArgumentException if {@code operation} does not point to an actual operation or if {@code qname}
+     *                                  does not identify a valid root underneath it.
+     */
+    public static @NonNull SchemaTracker forOperation(final EffectiveModelContext context, final Absolute operation,
+            final QName qname) {
+        final SchemaInferenceStack stack = SchemaInferenceStack.of(context, operation);
+        final EffectiveStatement<?, ?> current = stack.currentStatement();
+        checkArgument(current instanceof RpcEffectiveStatement || current instanceof ActionEffectiveStatement,
+            "Path %s resolved into non-operation %s", operation, current);
+        stack.enterSchemaTree(qname);
+        return new SchemaTracker(stack);
+    }
 
-        checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
-        return schema;
+    /**
+     * Return a copy of this tracker's state as an {@link SchemaInferenceStack}.
+     *
+     * @return A SchemaInferenceStack
+     */
+    public @NonNull SchemaInferenceStack toSchemaInferenceStack() {
+        return dataTree.copy();
     }
 
-    private static SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
-        for (final CaseSchemaNode caze : parent.getCases().values()) {
-            final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
-            if (potential.isPresent()) {
-                return potential.get();
-            }
-        }
-        return null;
+    public Object getParent() {
+        final WithStatus schema = schemaStack.peek();
+        return schema == null ? root : schema;
     }
 
-    private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
-        for (final CaseSchemaNode caze : parent.getCases().values()) {
-            final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
-            if (potential.isPresent()) {
-                return caze;
-            }
+    private SchemaNode enterDataTree(final PathArgument name) {
+        final QName qname = name.getNodeType();
+        final DataTreeEffectiveStatement<?> stmt = dataTree.enterDataTree(qname);
+        verify(stmt instanceof SchemaNode, "Unexpected result %s", stmt);
+        final SchemaNode ret = (SchemaNode) stmt;
+        final Object parent = getParent();
+        if (parent instanceof ChoiceSchemaNode) {
+            final DataSchemaNode check = ((ChoiceSchemaNode) parent).findDataSchemaChild(qname).orElse(null);
+            verify(check == ret, "Data tree result %s does not match choice result %s", ret, check);
         }
-        return null;
+        return ret;
     }
 
     public void startList(final PathArgument name) {
-        final SchemaNode schema = getSchema(name);
-        checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
+        final SchemaNode schema = enterDataTree(name);
+        checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema);
         schemaStack.push(schema);
     }
 
@@ -156,23 +202,17 @@ public final class SchemaTracker {
         schemaStack.push((ListSchemaNode) schema);
     }
 
-    public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
-        final SchemaNode schema = getSchema(name);
-
-        checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
-        return (LeafSchemaNode) schema;
-    }
-
     public void startLeafNode(final NodeIdentifier name) throws IOException {
-        schemaStack.push(leafNode(name));
+        final SchemaNode schema = enterDataTree(name);
+        checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema);
+        schemaStack.push(schema);
     }
 
     public LeafListSchemaNode startLeafSet(final NodeIdentifier name) {
-        final SchemaNode schema = getSchema(name);
-
-        checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
+        final SchemaNode schema = enterDataTree(name);
+        checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema);
         schemaStack.push(schema);
-        return (LeafListSchemaNode)schema;
+        return (LeafListSchemaNode) schema;
     }
 
     public LeafListSchemaNode leafSetEntryNode(final QName qname) {
@@ -181,9 +221,10 @@ public final class SchemaTracker {
             return (LeafListSchemaNode) parent;
         }
 
+        // FIXME: when would this trigger?
         final SchemaNode child = SchemaUtils.findDataChildSchemaByQName((SchemaNode) parent, qname);
         checkArgument(child instanceof LeafListSchemaNode,
-            "Node %s is neither a leaf-list nor currently in a leaf-list", child.getPath());
+            "Node %s is neither a leaf-list nor currently in a leaf-list", child);
         return (LeafListSchemaNode) child;
     }
 
@@ -193,35 +234,19 @@ public final class SchemaTracker {
 
     public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
         LOG.debug("Enter choice {}", name);
-        final SchemaNode schema = getSchema(name);
-
-        checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
-        schemaStack.push(schema);
-        return (ChoiceSchemaNode)schema;
+        final ChoiceEffectiveStatement stmt = dataTree.enterChoice(name.getNodeType());
+        verify(stmt instanceof ChoiceSchemaNode, "Node %s is not a choice", stmt);
+        final ChoiceSchemaNode ret = (ChoiceSchemaNode) stmt;
+        schemaStack.push(ret);
+        return ret;
     }
 
     public SchemaNode startContainerNode(final NodeIdentifier name) {
         LOG.debug("Enter container {}", name);
-        final SchemaNode schema = getSchema(name);
-
-        boolean isAllowed = schema instanceof ContainerSchemaNode;
-        isAllowed |= schema instanceof NotificationDefinition;
-
-        checkArgument(isAllowed, "Node %s is not a container nor a notification", schema.getPath());
+        final SchemaNode schema = enterDataTree(name);
+        checkArgument(schema instanceof ContainerLike || schema instanceof NotificationDefinition,
+            "Node %s is not a container nor a notification", schema);
         schemaStack.push(schema);
-
-        return schema;
-    }
-
-    public SchemaNode startYangModeledAnyXmlNode(final NodeIdentifier name) {
-        LOG.debug("Enter yang modeled anyXml {}", name);
-        final SchemaNode schema = getSchema(name);
-
-        checkArgument(schema instanceof YangModeledAnyxmlSchemaNode, "Node %s is not an yang modeled anyXml.",
-            schema.getPath());
-
-        schemaStack.push(((YangModeledAnyxmlSchemaNode) schema).getSchemaOfAnyXmlData());
-
         return schema;
     }
 
@@ -243,27 +268,35 @@ public final class SchemaTracker {
         return resolvedSchema;
     }
 
-    public AnyxmlSchemaNode anyxmlNode(final NodeIdentifier name) {
-        final SchemaNode schema = getSchema(name);
-        checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema.getPath());
-        return (AnyxmlSchemaNode)schema;
+    private static SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
+        for (final CaseSchemaNode caze : parent.getCases()) {
+            final Optional<DataSchemaNode> potential = caze.findDataChildByName(qname);
+            if (potential.isPresent()) {
+                return caze;
+            }
+        }
+        return null;
     }
 
     public void startAnyxmlNode(final NodeIdentifier name) {
-        schemaStack.push(anyxmlNode(name));
-    }
-
-    public AnydataSchemaNode anydataNode(final NodeIdentifier name) {
-        final SchemaNode schema = getSchema(name);
-        checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema.getPath());
-        return (AnydataSchemaNode)schema;
+        final SchemaNode schema = enterDataTree(name);
+        checkArgument(schema instanceof AnyxmlSchemaNode, "Node %s is not anyxml", schema);
+        schemaStack.push(schema);
     }
 
     public void startAnydataNode(final NodeIdentifier name) {
-        schemaStack.push(anydataNode(name));
+        final SchemaNode schema = enterDataTree(name);
+        checkArgument(schema instanceof AnydataSchemaNode, "Node %s is not anydata", schema);
+        schemaStack.push(schema);
     }
 
     public Object endNode() {
-        return schemaStack.pop();
+        final Object ret = schemaStack.pop();
+        // If this is a data tree node, make sure it is updated. Before that, though, we need to check if this is not
+        // actually listEntry -> list or leafListEntry -> leafList exit.
+        if (!(ret instanceof AugmentationSchemaNode) && getParent() != ret) {
+            dataTree.exit();
+        }
+        return ret;
     }
 }