--  Verada.Containers.Unbounded.Vectors: vectors of any length, on the
--  heap, freed where the vector dies (a reclaimed type). The vector is limited: copies are
--  made explicitly. Its model is the array of its elements, Model, indexed from 1. Appending
--  doubles the storage when it is full, so a run of appends takes amortised constant time.
--  Only memory limits the length: an operation that lengthens a vector raises Storage_Error
--  when memory cannot hold the result (Verada.Storage).
with Verada.Storage;

generic
   type Element_Type is private;
package Verada.Containers.Unbounded.Vectors is
   type Element_Array is array (Positive range <>) of Element_Type;

   --  the arrays have the same elements, except perhaps at Index
   function Same_Except (A, B : Element_Array; Index : Positive) return Boolean is
     (A'First = B'First and then A'Last = B'Last
      and then (for all I in A'Range => (if I /= Index then A (I) = B (I))))
     with Ghost;

   --  the array's last element
   function Last_Of (A : Element_Array) return Element_Type is
     (A (A'Last))
     with Ghost, Pre => A'Length > 0;

   --  A is B with one more element at its end, X (`B & X`, element by element)
   function Appended (A, B : Element_Array; X : Element_Type) return Boolean is
     (A'First = 1 and then B'First = 1 and then A'Length = B'Length + 1
      and then (for all J in B'Range => A (J) = B (J))
      and then A (A'Last) = X)
     with Ghost;

   --  A is B with X before B's element At (at the end when At is past it), element by element
   function Inserted (A, B : Element_Array; At_Index : Positive; X : Element_Type) return Boolean is
     (A'First = 1 and then B'First = 1 and then A'Length = B'Length + 1 and then At_Index <= A'Length
      and then (for all J in 1 .. At_Index - 1 => A (J) = B (J))
      and then A (At_Index) = X
      and then (for all J in At_Index .. B'Length => A (J + 1) = B (J)))
     with Ghost;

   --  A is B without its element At, element by element
   function Removed (A, B : Element_Array; At_Index : Positive) return Boolean is
     (A'First = 1 and then B'First = 1 and then B'Length = A'Length + 1 and then At_Index <= B'Length
      and then (for all J in 1 .. At_Index - 1 => A (J) = B (J))
      and then (for all J in At_Index .. A'Length => A (J) = B (J + 1)))
     with Ghost;

   --  A is B followed by C (`B & C`, element by element)
   function Concatenated (A, B, C : Element_Array) return Boolean is
     (A'First = 1 and then B'First = 1 and then C'First = 1
      and then A'Length = B'Length + C'Length
      and then (for all J in B'Range => A (J) = B (J))
      and then (for all J in C'Range => A (B'Length + J) = C (J)))
     with Ghost;

   --  an element of an array (for a postcondition, where a component of a value's `'Old` is
   --  written through it)
   function Element_At (A : Element_Array; Index : Positive) return Element_Type is
     (A (Index))
     with Ghost, Pre => Index in A'Range;

   --  the array without its last element
   function Without_Last (A : Element_Array) return Element_Array is
     (A (A'First .. A'Last - 1))
     with Ghost, Pre => A'Length > 0;

   --  A is B backwards, element by element
   function Reversal (A, B : Element_Array) return Boolean is
     (A'First = 1 and then B'First = 1 and then A'Length = B'Length
      and then (for all J in A'Range => A (J) = B (B'Length - J + 1)))
     with Ghost;

   --  how many of A's first Last elements are Item
   function Count_Of (A : Element_Array; Item : Element_Type; Last : Natural) return Natural is
     (if Last = 0 then 0 else Count_Of (A, Item, Last - 1) + (if A (Last) = Item then 1 else 0))
     with Ghost, Global => null,
          Pre => Last <= A'Length and then (Last = 0 or else A'First = 1),
          Post => Count_Of'Result <= Last,
          Subprogram_Variant => (Decreases => Last);

   --  A and B hold the same elements, each as many times (a permutation of each other)
   function Is_Permutation (A, B : Element_Array) return Boolean is
     (A'Length = B'Length and then (A'Length = 0 or else (A'First = 1 and then B'First = 1))
      and then (for all J in A'Range => Count_Of (A, A (J), A'Length) = Count_Of (B, A (J), B'Length))
      and then (for all J in B'Range => Count_Of (A, B (J), A'Length) = Count_Of (B, B (J), B'Length)))
     with Ghost;

   type Vector is limited private
     with Default_Initial_Condition => Length (Vector) = 0,
          Finalizable => (Finalize => Clear, Relaxed_Finalization => True),
          Iterable => (First => Iter_First, Next => Iter_Next, Has_Element => Iter_Has_Element, Element => Iter_Element),
          Aggregate => (Empty => Empty, Add_Unnamed => Append);

   --  (below Length_Bound, as memory holds no more (Verada.Storage): a position after the
   --  last is still a Natural, so a `for E of V` loop's cursor always moves on and the loop
   --  ends, and two lengths' sum is a Natural)
   function Length (Container : Vector) return Natural
     with Global => null,
          Post => Length'Result < Verada.Storage.Length_Bound;

   --  an empty vector (for container aggregates, `[A, B]`)
   function Empty return Vector
     with Global => null,
          Post => Length (Empty'Result) = 0;

   function Model (Container : Vector) return Element_Array
     with Global => null,
          Post => Model'Result'Length = Length (Container)
                  and then (Model'Result'Length = 0 or else Model'Result'First = 1);

   function Element (Container : Vector; Index : Positive) return Element_Type
     with Global => null,
          Pre => Index <= Length (Container),
          Post => Element'Result = Model (Container) (Index);

   procedure Append (Container : in out Vector; New_Item : Element_Type)
     with Global => null, Always_Terminates,
          Post => Model (Container) = Model (Container)'Old & New_Item
            --  (the same, element by element, which callers' loops use)
            and Appended (Model (Container), Model (Container)'Old, New_Item);

   --  New_Item before the element at Before, the rest one place on (Python's `xs.insert(i, x)`,
   --  from 0 there)
   procedure Insert (Container : in out Vector; Before : Positive; New_Item : Element_Type)
     with Global => null, Always_Terminates,
          Pre => Before <= Length (Container) + 1,
          Post => Inserted (Model (Container), Model (Container)'Old, Before, New_Item);

   --  the element at Index taken out, the rest one place back (Python's `xs.pop(i)`)
   procedure Pop (Container : in out Vector; Index : Positive; Item : out Element_Type)
     with Global => null, Always_Terminates,
          Pre => Index <= Length (Container),
          Post => Removed (Model (Container), Model (Container)'Old, Index)
                  and Item = Element_At (Model (Container)'Old, Index);

   --  Items' elements after the vector's own (Python's `xs.extend(ys)`)
   procedure Extend (Container : in out Vector; Items : Vector)
     with Global => null, Always_Terminates,
          --  (`Model (Container)'Old & Model (Items)`, element by element: the solver does not
          --  take that equality of arrays from the elements, ledger 2026-10-30)
          Post => Concatenated (Model (Container), Model (Container)'Old, Model (Items));

   procedure Replace_Element (Container : in out Vector; Index : Positive; New_Item : Element_Type)
     with Global => null, Always_Terminates,
          Pre => Index <= Length (Container),
          Post => Same_Except (Model (Container), Model (Container)'Old, Index)
                  and Element (Container, Index) = New_Item;

   procedure Delete_Last (Container : in out Vector)
     with Global => null, Always_Terminates,
          Pre => Length (Container) > 0,
          Post => Model (Container) = Without_Last (Model (Container)'Old);

   --  the last element, which leaves the vector (Python's `x = xs.pop()`)
   procedure Pop (Container : in out Vector; Item : out Element_Type)
     with Global => null, Always_Terminates,
          Pre => Length (Container) > 0,
          Post => Item = Last_Of (Model (Container)'Old)
                  and Model (Container) = Without_Last (Model (Container)'Old);

   procedure Copy (Source : Vector; Target : in out Vector)
     with Global => null, Always_Terminates,
          Post => Model (Target) = Model (Source);

   procedure Move (From : in out Vector; To : in out Vector)
     with Global => null, Always_Terminates,
          Post => Model (To) = Model (From)'Old and then Length (From) = 0;

   procedure Clear (Container : in out Vector)
     with Global => null, Always_Terminates,
          Post => Length (Container) = 0;

   --  Item is an element (Python's `x in xs`)
   function Contains (Container : Vector; Item : Element_Type) return Boolean is
     (for some I in 1 .. Length (Container) => Element (Container, I) = Item);

   --  the position of the first element that is Item (Python's `xs.index(x)`, from 0 there)
   function Index (Container : Vector; Item : Element_Type) return Positive
     with Global => null,
          Pre => Contains (Container, Item),
          Post => Index'Result <= Length (Container)
                  and then Element (Container, Index'Result) = Item
                  and then (for all J in 1 .. Index'Result - 1 => Element (Container, J) /= Item);

   --  how many elements are Item (Python's `xs.count(x)`)
   function Count (Container : Vector; Item : Element_Type) return Natural
     with Global => null,
          Post => Count'Result = Count_Of (Model (Container), Item, Length (Container))
                  and then Count'Result <= Length (Container)
                  and then (Count'Result = 0) = not Contains (Container, Item);

   --  the first element that is Item taken out, the rest one place back (Python's
   --  `xs.remove(x)`)
   procedure Remove (Container : in out Vector; Item : Element_Type)
     with Global => null, Always_Terminates,
          Pre => Contains (Container, Item),
          Post => Removed (Model (Container), Model (Container)'Old, Index (Container, Item)'Old);

   --  the element at Index taken out, the rest one place back (Python's statement
   --  `xs.pop(i)` and `del xs[i]`)
   procedure Delete (Container : in out Vector; Index : Positive)
     with Global => null, Always_Terminates,
          Pre => Index <= Length (Container),
          Post => Removed (Model (Container), Model (Container)'Old, Index);

   --  the elements in the opposite order (Python's `xs.reverse()`)
   procedure Reverse_Elements (Container : in out Vector)
     with Global => null, Always_Terminates,
          Post => Length (Container) = Length (Container)'Old
                  and Reversal (Model (Container), Model (Container)'Old);

   --  a new vector of the elements in the opposite order (Python's `list(reversed(xs))`)
   function Reversed (Container : Vector) return Vector
     with Global => null,
          Post => Length (Reversed'Result) = Length (Container)
                  and then Reversal (Model (Reversed'Result), Model (Container));

   --  a new vector of Left's elements then Right's (Python's `xs + ys`)
   function "+" (Left, Right : Vector) return Vector
     with Global => null,
          Post => Length ("+"'Result) = Length (Left) + Length (Right)
                  and then Concatenated (Model ("+"'Result), Model (Left), Model (Right));

   --  a new vector of Left's elements Right times over, empty when Right is not positive
   --  (Python's `xs * n`)
   function "*" (Left : Vector; Right : Integer) return Vector
     with Global => null,
          Post => Length ("*"'Result) = (if Right > 0 then Length (Left) * Right else 0)
                  --  (each element is the one a whole copy of Left before it, and the first
                  --  copy is Left; Lemma_Repeat_Element gives an element by its place in its
                  --  copy)
                  and then (for all I in 1 .. Length ("*"'Result) =>
                              (if I <= Length (Left) then Element ("*"'Result, I) = Element (Left, I)
                               else Element ("*"'Result, I) = Element ("*"'Result, I - Length (Left))));

   --  The element at I of Left * N is the one at I's place in its copy of Left: what "*"'s
   --  postcondition says a copy at a time, by place (proved once, by induction on I, where a
   --  solver's search over `mod` with a divisor that is not a constant is not stable)
   procedure Lemma_Repeat_Element (Left : Vector; N : Integer; I : Positive)
     with Ghost, Global => null,
          Pre => Length (Left) > 0 and then N > 0 and then I <= Length (Left * N),
          Post => Element (Left * N, I) = Element (Left, (I - 1) mod Length (Left) + 1),
          Subprogram_Variant => (Decreases => I);

   --  Python's `n * xs`
   function "*" (Left : Integer; Right : Vector) return Vector
     with Global => null,
          Post => Length ("*"'Result) = (if Left > 0 then Length (Right) * Left else 0)
                  and then (for all I in 1 .. Length ("*"'Result) =>
                              (if I <= Length (Right) then Element ("*"'Result, I) = Element (Right, I)
                               else Element ("*"'Result, I) = Element ("*"'Result, I - Length (Right))));

   --  The operations that need an order of the elements, Python's `<` ("<" here), are
   --  generic in it. Their preconditions ask of "<" only what they need, and only of the
   --  vector's elements: never both X < Y and Y < X (and so never X < X), and, for the
   --  minimum and maximum, that X < Y means every Z is above X or below Y (a strict weak
   --  order, which Python's orders of numbers and strings are).

   --  the elements in increasing order, equal ones (neither below the other) in the order
   --  they had (Python's `xs.sort()`, which is stable)
   generic
      with function "<" (Left, Right : Element_Type) return Boolean is <>;
   procedure Generic_Sort (Container : in out Vector)
     with Global => null, Always_Terminates,
          Pre => (for all I in 1 .. Length (Container) =>
                    (for all J in 1 .. Length (Container) =>
                       (if Element (Container, I) < Element (Container, J)
                        then not (Element (Container, J) < Element (Container, I))))),
          Post => Length (Container) = Length (Container)'Old
                  and (for all I in 1 .. Length (Container) - 1 =>
                              not (Element (Container, I + 1) < Element (Container, I)))
                  and Is_Permutation (Model (Container), Model (Container)'Old);

   --  a new vector of the elements in increasing order, as Generic_Sort orders them
   --  (Python's `sorted(xs)`)
   generic
      with function "<" (Left, Right : Element_Type) return Boolean is <>;
   function Generic_Sorted (Container : Vector) return Vector
     with Global => null,
          Pre => (for all I in 1 .. Length (Container) =>
                    (for all J in 1 .. Length (Container) =>
                       (if Element (Container, I) < Element (Container, J)
                        then not (Element (Container, J) < Element (Container, I))))),
          Post => Length (Generic_Sorted'Result) = Length (Container)
                  and then (for all I in 1 .. Length (Generic_Sorted'Result) - 1 =>
                              not (Element (Generic_Sorted'Result, I + 1) < Element (Generic_Sorted'Result, I)))
                  and then Is_Permutation (Model (Generic_Sorted'Result), Model (Container));

   --  the first least element: no element is below it, and it is below every element
   --  before it (Python's `min(xs)`)
   generic
      with function "<" (Left, Right : Element_Type) return Boolean is <>;
   function Generic_Minimum (Container : Vector) return Element_Type
     with Global => null,
          Pre => Length (Container) > 0
                 and then (for all I in 1 .. Length (Container) =>
                             (for all J in 1 .. Length (Container) =>
                                (if Element (Container, I) < Element (Container, J)
                                 then not (Element (Container, J) < Element (Container, I)))))
                 and then (for all I in 1 .. Length (Container) =>
                             (for all J in 1 .. Length (Container) =>
                                (for all K in 1 .. Length (Container) =>
                                   (if Element (Container, I) < Element (Container, J)
                                    then Element (Container, I) < Element (Container, K)
                                         or else Element (Container, K) < Element (Container, J))))),
          Post => (for all J in 1 .. Length (Container) => not (Element (Container, J) < Generic_Minimum'Result))
                  and then (for some K in 1 .. Length (Container) =>
                              Element (Container, K) = Generic_Minimum'Result
                              and then (for all J in 1 .. K - 1 => Generic_Minimum'Result < Element (Container, J)));

   --  the first greatest element: no element is above it, and it is above every element
   --  before it (Python's `max(xs)`)
   generic
      with function "<" (Left, Right : Element_Type) return Boolean is <>;
   function Generic_Maximum (Container : Vector) return Element_Type
     with Global => null,
          Pre => Length (Container) > 0
                 and then (for all I in 1 .. Length (Container) =>
                             (for all J in 1 .. Length (Container) =>
                                (if Element (Container, I) < Element (Container, J)
                                 then not (Element (Container, J) < Element (Container, I)))))
                 and then (for all I in 1 .. Length (Container) =>
                             (for all J in 1 .. Length (Container) =>
                                (for all K in 1 .. Length (Container) =>
                                   (if Element (Container, I) < Element (Container, J)
                                    then Element (Container, I) < Element (Container, K)
                                         or else Element (Container, K) < Element (Container, J))))),
          Post => (for all J in 1 .. Length (Container) => not (Generic_Maximum'Result < Element (Container, J)))
                  and then (for some K in 1 .. Length (Container) =>
                              Element (Container, K) = Generic_Maximum'Result
                              and then (for all J in 1 .. K - 1 => Element (Container, J) < Generic_Maximum'Result));

   --  `for E of V` and `for all E of V => ...`: positions 1 .. Length (V)
   function Iter_First (Container : Vector) return Natural is (1);

   function Iter_Next (Container : Vector; Position : Natural) return Natural is
     (if Position < Natural'Last then Position + 1 else Position);

   function Iter_Has_Element (Container : Vector; Position : Natural) return Boolean is
     (Position in 1 .. Length (Container));

   function Iter_Element (Container : Vector; Position : Natural) return Element_Type is
     (Element (Container, Position))
     with Pre => Iter_Has_Element (Container, Position);

   --  a new vector of the elements after From up to To (Python's `xs[From:To]`, its bounds
   --  positions from 0 within the vector)
   function Slice (Container : Vector; From, To : Natural) return Vector
     with Global => null,
          Pre => From <= Length (Container) and then To <= Length (Container),
          Post => Length (Slice'Result) = (if From < To then To - From else 0)
                  and then (for all J in 1 .. Length (Slice'Result) => Element (Slice'Result, J) = Element (Container, From + J));

   --  whether it has no elements (Varc's `xs.is_empty()`)
   function Is_Empty (Container : Vector) return Boolean is (Length (Container) = 0)
     with Global => null;

private
   type Element_Array_Access is access Element_Array;

   --  Data is null for the empty vector that has no storage; otherwise it is the storage, from
   --  1, and the elements are Data (1 .. Last). The invariant is on the full view, where Verada
   --  takes a private type's invariant (contracts), and reads the representation directly (it may not call
   --  the type's visible operations).
   type Vector is limited record
      Data : Element_Array_Access;
      Last : Natural range 0 .. Verada.Storage.Length_Bound - 1 := 0;
   end record
     with Type_Invariant =>
       (if Vector.Data = null then Vector.Last = 0
        else Vector.Data'First = 1 and then Vector.Last <= Vector.Data'Last);

   function Length (Container : Vector) return Natural is (Container.Last);

   function Model (Container : Vector) return Element_Array is
     (if Container.Data = null then [] else Container.Data (1 .. Container.Last));

   function Element (Container : Vector; Index : Positive) return Element_Type is
     (Container.Data (Index));
end Verada.Containers.Unbounded.Vectors;
