--  Verada predefined library: a hash map from integers, a proof enclave. Its entries live in
--  place in one table, open addressing with linear probing, which doubles when it is half
--  full; the heap engine proves the operations against the map's model, its keys and their
--  elements in the order the keys were first added, so that clients treat a map as that
--  value. Only memory limits the size: Include raises Storage_Error when memory cannot hold
--  one more entry (Verada.Storage).
with Verada.Containers.Functional.Sequences;
with Verada.Footprints;
with Verada.Storage;
generic
   type Element_Type is private;
package Verada.Containers.Hash_Maps
  with Annotate => (Verada, Enclave)
is
   package Key_Sequences is new Verada.Containers.Functional.Sequences (Integer);
   package Element_Sequences is new Verada.Containers.Functional.Sequences (Element_Type);
   use type Key_Sequences.Sequence;
   use type Element_Sequences.Sequence;

   --  a map's value: its keys, each once, in the order they were first added, and each key's
   --  element at the key's position
   type Map_Model is record
      Keys : Key_Sequences.Sequence;
      Elements : Element_Sequences.Sequence;
   end record;

   --  whether a model has a key
   function Has_Key (M : Map_Model; K : Integer) return Boolean is
     (for some I in 1 .. Key_Sequences.Length (M.Keys) => Key_Sequences.Get (M.Keys, I) = K)
     with Ghost;

   --  the position of a key a model has
   function Position (M : Map_Model; K : Integer) return Positive
     with Ghost,
          Pre => Has_Key (M, K),
          Post => Position'Result <= Key_Sequences.Length (M.Keys) and then Key_Sequences.Get (M.Keys, Position'Result) = K;

   --  a model with K's element E: a new key last, or an existing key's element replaced in
   --  place
   function Included_Keys (M : Map_Model; K : Integer) return Key_Sequences.Sequence is
     (if Has_Key (M, K) then M.Keys else Key_Sequences.Add (M.Keys, K))
     with Ghost, Pre => Key_Sequences.Length (M.Keys) < Verada.Storage.Length_Bound;

   function Included_Elements (M : Map_Model; K : Integer; E : Element_Type) return Element_Sequences.Sequence is
     (if Has_Key (M, K) then Element_Sequences.Set (M.Elements, Position (M, K), E) else Element_Sequences.Add (M.Elements, E))
     with Ghost,
          Pre => Key_Sequences.Length (M.Keys) < Verada.Storage.Length_Bound
                 and then Key_Sequences.Length (M.Keys) = Element_Sequences.Length (M.Elements);

   type Map is limited private
     with Default_Initial_Condition => Key_Sequences.Length (Model (Map).Keys) = 0,
          Finalizable => (Finalize => Clear, Relaxed_Finalization => True);

   function Model (M : Map) return Map_Model
     with Ghost,
          Post => Key_Sequences.Length (Model'Result.Keys) = Element_Sequences.Length (Model'Result.Elements);

   function Length (M : Map) return Natural
     with Post => Length'Result = Key_Sequences.Length (Model (M).Keys);

   function Contains (M : Map; K : Integer) return Boolean
     with Post => Contains'Result = Has_Key (Model (M), K);

   --  K's element
   function Element (M : Map; K : Integer) return Element_Type
     with Pre => Has_Key (Model (M), K),
          Post => (for all I in 1 .. Length (M) =>
                     (if Key_Sequences.Get (Model (M).Keys, I) = K then Element_Sequences.Get (Model (M).Elements, I) = Element'Result));

   --  K's element E: a new key last, or an existing key's element replaced in place
   procedure Include (M : in out Map; K : Integer; E : Element_Type)
     with Post => Model (M).Keys = Included_Keys (Model (M)'Old, K)
                  and Model (M).Elements = Included_Elements (Model (M)'Old, K, E);

   --  every key removed (and the table freed: a map that ends is cleared)
   procedure Clear (M : in out Map)
     with Post => Length (M) = 0;
private
   Max_Length : constant := Verada.Storage.Length_Bound;
   Max_Capacity : constant := 4 * Max_Length;

   --  a slot of the table: whether it holds an entry, with its key and element; Index is the
   --  entry's position in the model (or, free, the slot's position in the free list); Nth and
   --  Free are the table's two lists held in its slots: the slot of the model's Nth + 1st key,
   --  and the Free + 1st free slot
   type Slot is record
      Used : Boolean := False;
      Key : Integer := 0;
      Value : Element_Type;
      Index : Natural := 0;
      Nth : Natural := 0;
      Free : Natural := 0;
   end record;

   type Slot_Array is array (Natural range <>) of Slot;
   type Table_Ptr is access Slot_Array;
   package Table_Cells is new Verada.Footprints (Table_Ptr);
   package Natural_Sequences is new Verada.Containers.Functional.Sequences (Natural);

   --  where a key's probes start in a table of Capacity slots (its remainder: a function with
   --  a body, so that proofs see only that it is a slot, not the nonlinear `mod`)
   function Home (K : Integer; Capacity : Positive) return Natural
     with Global => null, Post => Home'Result < Capacity;

   --  the slot Offset after Start, around the table
   function Around (Start, Offset : Natural; Capacity : Positive) return Natural is
     (if Start + Offset >= Capacity then Start + Offset - Capacity else Start + Offset)
     with Global => null,
          Pre => Start < Capacity and then Offset < Capacity and then Capacity <= Max_Capacity,
          Post => Around'Result < Capacity;

   --  how many slots after Start Finish is, around the table
   function Distance (Start, Finish : Natural; Capacity : Positive) return Natural is
     (if Finish >= Start then Finish - Start else Finish + Capacity - Start)
     with Global => null,
          Pre => Start < Capacity and then Finish < Capacity and then Capacity <= Max_Capacity,
          Post => Distance'Result < Capacity;

   type Map is limited record
      Table : Table_Ptr := null;
      Count : Natural := 0;
      Repr : Table_Cells.Cells := Table_Cells.Empty;
      Keys : Key_Sequences.Sequence := Key_Sequences.Empty_Sequence;
      Elements : Element_Sequences.Sequence := Element_Sequences.Empty_Sequence;
   end record
     with Type_Invariant => Well_Formed (Map);

   --  a table of its slots with its entries in the model's order: the I-th key's slot is the
   --  Nth of slot I - 1, holds the key and its element, and its Index is I; the free slots are
   --  the Free of slots 0 .. Capacity - Count - 1, each with its own position as Index; and
   --  every key's probes from its home to its slot pass only slots in use. In parts, each an
   --  expression function, so that an operation needs only those it uses.

   --  the table and its footprint, and the counts
   function Shaped (M : Map) return Boolean is
     (M.Table /= null
      and then Table_Cells.Contains (M.Repr, M.Table)
      and then (for all P of M.Repr => P = M.Table)
      and then M.Table'First = 0
      and then M.Table'Length in 2 .. Max_Capacity
      and then M.Count <= Max_Capacity / 2
      and then M.Count * 2 <= M.Table'Length
      and then Key_Sequences.Length (M.Keys) = M.Count
      and then Element_Sequences.Length (M.Elements) = M.Count);

   --  The parts of the invariant over a table's value (so that lemmas about a table before and
   --  after a change are about values), and over a map's table.

   --  a table's bounds, with room for the entries
   function Sized (T : Slot_Array; Count : Natural) return Boolean is
     (T'First = 0 and then T'Length in 2 .. Max_Capacity and then Count <= Max_Capacity / 2 and then Count * 2 <= T'Length);

   --  the first free slot (where every probe ends at the latest)
   function Has_Free_In (T : Slot_Array) return Boolean is
     (T (0).Free < T'Length and then not T (T (0).Free).Used)
     with Global => null,
          Pre => T'First = 0 and then T'Length in 2 .. Max_Capacity;

   function Entries_In (T : Slot_Array; Count : Natural; Keys : Key_Sequences.Sequence; Elements : Element_Sequences.Sequence) return Boolean is
     --  (over the slot X = I - 1 itself, so that a fact about a slot matches it: an index
     --  written `I - 1` under the quantifier keeps solvers from using it at a given slot)
     (for all X in 0 .. Count - 1 =>
        T (X).Nth < T'Length
        and then T (T (X).Nth).Used
        and then T (T (X).Nth).Key = Key_Sequences.Get (Keys, X + 1)
        and then T (T (X).Nth).Value = Element_Sequences.Get (Elements, X + 1)
        and then T (T (X).Nth).Index = X + 1)
     with Global => null,
          Pre => Sized (T, Count) and then Key_Sequences.Length (Keys) >= Count and then Element_Sequences.Length (Elements) >= Count;

   function Free_In (T : Slot_Array; Count : Natural) return Boolean is
     (for all X in 0 .. T'Length - Count - 1 =>
        T (X).Free < T'Length
        and then not T (T (X).Free).Used
        and then T (T (X).Free).Index = X + 1)
     with Global => null,
          Pre => Sized (T, Count);

   function Linked_In (T : Slot_Array; Count : Natural) return Boolean is
     (for all P in T'Range =>
        (if T (P).Used
         then T (P).Index in 1 .. Count and then T (T (P).Index - 1).Nth = P
         else T (P).Index in 1 .. T'Length - Count and then T (T (P).Index - 1).Free = P))
     with Global => null,
          Pre => Sized (T, Count);

   --  every key's probes from its home to its slot pass only slots in use
   function Clustered_In (T : Slot_Array) return Boolean is
     (for all P in T'Range =>
        (if T (P).Used
         then (for all D in 0 .. Distance (Home (T (P).Key, T'Length), P, T'Length) - 1 =>
                 T (Around (Home (T (P).Key, T'Length), D, T'Length)).Used)))
     with Global => null,
          Pre => T'First = 0 and then T'Length in 2 .. Max_Capacity;

   function Distinct_In (Count : Natural; Keys : Key_Sequences.Sequence) return Boolean is
     (for all I in 1 .. Count => (for all J in 1 .. I - 1 => Key_Sequences.Get (Keys, I) /= Key_Sequences.Get (Keys, J)))
     with Global => null,
          Pre => Key_Sequences.Length (Keys) >= Count;

   function Has_Free (M : Map) return Boolean is (Has_Free_In (M.Table.all)) with Pre => Shaped (M);
   function Entries (M : Map) return Boolean is (Entries_In (M.Table.all, M.Count, M.Keys, M.Elements)) with Pre => Shaped (M);
   function Free_Listed (M : Map) return Boolean is (Free_In (M.Table.all, M.Count)) with Pre => Shaped (M);
   function Slots_Linked (M : Map) return Boolean is (Linked_In (M.Table.all, M.Count)) with Pre => Shaped (M);
   function Clustered (M : Map) return Boolean is (Clustered_In (M.Table.all)) with Pre => Shaped (M);
   function Distinct (M : Map) return Boolean is (Distinct_In (M.Count, M.Keys)) with Pre => Shaped (M);

   function Well_Formed (M : Map) return Boolean is
     (if M.Table = null
      then M.Count = 0 and then Key_Sequences.Length (M.Keys) = 0 and then Element_Sequences.Length (M.Elements) = 0
           and then (for all P of M.Repr => False)
      else Shaped (M) and then Has_Free (M) and then Entries (M) and then Free_Listed (M)
           and then Slots_Linked (M) and then Clustered (M) and then Distinct (M));

   function Model (M : Map) return Map_Model is ((Keys => M.Keys, Elements => M.Elements));
   function Length (M : Map) return Natural is (M.Count);
end Verada.Containers.Hash_Maps;
