# A proof enclave written in Vibe, proved whole: a linked stack whose nodes a ghost sequence
# lists and whose footprint holds them (e4-user-enclaves.md)
from verada import *

enclave()


@dataclass
class _Node:
    value: int
    next: Ref[_Node] | None = None


@dataclass(limited=True)
class Stack:
    _top: Ref[_Node] | None = None
    _count: int = 0
    _repr: Ghost[Cells[Ref[_Node]]]
    _nodes: Seq[Ref[_Node]]

    # the nodes from the bottom (1) to the top, each in the footprint, each pointing at the
    # one below it, all distinct; the footprint holds exactly them
    def __invariant__(self) -> bool:
        return (
            0 <= self._count and self._count <= 1000
            and len(self._nodes) >= self._count
            and (self._top is None if self._count == 0 else self._top == self._nodes.get(self._count))
            and all(self._nodes.get(i) is not None and self._nodes.get(i) in self._repr for i in range(1, self._count + 1))
            and all(self._nodes.get(i).next == (None if i == 1 else self._nodes.get(i - 1)) for i in range(1, self._count + 1))
            and all(all(self._nodes.get(i) != self._nodes.get(j) for j in range(1, i)) for i in range(1, self._count + 1))
            and all(any(self._nodes.get(i) == p for i in range(1, self._count + 1)) for p in self._repr)
        )

    def __initial__(self) -> bool:
        return size(self) == 0

    @ghost
    def model(self) -> int:
        return self._count

    def size(self) -> int:
        ensures(result == self.model())
        return self._count

    def push(self, x: int) -> None:
        requires(self.size() < 1000)
        ensures(self.size() == old(self.size()) + 1)
        n = Ref(_Node(value=x, next=self._top))
        self._top = n
        self._count = self._count + 1
        self._repr = self._repr.add(n)
        if len(self._nodes) > self._count - 1:
            self._nodes = self._nodes.set(self._count, n)
        else:
            self._nodes = self._nodes.add(n)

    @terminates
    def pop(self) -> int:
        requires(self.size() > 0)
        ensures(self.size() == old(self.size()) - 1)
        top = self._top
        x = top.value
        self._top = top.next
        self._repr = self._repr.remove(top)
        self._count = self._count - 1
        del top
        return x

    def __del__(self) -> None:
        while self.size() > 0:
            decreases(self.size())
            gone: int = self.pop()
