--  Ada.Environment_Variables (RM A.17): the process's environment variables, read and
--  changed by name. Where the RM raises Constraint_Error (the value of a variable that does
--  not exist, a name that is empty or holds `=`), a precondition requires what avoids it. A
--  name or value holds no NUL character, which the host's environment cannot hold either.
--  Only memory limits a value's length (Verada.Storage).
with Verada.Storage;

package Ada.Environment_Variables
  with Abstract_State => Environment, Initializes => Environment
is
   --  a name a variable may have: not empty, with no `=` and no NUL
   function Is_Name (Name : String) return Boolean is
     (Name'Length > 0 and then (for all I in Name'Range => Name (I) /= '=' and then Name (I) /= Character'Val (0)))
     with Global => null;

   --  a value a variable may hold: no NUL
   function Is_Value (Value : String) return Boolean is
     (for all I in Value'Range => Value (I) /= Character'Val (0))
     with Global => null;

   function Exists (Name : String) return Boolean
     with Global => Environment;

   --  the model: the value of the variable Name (empty when it does not exist), for
   --  contracts only
   function Model (Name : String) return String
     with Ghost, Import, Global => Environment,
          Post => Model'Result'Length < Verada.Storage.Length_Bound
                  and then (Model'Result'Length = 0 or else Model'Result'First = 1);

   function Value (Name : String) return String
     with Global => Environment,
          Pre => Exists (Name),
          Post => Value'Result = Model (Name)
                  and then (Value'Result'Length = 0 or else Value'Result'First = 1);

   --  the variable's value, or Default when it does not exist
   function Value (Name : String; Default : String) return String
     with Global => Environment,
          Post => (if Exists (Name) then Value'Result = Model (Name) else Value'Result = Default);

   procedure Set (Name : String; Value : String)
     with Global => (In_Out => Environment),
          Pre => Is_Name (Name) and then Is_Value (Value),
          Post => Exists (Name) and then Model (Name) = Value;

   procedure Clear (Name : String)
     with Global => (In_Out => Environment),
          Post => not Exists (Name) and then Model (Name)'Length = 0;

   --  every variable removed
   procedure Clear
     with Global => (In_Out => Environment);

   --  Process called with each variable's name and value, as they were when Iterate began
   procedure Iterate (Process : not null access procedure (Name, Value : String))
     with Global => (In_Out => Environment);
end Ada.Environment_Variables;
