src/HOL/Quickcheck_Narrowing.thy
author haftmann
Thu Sep 18 18:48:54 2014 +0200 (2014-09-18)
changeset 58400 d0d3c30806b4
parent 58350 919149921e46
child 58813 625d04d4fd2a
permissions -rw-r--r--
always annotate potentially polymorphic Haskell numerals
     1 (* Author: Lukas Bulwahn, TU Muenchen *)
     2 
     3 header {* Counterexample generator performing narrowing-based testing *}
     4 
     5 theory Quickcheck_Narrowing
     6 imports Quickcheck_Random
     7 keywords "find_unused_assms" :: diag
     8 begin
     9 
    10 subsection {* Counterexample generator *}
    11 
    12 subsubsection {* Code generation setup *}
    13 
    14 setup {* Code_Target.extend_target ("Haskell_Quickcheck", (Code_Haskell.target, I)) *}
    15 
    16 code_printing
    17   code_module Typerep \<rightharpoonup> (Haskell_Quickcheck) {*
    18 data Typerep = Typerep String [Typerep]
    19 *}
    20 | type_constructor typerep \<rightharpoonup> (Haskell_Quickcheck) "Typerep.Typerep"
    21 | constant Typerep.Typerep \<rightharpoonup> (Haskell_Quickcheck) "Typerep.Typerep"
    22 | type_constructor integer \<rightharpoonup> (Haskell_Quickcheck) "Prelude.Int"
    23 
    24 code_reserved Haskell_Quickcheck Typerep
    25 
    26 code_printing
    27   constant "0::integer" \<rightharpoonup>
    28     (Haskell_Quickcheck) "!(0/ ::/ Prelude.Int)"
    29 
    30 setup {*
    31   let
    32     val target = "Haskell_Quickcheck";
    33     fun print _ = Code_Haskell.print_numeral "Prelude.Int";
    34   in
    35     Numeral.add_code @{const_name Code_Numeral.Pos} I print target
    36     #> Numeral.add_code @{const_name Code_Numeral.Neg} (op ~) print target
    37   end
    38 *}
    39 
    40 
    41 subsubsection {* Narrowing's deep representation of types and terms *}
    42 
    43 datatype (plugins only: code extraction) narrowing_type =
    44   Narrowing_sum_of_products "narrowing_type list list"
    45 
    46 datatype (plugins only: code extraction) narrowing_term =
    47   Narrowing_variable "integer list" narrowing_type
    48 | Narrowing_constructor integer "narrowing_term list"
    49 
    50 datatype (plugins only: code extraction) (dead 'a) narrowing_cons =
    51   Narrowing_cons narrowing_type "(narrowing_term list \<Rightarrow> 'a) list"
    52 
    53 primrec map_cons :: "('a => 'b) => 'a narrowing_cons => 'b narrowing_cons"
    54 where
    55   "map_cons f (Narrowing_cons ty cs) = Narrowing_cons ty (map (\<lambda>c. f o c) cs)"
    56 
    57 subsubsection {* From narrowing's deep representation of terms to @{theory Code_Evaluation}'s terms *}
    58 
    59 class partial_term_of = typerep +
    60   fixes partial_term_of :: "'a itself => narrowing_term => Code_Evaluation.term"
    61 
    62 lemma partial_term_of_anything: "partial_term_of x nt \<equiv> t"
    63   by (rule eq_reflection) (cases "partial_term_of x nt", cases t, simp)
    64  
    65 subsubsection {* Auxilary functions for Narrowing *}
    66 
    67 consts nth :: "'a list => integer => 'a"
    68 
    69 code_printing constant nth \<rightharpoonup> (Haskell_Quickcheck) infixl 9 "!!"
    70 
    71 consts error :: "char list => 'a"
    72 
    73 code_printing constant error \<rightharpoonup> (Haskell_Quickcheck) "error"
    74 
    75 consts toEnum :: "integer => char"
    76 
    77 code_printing constant toEnum \<rightharpoonup> (Haskell_Quickcheck) "Prelude.toEnum"
    78 
    79 consts marker :: "char"
    80 
    81 code_printing constant marker \<rightharpoonup> (Haskell_Quickcheck) "''\\0'"
    82 
    83 subsubsection {* Narrowing's basic operations *}
    84 
    85 type_synonym 'a narrowing = "integer => 'a narrowing_cons"
    86 
    87 definition empty :: "'a narrowing"
    88 where
    89   "empty d = Narrowing_cons (Narrowing_sum_of_products []) []"
    90   
    91 definition cons :: "'a => 'a narrowing"
    92 where
    93   "cons a d = (Narrowing_cons (Narrowing_sum_of_products [[]]) [(\<lambda>_. a)])"
    94 
    95 fun conv :: "(narrowing_term list => 'a) list => narrowing_term => 'a"
    96 where
    97   "conv cs (Narrowing_variable p _) = error (marker # map toEnum p)"
    98 | "conv cs (Narrowing_constructor i xs) = (nth cs i) xs"
    99 
   100 fun non_empty :: "narrowing_type => bool"
   101 where
   102   "non_empty (Narrowing_sum_of_products ps) = (\<not> (List.null ps))"
   103 
   104 definition "apply" :: "('a => 'b) narrowing => 'a narrowing => 'b narrowing"
   105 where
   106   "apply f a d =
   107      (case f d of Narrowing_cons (Narrowing_sum_of_products ps) cfs =>
   108        case a (d - 1) of Narrowing_cons ta cas =>
   109        let
   110          shallow = (d > 0 \<and> non_empty ta);
   111          cs = [(\<lambda>xs'. (case xs' of [] => undefined | x # xs => cf xs (conv cas x))). shallow, cf <- cfs]
   112        in Narrowing_cons (Narrowing_sum_of_products [ta # p. shallow, p <- ps]) cs)"
   113 
   114 definition sum :: "'a narrowing => 'a narrowing => 'a narrowing"
   115 where
   116   "sum a b d =
   117     (case a d of Narrowing_cons (Narrowing_sum_of_products ssa) ca => 
   118       case b d of Narrowing_cons (Narrowing_sum_of_products ssb) cb =>
   119       Narrowing_cons (Narrowing_sum_of_products (ssa @ ssb)) (ca @ cb))"
   120 
   121 lemma [fundef_cong]:
   122   assumes "a d = a' d" "b d = b' d" "d = d'"
   123   shows "sum a b d = sum a' b' d'"
   124 using assms unfolding sum_def by (auto split: narrowing_cons.split narrowing_type.split)
   125 
   126 lemma [fundef_cong]:
   127   assumes "f d = f' d" "(\<And>d'. 0 \<le> d' \<and> d' < d \<Longrightarrow> a d' = a' d')"
   128   assumes "d = d'"
   129   shows "apply f a d = apply f' a' d'"
   130 proof -
   131   note assms
   132   moreover have "0 < d' \<Longrightarrow> 0 \<le> d' - 1"
   133     by (simp add: less_integer_def less_eq_integer_def)
   134   ultimately show ?thesis
   135     by (auto simp add: apply_def Let_def
   136       split: narrowing_cons.split narrowing_type.split)
   137 qed
   138 
   139 subsubsection {* Narrowing generator type class *}
   140 
   141 class narrowing =
   142   fixes narrowing :: "integer => 'a narrowing_cons"
   143 
   144 datatype (plugins only: code extraction) property =
   145   Universal narrowing_type "(narrowing_term => property)" "narrowing_term => Code_Evaluation.term"
   146 | Existential narrowing_type "(narrowing_term => property)" "narrowing_term => Code_Evaluation.term"
   147 | Property bool
   148 
   149 (* FIXME: hard-wired maximal depth of 100 here *)
   150 definition exists :: "('a :: {narrowing, partial_term_of} => property) => property"
   151 where
   152   "exists f = (case narrowing (100 :: integer) of Narrowing_cons ty cs => Existential ty (\<lambda> t. f (conv cs t)) (partial_term_of (TYPE('a))))"
   153 
   154 definition "all" :: "('a :: {narrowing, partial_term_of} => property) => property"
   155 where
   156   "all f = (case narrowing (100 :: integer) of Narrowing_cons ty cs => Universal ty (\<lambda>t. f (conv cs t)) (partial_term_of (TYPE('a))))"
   157 
   158 subsubsection {* class @{text is_testable} *}
   159 
   160 text {* The class @{text is_testable} ensures that all necessary type instances are generated. *}
   161 
   162 class is_testable
   163 
   164 instance bool :: is_testable ..
   165 
   166 instance "fun" :: ("{term_of, narrowing, partial_term_of}", is_testable) is_testable ..
   167 
   168 definition ensure_testable :: "'a :: is_testable => 'a :: is_testable"
   169 where
   170   "ensure_testable f = f"
   171 
   172 
   173 subsubsection {* Defining a simple datatype to represent functions in an incomplete and redundant way *}
   174 
   175 datatype (plugins only: code quickcheck_narrowing extraction) (dead 'a, dead 'b) ffun =
   176   Constant 'b
   177 | Update 'a 'b "('a, 'b) ffun"
   178 
   179 primrec eval_ffun :: "('a, 'b) ffun => 'a => 'b"
   180 where
   181   "eval_ffun (Constant c) x = c"
   182 | "eval_ffun (Update x' y f) x = (if x = x' then y else eval_ffun f x)"
   183 
   184 hide_type (open) ffun
   185 hide_const (open) Constant Update eval_ffun
   186 
   187 datatype (plugins only: code quickcheck_narrowing extraction) (dead 'b) cfun = Constant 'b
   188 
   189 primrec eval_cfun :: "'b cfun => 'a => 'b"
   190 where
   191   "eval_cfun (Constant c) y = c"
   192 
   193 hide_type (open) cfun
   194 hide_const (open) Constant eval_cfun Abs_cfun Rep_cfun
   195 
   196 subsubsection {* Setting up the counterexample generator *}
   197 
   198 ML_file "Tools/Quickcheck/narrowing_generators.ML"
   199 
   200 setup {* Narrowing_Generators.setup *}
   201 
   202 definition narrowing_dummy_partial_term_of :: "('a :: partial_term_of) itself => narrowing_term => term"
   203 where
   204   "narrowing_dummy_partial_term_of = partial_term_of"
   205 
   206 definition narrowing_dummy_narrowing :: "integer => ('a :: narrowing) narrowing_cons"
   207 where
   208   "narrowing_dummy_narrowing = narrowing"
   209 
   210 lemma [code]:
   211   "ensure_testable f =
   212     (let
   213       x = narrowing_dummy_narrowing :: integer => bool narrowing_cons;
   214       y = narrowing_dummy_partial_term_of :: bool itself => narrowing_term => term;
   215       z = (conv :: _ => _ => unit)  in f)"
   216 unfolding Let_def ensure_testable_def ..
   217 
   218 subsection {* Narrowing for sets *}
   219 
   220 instantiation set :: (narrowing) narrowing
   221 begin
   222 
   223 definition "narrowing_set = Quickcheck_Narrowing.apply (Quickcheck_Narrowing.cons set) narrowing"
   224 
   225 instance ..
   226 
   227 end
   228   
   229 subsection {* Narrowing for integers *}
   230 
   231 
   232 definition drawn_from :: "'a list \<Rightarrow> 'a narrowing_cons"
   233 where
   234   "drawn_from xs =
   235     Narrowing_cons (Narrowing_sum_of_products (map (\<lambda>_. []) xs)) (map (\<lambda>x _. x) xs)"
   236 
   237 function around_zero :: "int \<Rightarrow> int list"
   238 where
   239   "around_zero i = (if i < 0 then [] else (if i = 0 then [0] else around_zero (i - 1) @ [i, -i]))"
   240   by pat_completeness auto
   241 termination by (relation "measure nat") auto
   242 
   243 declare around_zero.simps [simp del]
   244 
   245 lemma length_around_zero:
   246   assumes "i >= 0" 
   247   shows "length (around_zero i) = 2 * nat i + 1"
   248 proof (induct rule: int_ge_induct [OF assms])
   249   case 1
   250   from 1 show ?case by (simp add: around_zero.simps)
   251 next
   252   case (2 i)
   253   from 2 show ?case
   254     by (simp add: around_zero.simps [of "i + 1"])
   255 qed
   256 
   257 instantiation int :: narrowing
   258 begin
   259 
   260 definition
   261   "narrowing_int d = (let (u :: _ \<Rightarrow> _ \<Rightarrow> unit) = conv; i = int_of_integer d
   262     in drawn_from (around_zero i))"
   263 
   264 instance ..
   265 
   266 end
   267 
   268 lemma [code, code del]: "partial_term_of (ty :: int itself) t \<equiv> undefined"
   269   by (rule partial_term_of_anything)+
   270 
   271 lemma [code]:
   272   "partial_term_of (ty :: int itself) (Narrowing_variable p t) \<equiv>
   273     Code_Evaluation.Free (STR ''_'') (Typerep.Typerep (STR ''Int.int'') [])"
   274   "partial_term_of (ty :: int itself) (Narrowing_constructor i []) \<equiv>
   275     (if i mod 2 = 0
   276      then Code_Evaluation.term_of (- (int_of_integer i) div 2)
   277      else Code_Evaluation.term_of ((int_of_integer i + 1) div 2))"
   278   by (rule partial_term_of_anything)+
   279 
   280 instantiation integer :: narrowing
   281 begin
   282 
   283 definition
   284   "narrowing_integer d = (let (u :: _ \<Rightarrow> _ \<Rightarrow> unit) = conv; i = int_of_integer d
   285     in drawn_from (map integer_of_int (around_zero i)))"
   286 
   287 instance ..
   288 
   289 end
   290 
   291 lemma [code, code del]: "partial_term_of (ty :: integer itself) t \<equiv> undefined"
   292   by (rule partial_term_of_anything)+
   293 
   294 lemma [code]:
   295   "partial_term_of (ty :: integer itself) (Narrowing_variable p t) \<equiv>
   296     Code_Evaluation.Free (STR ''_'') (Typerep.Typerep (STR ''Code_Numeral.integer'') [])"
   297   "partial_term_of (ty :: integer itself) (Narrowing_constructor i []) \<equiv>
   298     (if i mod 2 = 0
   299      then Code_Evaluation.term_of (- i div 2)
   300      else Code_Evaluation.term_of ((i + 1) div 2))"
   301   by (rule partial_term_of_anything)+
   302 
   303 code_printing constant "Code_Evaluation.term_of :: integer \<Rightarrow> term" \<rightharpoonup> (Haskell_Quickcheck) 
   304   "(let { t = Typerep.Typerep \"Code'_Numeral.integer\" [];
   305      mkFunT s t = Typerep.Typerep \"fun\" [s, t];
   306      numT = Typerep.Typerep \"Num.num\" [];
   307      mkBit 0 = Generated'_Code.Const \"Num.num.Bit0\" (mkFunT numT numT);
   308      mkBit 1 = Generated'_Code.Const \"Num.num.Bit1\" (mkFunT numT numT);
   309      mkNumeral 1 = Generated'_Code.Const \"Num.num.One\" numT;
   310      mkNumeral i = let { q = i `Prelude.div` 2; r = i `Prelude.mod` 2 }
   311        in Generated'_Code.App (mkBit r) (mkNumeral q);
   312      mkNumber 0 = Generated'_Code.Const \"Groups.zero'_class.zero\" t;
   313      mkNumber 1 = Generated'_Code.Const \"Groups.one'_class.one\" t;
   314      mkNumber i = if i > 0 then
   315          Generated'_Code.App
   316            (Generated'_Code.Const \"Num.numeral'_class.numeral\"
   317               (mkFunT numT t))
   318            (mkNumeral i)
   319        else
   320          Generated'_Code.App
   321            (Generated'_Code.Const \"Groups.uminus'_class.uminus\" (mkFunT t t))
   322            (mkNumber (- i)); } in mkNumber)"
   323 
   324 subsection {* The @{text find_unused_assms} command *}
   325 
   326 ML_file "Tools/Quickcheck/find_unused_assms.ML"
   327 
   328 subsection {* Closing up *}
   329 
   330 hide_type narrowing_type narrowing_term narrowing_cons property
   331 hide_const map_cons nth error toEnum marker empty Narrowing_cons conv non_empty ensure_testable all exists drawn_from around_zero
   332 hide_const (open) Narrowing_variable Narrowing_constructor "apply" sum cons
   333 hide_fact empty_def cons_def conv.simps non_empty.simps apply_def sum_def ensure_testable_def all_def exists_def
   334 
   335 end