Guest User

SPARK Example

a guest
Apr 25th, 2020
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ada 2.16 KB | None | 0 0
  1.  
  2. ```
  3. -------------------------------------------
  4. -- double.ads (specification)
  5. -------------------------------------------
  6. package double
  7.     with SPARK_Mode => On
  8. is
  9.     type SomeArrayType is array (Positive range <>) of Natural;
  10.  
  11.     function doubleArray(arr : in SomeArrayType) return SomeArrayType
  12.         with
  13.             Global => null,
  14.             Depends => (doubleArray'Result => arr),
  15.             -- set arbitrary range here in precondition to avoid overflow
  16.             Pre => (for all idx in arr'Range => arr(idx) in 0..20000),
  17.             -- prove that everything in the return array is even
  18.             Post => (for all idx in arr'Range =>
  19.                      isEven(doubleArray'Result(idx)));
  20.  
  21.     function isEven(num : in Natural) return Boolean with
  22.              Contract_Cases =>
  23.                  (num rem 2 = 0 => isEven'Result = True,
  24.                   num rem 2 /= 0 => isEven'Result = False);
  25.  
  26. end double;
  27.  
  28. -------------------------------------------
  29. -- double.adb (implementation)
  30. -------------------------------------------
  31. package body double is
  32.  
  33.     function doubleArray(arr : in SomeArrayType) return SomeArrayType with
  34.         SPARK_Mode => On
  35.     is
  36.         doubled : SomeArrayType(arr'Range) := (others => 0);
  37.     begin
  38.         for i in arr'Range loop
  39.             doubled(i) := 2 * arr(i);
  40.  
  41.             pragma Loop_Invariant(for all j in arr'First .. i =>
  42.                doubled(j) = 2 * arr(j));
  43.         end loop;
  44.  
  45.         return doubled;
  46.     end doubleArray;
  47.  
  48.  
  49.     function isEven(num : in Natural) return Boolean with
  50.         SPARK_Mode => On
  51.     is
  52.     begin
  53.         if num rem 2 = 0 then
  54.             return True;
  55.         else
  56.             return False;
  57.         end if;
  58.     end isEven;
  59. end double;
  60.  
  61. -------------------------------------------
  62. -- main.adb
  63. -------------------------------------------
  64.  
  65. with Ada.Text_IO;
  66. with double; use double;
  67.  
  68. procedure Main
  69.     with SPARK_Mode => On
  70. is
  71.     arr : SomeArrayType := (3, 7, 8, 0, 1);
  72.     result : SomeArrayType := doubleArray(arr);
  73. begin
  74.      for i in result'Range loop
  75.         Ada.Text_IO.Put(Integer'Image(result(i)) & ", ");
  76.     end loop;
  77. end Main;
  78. ```
Advertisement
Add Comment
Please, Sign In to add comment