Problem: bst_zig

Your task is to implement a Binary Search Tree and verify that it correctly implements a mathematical Set in Dafny. The tree must maintain the BST Invariant: for any node with value $v$, all values in the left subtree are less than $v$ and all values in the right subtree are greater than $v$. Here, you just need to focus on the Zig operation (a single right rotation) and verify that it correctly preserves the tree's logical state while modifying its physical structure. The Zig operation is a fundamental building block of self-balancing trees like Splay Trees. It involves rotating a node $P$ with its left child $L$ such that $L$ becomes the new root of the subtree. Specifically, you must prove the following: (1) Set Preservation: The mathematical set of values (the tree's "view") remains exactly the same before and after the rotation; no elements are lost or added during the structural modification. (2) BST Invariant Preservation: for any node with value $v$, all values in the left subtree are less than $v$ and all values in the right subtree are greater than $v$. (3) Structural Correctness: After the rotation, the original left child $L$ must now be the root of the returned tree, and the original parent $P$ must now be $L$'s right child.

// Following is the block for necessary definitions
// <preamble>
datatype Tree = Empty | Node(val: int, left: Tree, right: Tree)

function view(tree: Tree): set<int>
    decreases tree
{
    match tree
    case Empty => {}
    case Node(val, left, right) => view(left) + view(right) + {val}
}

predicate is_bst(tree: Tree)
    decreases tree
{
    match tree
    case Empty => true
    case Node(val, left, right) =>
        (forall x :: x in view(left) ==> x < val) &&
        is_bst(left) &&
        (forall x :: x in view(right) ==> x > val) &&
        is_bst(right)
}
// </preamble>

// Following is the block for potential helper specifications
// <helpers>

// </helpers>

// Following is the block for proofs of lemmas
// <proofs>

// </proofs>

// Following is the block for the main specification
// <spec>
method zig(tree: Tree) returns (res: Tree)
    // tree corresponds to Box<Node>, so it cannot be Empty
    requires tree.Node? 
    // tree.left corresponds to node.left.is_some()
    requires tree.left.Node? 
    requires is_bst(tree)
    ensures is_bst(res)
    ensures view(res) == view(tree)
    // The left child is now the root
    ensures res.val == tree.left.val 
    // Old root is now right child
    ensures res.right.Node? && res.right.val == tree.val 
// </spec>
// <code>
{
    // Implement and verify BST zig rotation algorithm here.
}
// </code>