--  A proof enclave proved whole (e2-heap-engine.md): a linked stack whose nodes a ghost sequence
--  lists and whose footprint holds them, so that its frames are proved too and no part of it
--  is trusted (no B8002)
with Verada.Footprints;
with Verada.Containers.Functional.Sequences;
package Stacks
  with Annotate => (Verada, Enclave)
is
   type Stack is limited private
     with Default_Initial_Condition => Size (Stack) = 0;
   function Model (S : Stack) return Natural with Ghost;
   function Size (S : Stack) return Natural
     with Post => Size'Result = Model (S);
   procedure Push (S : in out Stack; X : Integer)
     with Pre => Size (S) < 1000, Post => Size (S) = Size (S)'Old + 1;
   procedure Pop (S : in out Stack; X : out Integer)
     with Pre => Size (S) > 0, Post => Size (S) = Size (S)'Old - 1;
private
   type Node;
   type Node_Ptr is access Node;
   type Node is record
      Value : Integer;
      Next : Node_Ptr;
   end record;
   package Node_Cells is new Verada.Footprints (Node_Ptr);
   package Node_Seqs is new Verada.Containers.Functional.Sequences (Node_Ptr);
   use Node_Seqs;
   --  the nodes from the bottom (1) to the top (Count: the sequence may run on, with nodes
   --  popped and freed), each in the footprint, each pointing at the one below it, all
   --  distinct; the footprint holds exactly them
   type Stack is limited record
      Top : Node_Ptr;
      Count : Natural := 0;
      Repr : Node_Cells.Cells := Node_Cells.Empty;
      Nodes : Node_Seqs.Sequence;
   end record
     with Type_Invariant => Stack.Count <= 1000
       and then Length (Stack.Nodes) >= Stack.Count
       and then (if Stack.Count = 0 then Stack.Top = null else Stack.Top = Get (Stack.Nodes, Stack.Count))
       and then (for all I in 1 .. Stack.Count => Get (Stack.Nodes, I) /= null and then Node_Cells.Contains (Stack.Repr, Get (Stack.Nodes, I)))
       and then (for all I in 1 .. Stack.Count => Get (Stack.Nodes, I).Next = (if I = 1 then null else Get (Stack.Nodes, I - 1)))
       and then (for all I in 1 .. Stack.Count => (for all J in 1 .. I - 1 => Get (Stack.Nodes, I) /= Get (Stack.Nodes, J)))
       and then (for all P of Stack.Repr => (for some I in 1 .. Stack.Count => Get (Stack.Nodes, I) = P));
   function Model (S : Stack) return Natural is (S.Count);
   function Size (S : Stack) return Natural is (S.Count);
end Stacks;
