src/HOL/Tools/Predicate_Compile/code_prolog.ML
author wenzelm
Fri Aug 27 12:57:55 2010 +0200 (2010-08-27)
changeset 38797 abe92b33ac9f
parent 38793 eba0175d4cd1
parent 38755 a37d39fe32f8
child 38864 4abe644fcea5
permissions -rw-r--r--
merged, resolving some minor conflicts in src/HOL/Tools/Predicate_Compile/code_prolog.ML;
bulwahn@38073
     1
(*  Title:      HOL/Tools/Predicate_Compile/code_prolog.ML
bulwahn@38073
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@38073
     3
bulwahn@38073
     4
Prototype of an code generator for logic programming languages (a.k.a. Prolog)
bulwahn@38073
     5
*)
bulwahn@38073
     6
bulwahn@38073
     7
signature CODE_PROLOG =
bulwahn@38073
     8
sig
bulwahn@38792
     9
  datatype prolog_system = SWI_PROLOG | YAP
bulwahn@38792
    10
  type code_options =
bulwahn@38792
    11
    {ensure_groundness : bool, limited_types : (typ * int) list, prolog_system : prolog_system}
bulwahn@38727
    12
  val options : code_options ref
bulwahn@38727
    13
bulwahn@38113
    14
  datatype arith_op = Plus | Minus
bulwahn@38112
    15
  datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    16
    | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    17
  datatype prem = Conj of prem list
bulwahn@38113
    18
    | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    19
    | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    20
    | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    21
    | Ground of string * typ;
bulwahn@38727
    22
bulwahn@38079
    23
  type clause = ((string * prol_term list) * prem);
bulwahn@38073
    24
  type logic_program = clause list;
bulwahn@38079
    25
  type constant_table = (string * string) list
bulwahn@38792
    26
bulwahn@38792
    27
  val generate : bool -> Proof.context -> string -> (logic_program * constant_table)
bulwahn@38079
    28
  val write_program : logic_program -> string
bulwahn@38792
    29
  val run : prolog_system -> logic_program -> string -> string list -> int option -> prol_term list list
bulwahn@38073
    30
bulwahn@38733
    31
  val quickcheck : Proof.context -> bool -> term -> int -> term list option * (bool list * bool)
bulwahn@38733
    32
bulwahn@38079
    33
  val trace : bool Unsynchronized.ref
bulwahn@38073
    34
end;
bulwahn@38073
    35
bulwahn@38073
    36
structure Code_Prolog : CODE_PROLOG =
bulwahn@38073
    37
struct
bulwahn@38073
    38
bulwahn@38079
    39
(* diagnostic tracing *)
bulwahn@38079
    40
bulwahn@38079
    41
val trace = Unsynchronized.ref false
bulwahn@38079
    42
bulwahn@38079
    43
fun tracing s = if !trace then Output.tracing s else () 
bulwahn@38727
    44
bulwahn@38727
    45
(* code generation options *)
bulwahn@38727
    46
bulwahn@38792
    47
datatype prolog_system = SWI_PROLOG | YAP
bulwahn@38727
    48
bulwahn@38792
    49
type code_options =
bulwahn@38792
    50
  {ensure_groundness : bool, limited_types : (typ * int) list, prolog_system : prolog_system}
bulwahn@38792
    51
bulwahn@38792
    52
val options = Unsynchronized.ref {ensure_groundness = false, limited_types = [],
bulwahn@38792
    53
  prolog_system = SWI_PROLOG};
bulwahn@38727
    54
bulwahn@38073
    55
(* general string functions *)
bulwahn@38073
    56
bulwahn@38073
    57
val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
bulwahn@38073
    58
val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
bulwahn@38073
    59
bulwahn@38073
    60
(* internal program representation *)
bulwahn@38073
    61
bulwahn@38113
    62
datatype arith_op = Plus | Minus
bulwahn@38113
    63
bulwahn@38112
    64
datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    65
  | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    66
bulwahn@38735
    67
fun dest_Var (Var v) = v
bulwahn@38735
    68
bulwahn@38735
    69
fun add_vars (Var v) = insert (op =) v
bulwahn@38735
    70
  | add_vars (ArithOp (_, ts)) = fold add_vars ts
bulwahn@38735
    71
  | add_vars (AppF (_, ts)) = fold add_vars ts
bulwahn@38735
    72
  | add_vars _ = I
bulwahn@38735
    73
bulwahn@38735
    74
fun map_vars f (Var v) = Var (f v)
bulwahn@38735
    75
  | map_vars f (ArithOp (opr, ts)) = ArithOp (opr, map (map_vars f) ts)
bulwahn@38735
    76
  | map_vars f (AppF (fs, ts)) = AppF (fs, map (map_vars f) ts)
bulwahn@38735
    77
  | map_vars f t = t
bulwahn@38735
    78
  
bulwahn@38728
    79
fun maybe_AppF (c, []) = Cons c
bulwahn@38728
    80
  | maybe_AppF (c, xs) = AppF (c, xs)
bulwahn@38728
    81
bulwahn@38113
    82
fun is_Var (Var _) = true
bulwahn@38113
    83
  | is_Var _ = false
bulwahn@38113
    84
bulwahn@38113
    85
fun is_arith_term (Var _) = true
bulwahn@38113
    86
  | is_arith_term (Number _) = true
bulwahn@38113
    87
  | is_arith_term (ArithOp (_, operands)) = forall is_arith_term operands
bulwahn@38113
    88
  | is_arith_term _ = false
bulwahn@38073
    89
bulwahn@38081
    90
fun string_of_prol_term (Var s) = "Var " ^ s
bulwahn@38075
    91
  | string_of_prol_term (Cons s) = "Cons " ^ s
bulwahn@38075
    92
  | string_of_prol_term (AppF (f, args)) = f ^ "(" ^ commas (map string_of_prol_term args) ^ ")" 
bulwahn@38112
    93
  | string_of_prol_term (Number n) = "Number " ^ string_of_int n
bulwahn@38075
    94
bulwahn@38113
    95
datatype prem = Conj of prem list
bulwahn@38113
    96
  | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    97
  | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    98
  | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    99
  | Ground of string * typ;
bulwahn@38735
   100
bulwahn@38073
   101
fun dest_Rel (Rel (c, ts)) = (c, ts)
bulwahn@38735
   102
bulwahn@38735
   103
fun map_term_prem f (Conj prems) = Conj (map (map_term_prem f) prems)
bulwahn@38735
   104
  | map_term_prem f (Rel (r, ts)) = Rel (r, map f ts)
bulwahn@38735
   105
  | map_term_prem f (NotRel (r, ts)) = NotRel (r, map f ts)
bulwahn@38735
   106
  | map_term_prem f (Eq (l, r)) = Eq (f l, f r)
bulwahn@38735
   107
  | map_term_prem f (NotEq (l, r)) = NotEq (f l, f r)
bulwahn@38735
   108
  | map_term_prem f (ArithEq (l, r)) = ArithEq (f l, f r)
bulwahn@38735
   109
  | map_term_prem f (NotArithEq (l, r)) = NotArithEq (f l, f r)
bulwahn@38735
   110
  | map_term_prem f (Ground (v, T)) = Ground (dest_Var (f (Var v)), T)
bulwahn@38735
   111
bulwahn@38735
   112
fun fold_prem_terms f (Conj prems) = fold (fold_prem_terms f) prems
bulwahn@38735
   113
  | fold_prem_terms f (Rel (_, ts)) = fold f ts
bulwahn@38735
   114
  | fold_prem_terms f (NotRel (_, ts)) = fold f ts
bulwahn@38735
   115
  | fold_prem_terms f (Eq (l, r)) = f l #> f r
bulwahn@38735
   116
  | fold_prem_terms f (NotEq (l, r)) = f l #> f r
bulwahn@38735
   117
  | fold_prem_terms f (ArithEq (l, r)) = f l #> f r
bulwahn@38735
   118
  | fold_prem_terms f (NotArithEq (l, r)) = f l #> f r
bulwahn@38735
   119
  | fold_prem_terms f (Ground (v, T)) = f (Var v)
bulwahn@38735
   120
  
bulwahn@38079
   121
type clause = ((string * prol_term list) * prem);
bulwahn@38073
   122
bulwahn@38073
   123
type logic_program = clause list;
bulwahn@38073
   124
bulwahn@38073
   125
(* translation from introduction rules to internal representation *)
bulwahn@38073
   126
bulwahn@38079
   127
(** constant table **)
bulwahn@38079
   128
bulwahn@38079
   129
type constant_table = (string * string) list
bulwahn@38079
   130
bulwahn@38073
   131
(* assuming no clashing *)
bulwahn@38079
   132
fun mk_constant_table consts =
bulwahn@38079
   133
  AList.make (first_lower o Long_Name.base_name) consts
bulwahn@38079
   134
bulwahn@38079
   135
fun declare_consts consts constant_table =
bulwahn@38079
   136
  fold (fn c => AList.update (op =) (c, first_lower (Long_Name.base_name c))) consts constant_table
bulwahn@38079
   137
  
bulwahn@38079
   138
fun translate_const constant_table c =
bulwahn@38079
   139
  case AList.lookup (op =) constant_table c of
bulwahn@38079
   140
    SOME c' => c'
bulwahn@38079
   141
  | NONE => error ("No such constant: " ^ c)
bulwahn@38073
   142
bulwahn@38079
   143
fun inv_lookup _ [] _ = NONE
bulwahn@38079
   144
  | inv_lookup eq ((key, value)::xs) value' =
bulwahn@38079
   145
      if eq (value', value) then SOME key
bulwahn@38079
   146
      else inv_lookup eq xs value';
bulwahn@38079
   147
bulwahn@38079
   148
fun restore_const constant_table c =
bulwahn@38079
   149
  case inv_lookup (op =) constant_table c of
bulwahn@38079
   150
    SOME c' => c'
bulwahn@38079
   151
  | NONE => error ("No constant corresponding to "  ^ c)
bulwahn@38727
   152
bulwahn@38079
   153
(** translation of terms, literals, premises, and clauses **)
bulwahn@38079
   154
bulwahn@38113
   155
fun translate_arith_const @{const_name "Groups.plus_class.plus"} = SOME Plus
bulwahn@38113
   156
  | translate_arith_const @{const_name "Groups.minus_class.minus"} = SOME Minus
bulwahn@38113
   157
  | translate_arith_const _ = NONE
bulwahn@38113
   158
bulwahn@38734
   159
fun mk_nat_term constant_table n =
bulwahn@38734
   160
  let
bulwahn@38734
   161
    val zero = translate_const constant_table @{const_name "Groups.zero_class.zero"}
bulwahn@38734
   162
    val Suc = translate_const constant_table @{const_name "Suc"}
bulwahn@38734
   163
  in funpow n (fn t => AppF (Suc, [t])) (Cons zero) end
bulwahn@38734
   164
bulwahn@38079
   165
fun translate_term ctxt constant_table t =
bulwahn@38112
   166
  case try HOLogic.dest_number t of
bulwahn@38112
   167
    SOME (@{typ "int"}, n) => Number n
bulwahn@38734
   168
  | SOME (@{typ "nat"}, n) => mk_nat_term constant_table n
bulwahn@38112
   169
  | NONE =>
bulwahn@38112
   170
      (case strip_comb t of
bulwahn@38112
   171
        (Free (v, T), []) => Var v 
bulwahn@38112
   172
      | (Const (c, _), []) => Cons (translate_const constant_table c)
bulwahn@38112
   173
      | (Const (c, _), args) =>
bulwahn@38113
   174
        (case translate_arith_const c of
bulwahn@38113
   175
          SOME aop => ArithOp (aop, map (translate_term ctxt constant_table) args)
bulwahn@38113
   176
        | NONE =>                                                             
bulwahn@38113
   177
            AppF (translate_const constant_table c, map (translate_term ctxt constant_table) args))
bulwahn@38112
   178
      | _ => error ("illegal term for translation: " ^ Syntax.string_of_term ctxt t))
bulwahn@38073
   179
bulwahn@38079
   180
fun translate_literal ctxt constant_table t =
bulwahn@38073
   181
  case strip_comb t of
bulwahn@38079
   182
    (Const (@{const_name "op ="}, _), [l, r]) =>
bulwahn@38113
   183
      let
bulwahn@38113
   184
        val l' = translate_term ctxt constant_table l
bulwahn@38113
   185
        val r' = translate_term ctxt constant_table r
bulwahn@38113
   186
      in
bulwahn@38728
   187
        (if is_Var l' andalso is_arith_term r' andalso not (is_Var r') then ArithEq else Eq) (l', r')
bulwahn@38113
   188
      end
bulwahn@38079
   189
  | (Const (c, _), args) =>
bulwahn@38079
   190
      Rel (translate_const constant_table c, map (translate_term ctxt constant_table) args)
bulwahn@38073
   191
  | _ => error ("illegal literal for translation: " ^ Syntax.string_of_term ctxt t)
bulwahn@38073
   192
bulwahn@38073
   193
fun NegRel_of (Rel lit) = NotRel lit
bulwahn@38073
   194
  | NegRel_of (Eq eq) = NotEq eq
bulwahn@38113
   195
  | NegRel_of (ArithEq eq) = NotArithEq eq
bulwahn@38113
   196
bulwahn@38727
   197
fun mk_groundness_prems t = map Ground (Term.add_frees t [])
bulwahn@38727
   198
  
bulwahn@38792
   199
fun translate_prem ensure_groundness ctxt constant_table t =  
bulwahn@38073
   200
    case try HOLogic.dest_not t of
bulwahn@38727
   201
      SOME t =>
bulwahn@38792
   202
        if ensure_groundness then
bulwahn@38727
   203
          Conj (mk_groundness_prems t @ [NegRel_of (translate_literal ctxt constant_table t)])
bulwahn@38727
   204
        else
bulwahn@38727
   205
          NegRel_of (translate_literal ctxt constant_table t)
bulwahn@38079
   206
    | NONE => translate_literal ctxt constant_table t
bulwahn@38114
   207
    
bulwahn@38114
   208
fun imp_prems_conv cv ct =
bulwahn@38114
   209
  case Thm.term_of ct of
bulwahn@38114
   210
    Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
bulwahn@38114
   211
  | _ => Conv.all_conv ct
bulwahn@38114
   212
bulwahn@38114
   213
fun Trueprop_conv cv ct =
bulwahn@38114
   214
  case Thm.term_of ct of
haftmann@38558
   215
    Const (@{const_name Trueprop}, _) $ _ => Conv.arg_conv cv ct  
bulwahn@38114
   216
  | _ => raise Fail "Trueprop_conv"
bulwahn@38114
   217
bulwahn@38114
   218
fun preprocess_intro thy rule =
bulwahn@38114
   219
  Conv.fconv_rule
bulwahn@38114
   220
    (imp_prems_conv
bulwahn@38114
   221
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv @{thm Predicate.eq_is_eq}))))
bulwahn@38114
   222
    (Thm.transfer thy rule)
bulwahn@38114
   223
bulwahn@38792
   224
fun translate_intros ensure_groundness ctxt gr const constant_table =
bulwahn@38073
   225
  let
bulwahn@38114
   226
    val intros = map (preprocess_intro (ProofContext.theory_of ctxt)) (Graph.get_node gr const)
bulwahn@38073
   227
    val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
bulwahn@38079
   228
    val constant_table' = declare_consts (fold Term.add_const_names intros' []) constant_table
bulwahn@38734
   229
      |> declare_consts [@{const_name "Groups.zero_class.zero"}, @{const_name "Suc"}]
bulwahn@38073
   230
    fun translate_intro intro =
bulwahn@38073
   231
      let
bulwahn@38073
   232
        val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
bulwahn@38727
   233
        val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro)
bulwahn@38792
   234
        val prems' = Conj (map (translate_prem ensure_groundness ctxt' constant_table') prems)
bulwahn@38079
   235
        val clause = (dest_Rel (translate_literal ctxt' constant_table' head), prems')
bulwahn@38073
   236
      in clause end
bulwahn@38079
   237
  in (map translate_intro intros', constant_table') end
bulwahn@38073
   238
bulwahn@38731
   239
fun depending_preds_of (key, intros) =
bulwahn@38731
   240
  fold Term.add_const_names (map Thm.prop_of intros) []
bulwahn@38731
   241
bulwahn@38731
   242
fun add_edges edges_of key G =
bulwahn@38731
   243
  let
bulwahn@38731
   244
    fun extend' key (G, visited) = 
bulwahn@38731
   245
      case try (Graph.get_node G) key of
bulwahn@38731
   246
          SOME v =>
bulwahn@38731
   247
            let
bulwahn@38731
   248
              val new_edges = filter (fn k => is_some (try (Graph.get_node G) k)) (edges_of (key, v))
bulwahn@38731
   249
              val (G', visited') = fold extend'
bulwahn@38731
   250
                (subtract (op =) (key :: visited) new_edges) (G, key :: visited)
bulwahn@38731
   251
            in
bulwahn@38731
   252
              (fold (Graph.add_edge o (pair key)) new_edges G', visited')
bulwahn@38731
   253
            end
bulwahn@38731
   254
        | NONE => (G, visited)
bulwahn@38731
   255
  in
bulwahn@38731
   256
    fst (extend' key (G, []))
bulwahn@38731
   257
  end
bulwahn@38731
   258
bulwahn@38792
   259
fun generate ensure_groundness ctxt const =
bulwahn@38073
   260
  let 
bulwahn@38731
   261
    fun strong_conn_of gr keys =
bulwahn@38073
   262
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@38732
   263
    val gr = Predicate_Compile_Core.intros_graph_of ctxt
bulwahn@38731
   264
    val gr' = add_edges depending_preds_of const gr
bulwahn@38731
   265
    val scc = strong_conn_of gr' [const]
bulwahn@38079
   266
    val constant_table = mk_constant_table (flat scc)
bulwahn@38073
   267
  in
bulwahn@38792
   268
    apfst flat (fold_map (translate_intros ensure_groundness ctxt gr) (flat scc) constant_table)
bulwahn@38073
   269
  end
bulwahn@38727
   270
  
bulwahn@38789
   271
(* implementation for fully enumerating predicates and
bulwahn@38789
   272
  for size-limited predicates for enumerating the values of a datatype upto a specific size *)
bulwahn@38073
   273
bulwahn@38727
   274
fun add_ground_typ (Conj prems) = fold add_ground_typ prems
bulwahn@38727
   275
  | add_ground_typ (Ground (_, T)) = insert (op =) T
bulwahn@38727
   276
  | add_ground_typ _ = I
bulwahn@38073
   277
bulwahn@38728
   278
fun mk_relname (Type (Tcon, Targs)) =
bulwahn@38728
   279
  first_lower (Long_Name.base_name Tcon) ^ space_implode "_" (map mk_relname Targs)
bulwahn@38728
   280
  | mk_relname _ = raise Fail "unexpected type"
bulwahn@38728
   281
bulwahn@38789
   282
fun mk_lim_relname T = "lim_" ^  mk_relname T
bulwahn@38789
   283
bulwahn@38728
   284
(* This is copied from "pat_completeness.ML" *)
bulwahn@38728
   285
fun inst_constrs_of thy (T as Type (name, _)) =
bulwahn@38728
   286
  map (fn (Cn,CT) =>
bulwahn@38728
   287
    Envir.subst_term_types (Sign.typ_match thy (body_type CT, T) Vartab.empty) (Const (Cn, CT)))
bulwahn@38728
   288
    (the (Datatype.get_constrs thy name))
bulwahn@38728
   289
  | inst_constrs_of thy T = raise TYPE ("inst_constrs_of", [T], [])
bulwahn@38789
   290
bulwahn@38789
   291
fun is_recursive_constr T (Const (constr_name, T')) = member (op =) (binder_types T') T
bulwahn@38728
   292
  
bulwahn@38789
   293
fun mk_ground_impl ctxt limited_types (T as Type (Tcon, Targs)) (seen, constant_table) =
bulwahn@38728
   294
  if member (op =) seen T then ([], (seen, constant_table))
bulwahn@38728
   295
  else
bulwahn@38728
   296
    let
bulwahn@38789
   297
      val (limited, size) = case AList.lookup (op =) limited_types T of
bulwahn@38789
   298
        SOME s => (true, s)
bulwahn@38789
   299
      | NONE => (false, 0)      
bulwahn@38789
   300
      val rel_name = (if limited then mk_lim_relname else mk_relname) T
bulwahn@38789
   301
      fun mk_impl (Const (constr_name, cT), recursive) (seen, constant_table) =
bulwahn@38727
   302
        let
bulwahn@38727
   303
          val constant_table' = declare_consts [constr_name] constant_table
bulwahn@38789
   304
          val Ts = binder_types cT
bulwahn@38728
   305
          val (rec_clauses, (seen', constant_table'')) =
bulwahn@38789
   306
            fold_map (mk_ground_impl ctxt limited_types) Ts (seen, constant_table')
bulwahn@38789
   307
          val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto (length Ts))
bulwahn@38789
   308
          val lim_var =
bulwahn@38789
   309
            if limited then
bulwahn@38789
   310
              if recursive then [AppF ("suc", [Var "Lim"])]              
bulwahn@38789
   311
              else [Var "Lim"]
bulwahn@38789
   312
            else [] 
bulwahn@38789
   313
          fun mk_prem v T' =
bulwahn@38789
   314
            if limited andalso T' = T then Rel (mk_lim_relname T', [Var "Lim", v])
bulwahn@38789
   315
            else Rel (mk_relname T', [v])
bulwahn@38728
   316
          val clause =
bulwahn@38789
   317
            ((rel_name, lim_var @ [maybe_AppF (translate_const constant_table'' constr_name, vars)]),
bulwahn@38789
   318
             Conj (map2 mk_prem vars Ts))
bulwahn@38727
   319
        in
bulwahn@38728
   320
          (clause :: flat rec_clauses, (seen', constant_table''))
bulwahn@38727
   321
        end
bulwahn@38728
   322
      val constrs = inst_constrs_of (ProofContext.theory_of ctxt) T
bulwahn@38789
   323
      val constrs' = (constrs ~~ map (is_recursive_constr T) constrs)
bulwahn@38789
   324
        |> (fn cs => filter_out snd cs @ filter snd cs)
bulwahn@38789
   325
      val (clauses, constant_table') =
bulwahn@38789
   326
        apfst flat (fold_map mk_impl constrs' (T :: seen, constant_table))
bulwahn@38789
   327
      val size_term = funpow size (fn t => AppF ("suc", [t])) (Cons "zero")
bulwahn@38789
   328
    in
bulwahn@38789
   329
      ((if limited then
bulwahn@38789
   330
        cons ((mk_relname T, [Var "x"]), Rel (mk_lim_relname T, [size_term, Var "x"]))
bulwahn@38789
   331
      else I) clauses, constant_table')
bulwahn@38789
   332
    end
bulwahn@38789
   333
 | mk_ground_impl ctxt _ T (seen, constant_table) =
bulwahn@38728
   334
   raise Fail ("unexpected type :" ^ Syntax.string_of_typ ctxt T)
bulwahn@38728
   335
bulwahn@38727
   336
fun replace_ground (Conj prems) = Conj (map replace_ground prems)
bulwahn@38728
   337
  | replace_ground (Ground (x, T)) =
bulwahn@38728
   338
    Rel (mk_relname T, [Var x])  
bulwahn@38727
   339
  | replace_ground p = p
bulwahn@38727
   340
  
bulwahn@38789
   341
fun add_ground_predicates ctxt limited_types (p, constant_table) =
bulwahn@38727
   342
  let
bulwahn@38727
   343
    val ground_typs = fold (add_ground_typ o snd) p []
bulwahn@38789
   344
    val (grs, (_, constant_table')) = fold_map (mk_ground_impl ctxt limited_types) ground_typs ([], constant_table)
bulwahn@38727
   345
    val p' = map (apsnd replace_ground) p
bulwahn@38073
   346
  in
bulwahn@38727
   347
    ((flat grs) @ p', constant_table')
bulwahn@38073
   348
  end
bulwahn@38789
   349
bulwahn@38789
   350
  
bulwahn@38735
   351
(* rename variables to prolog-friendly names *)
bulwahn@38735
   352
bulwahn@38735
   353
fun rename_vars_term renaming = map_vars (fn v => the (AList.lookup (op =) renaming v))
bulwahn@38735
   354
bulwahn@38735
   355
fun rename_vars_prem renaming = map_term_prem (rename_vars_term renaming)
bulwahn@38735
   356
bulwahn@38735
   357
fun dest_Char (Symbol.Char c) = c
bulwahn@38735
   358
bulwahn@38735
   359
fun is_prolog_conform v =
bulwahn@38735
   360
  forall (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s) (Symbol.explode v)
bulwahn@38735
   361
bulwahn@38735
   362
fun mk_conform avoid v =
bulwahn@38735
   363
  let 
bulwahn@38735
   364
    val v' = space_implode "" (map (dest_Char o Symbol.decode)
bulwahn@38735
   365
      (filter (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s)
bulwahn@38735
   366
        (Symbol.explode v)))
bulwahn@38735
   367
    val v' = if v' = "" then "var" else v'
bulwahn@38735
   368
  in Name.variant avoid (first_upper v') end
bulwahn@38735
   369
  
bulwahn@38735
   370
fun mk_renaming v renaming =
bulwahn@38735
   371
  (v, mk_conform (map snd renaming) v) :: renaming
bulwahn@38735
   372
bulwahn@38735
   373
fun rename_vars_clause ((rel, args), prem) =
bulwahn@38735
   374
  let
bulwahn@38735
   375
    val vars = fold_prem_terms add_vars prem (fold add_vars args [])
bulwahn@38735
   376
    val renaming = fold mk_renaming vars []
bulwahn@38735
   377
  in ((rel, map (rename_vars_term renaming) args), rename_vars_prem renaming prem) end
bulwahn@38735
   378
  
bulwahn@38735
   379
val rename_vars_program = map rename_vars_clause
bulwahn@38735
   380
  
bulwahn@38073
   381
(* code printer *)
bulwahn@38073
   382
bulwahn@38113
   383
fun write_arith_op Plus = "+"
bulwahn@38113
   384
  | write_arith_op Minus = "-"
bulwahn@38113
   385
bulwahn@38735
   386
fun write_term (Var v) = v
bulwahn@38079
   387
  | write_term (Cons c) = c
bulwahn@38113
   388
  | write_term (AppF (f, args)) = f ^ "(" ^ space_implode ", " (map write_term args) ^ ")"
bulwahn@38113
   389
  | write_term (ArithOp (oper, [a1, a2])) = write_term a1 ^ " " ^ write_arith_op oper ^ " " ^ write_term a2
bulwahn@38112
   390
  | write_term (Number n) = string_of_int n
bulwahn@38073
   391
bulwahn@38073
   392
fun write_rel (pred, args) =
bulwahn@38073
   393
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   394
bulwahn@38073
   395
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   396
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   397
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   398
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   399
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38113
   400
  | write_prem (ArithEq (l, r)) = write_term l ^ " is " ^ write_term r
bulwahn@38113
   401
  | write_prem (NotArithEq (l, r)) = write_term l ^ " =\\= " ^ write_term r
bulwahn@38073
   402
bulwahn@38073
   403
fun write_clause (head, prem) =
bulwahn@38073
   404
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   405
bulwahn@38073
   406
fun write_program p =
bulwahn@38073
   407
  cat_lines (map write_clause p) 
bulwahn@38073
   408
bulwahn@38790
   409
(* query templates *)
bulwahn@38078
   410
bulwahn@38792
   411
(** query and prelude for swi-prolog **)
bulwahn@38792
   412
bulwahn@38792
   413
fun swi_prolog_query_first rel vnames =
bulwahn@38073
   414
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38082
   415
  "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38082
   416
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38077
   417
  
bulwahn@38792
   418
fun swi_prolog_query_firstn n rel vnames =
bulwahn@38077
   419
  "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
bulwahn@38077
   420
    rel ^ "(" ^ space_implode ", " vnames ^ "), Sols), writelist(Sols).\n" ^
bulwahn@38077
   421
    "writelist([]).\n" ^
bulwahn@38077
   422
    "writelist([(" ^ space_implode ", " vnames ^ ")|T]) :- " ^
bulwahn@38079
   423
    "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38079
   424
    "\\n', [" ^ space_implode ", " vnames ^ "]), writelist(T).\n"
bulwahn@38077
   425
  
bulwahn@38792
   426
val swi_prolog_prelude =
bulwahn@38073
   427
  "#!/usr/bin/swipl -q -t main -f\n\n" ^
bulwahn@38077
   428
  ":- use_module(library('dialect/ciao/aggregates')).\n" ^
bulwahn@38729
   429
  ":- style_check(-singleton).\n" ^
bulwahn@38729
   430
  ":- style_check(-discontiguous).\n" ^ 	
bulwahn@38729
   431
  ":- style_check(-atom).\n\n" ^
bulwahn@38073
   432
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   433
  "main :- halt(1).\n"
bulwahn@38075
   434
bulwahn@38792
   435
(** query and prelude for yap **)
bulwahn@38792
   436
bulwahn@38792
   437
fun yap_query_first rel vnames =
bulwahn@38792
   438
  "eval :- once(" ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38792
   439
  "format('" ^ space_implode ";" (map (fn v => v ^ " = ~w") vnames) ^
bulwahn@38792
   440
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38792
   441
bulwahn@38792
   442
val yap_prelude =
bulwahn@38792
   443
  "#!/usr/bin/yap -L\n\n" ^
bulwahn@38792
   444
  ":- initialization(eval).\n"
bulwahn@38792
   445
bulwahn@38792
   446
(* system-dependent query, prelude and invocation *)
bulwahn@38792
   447
bulwahn@38792
   448
fun query system nsols = 
bulwahn@38792
   449
  case system of
bulwahn@38792
   450
    SWI_PROLOG =>
bulwahn@38792
   451
      (case nsols of NONE => swi_prolog_query_first | SOME n => swi_prolog_query_firstn n)
bulwahn@38792
   452
  | YAP =>
bulwahn@38792
   453
      case nsols of NONE => yap_query_first | SOME n =>
bulwahn@38792
   454
        error "No support for querying multiple solutions in the prolog system yap"
bulwahn@38792
   455
bulwahn@38792
   456
fun prelude system =
bulwahn@38792
   457
  case system of SWI_PROLOG => swi_prolog_prelude | YAP => yap_prelude
bulwahn@38792
   458
bulwahn@38792
   459
fun invoke system file_name =
bulwahn@38792
   460
  let
bulwahn@38792
   461
    val cmd =
bulwahn@38792
   462
      case system of SWI_PROLOG => "/usr/local/bin/swipl -f " | YAP => "/usr/local/bin/yap -L "
bulwahn@38792
   463
  in bash_output (cmd ^ file_name) end
bulwahn@38792
   464
bulwahn@38075
   465
(* parsing prolog solution *)
bulwahn@38790
   466
bulwahn@38115
   467
val scan_number =
bulwahn@38115
   468
  Scan.many1 Symbol.is_ascii_digit
bulwahn@38075
   469
bulwahn@38075
   470
val scan_atom =
bulwahn@38728
   471
  Scan.many1 (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   472
bulwahn@38075
   473
val scan_var =
bulwahn@38078
   474
  Scan.many1
bulwahn@38078
   475
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   476
bulwahn@38076
   477
val scan_ident =
bulwahn@38076
   478
  Scan.repeat (Scan.one
bulwahn@38076
   479
    (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38076
   480
bulwahn@38075
   481
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   482
bulwahn@38075
   483
val string_of = concat o map (dest_Char o Symbol.decode)
bulwahn@38075
   484
bulwahn@38076
   485
val is_atom_ident = forall Symbol.is_ascii_lower
bulwahn@38076
   486
bulwahn@38076
   487
val is_var_ident =
bulwahn@38076
   488
  forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38078
   489
bulwahn@38115
   490
fun int_of_symbol_list xs = fold (fn x => fn s => s * 10 + (ord x - ord "0")) xs 0
bulwahn@38115
   491
bulwahn@38078
   492
fun scan_terms xs = (((scan_term --| $$ ",") ::: scan_terms)
bulwahn@38078
   493
  || (scan_term >> single)) xs
bulwahn@38078
   494
and scan_term xs =
bulwahn@38115
   495
  ((scan_number >> (Number o int_of_symbol_list))
bulwahn@38115
   496
  || (scan_var >> (Var o string_of))
bulwahn@38078
   497
  || ((scan_atom -- ($$ "(" |-- scan_terms --| $$ ")"))
bulwahn@38079
   498
    >> (fn (f, ts) => AppF (string_of f, ts)))
bulwahn@38078
   499
  || (scan_atom >> (Cons o string_of))) xs
bulwahn@38079
   500
bulwahn@38075
   501
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38077
   502
    (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
bulwahn@38075
   503
  o explode
bulwahn@38075
   504
  
bulwahn@38079
   505
fun parse_solutions sol =
bulwahn@38075
   506
  let
bulwahn@38077
   507
    fun dest_eq s = case space_explode "=" s of
bulwahn@38075
   508
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38078
   509
      | _ => raise Fail "unexpected equation in prolog output"
bulwahn@38079
   510
    fun parse_solution s = map dest_eq (space_explode ";" s)
bulwahn@38075
   511
  in
bulwahn@38079
   512
    map parse_solution (fst (split_last (space_explode "\n" sol)))
bulwahn@38075
   513
  end 
bulwahn@38073
   514
  
bulwahn@38073
   515
(* calling external interpreter and getting results *)
bulwahn@38073
   516
bulwahn@38792
   517
fun run system p query_rel vnames nsols =
bulwahn@38073
   518
  let
bulwahn@38073
   519
    val cmd = Path.named_root
bulwahn@38735
   520
    val p' = rename_vars_program p
bulwahn@38735
   521
    val _ = tracing "Renaming variable names..."
bulwahn@38735
   522
    val renaming = fold mk_renaming vnames [] 
bulwahn@38735
   523
    val vnames' = map (fn v => the (AList.lookup (op =) renaming v)) vnames
bulwahn@38792
   524
    val prog = prelude system ^ query system nsols query_rel vnames' ^ write_program p'
bulwahn@38079
   525
    val _ = tracing ("Generated prolog program:\n" ^ prog)
bulwahn@38073
   526
    val prolog_file = File.tmp_path (Path.basic "prolog_file")
bulwahn@38073
   527
    val _ = File.write prolog_file prog
bulwahn@38792
   528
    val (solution, _) = invoke system (File.shell_path prolog_file)
bulwahn@38079
   529
    val _ = tracing ("Prolog returned solution(s):\n" ^ solution)
bulwahn@38079
   530
    val tss = parse_solutions solution
bulwahn@38073
   531
  in
bulwahn@38079
   532
    tss
bulwahn@38073
   533
  end
bulwahn@38073
   534
bulwahn@38790
   535
(* restoring types in terms *)
bulwahn@38075
   536
bulwahn@38081
   537
fun restore_term ctxt constant_table (Var s, T) = Free (s, T)
bulwahn@38115
   538
  | restore_term ctxt constant_table (Number n, @{typ "int"}) = HOLogic.mk_number @{typ "int"} n
bulwahn@38115
   539
  | restore_term ctxt constant_table (Number n, _) = raise (Fail "unexpected type for number") 
bulwahn@38079
   540
  | restore_term ctxt constant_table (Cons s, T) = Const (restore_const constant_table s, T)
bulwahn@38079
   541
  | restore_term ctxt constant_table (AppF (f, args), T) =
bulwahn@38079
   542
    let
bulwahn@38079
   543
      val thy = ProofContext.theory_of ctxt
bulwahn@38079
   544
      val c = restore_const constant_table f
bulwahn@38079
   545
      val cT = Sign.the_const_type thy c
bulwahn@38079
   546
      val (argsT, resT) = strip_type cT
bulwahn@38079
   547
      val subst = Sign.typ_match thy (resT, T) Vartab.empty
bulwahn@38079
   548
      val argsT' = map (Envir.subst_type subst) argsT
bulwahn@38079
   549
    in
bulwahn@38079
   550
      list_comb (Const (c, Envir.subst_type subst cT),
bulwahn@38079
   551
        map (restore_term ctxt constant_table) (args ~~ argsT'))
bulwahn@38079
   552
    end
bulwahn@38079
   553
bulwahn@38790
   554
(* values command *)
bulwahn@38790
   555
bulwahn@38790
   556
val preprocess_options = Predicate_Compile_Aux.Options {
bulwahn@38790
   557
  expected_modes = NONE,
bulwahn@38790
   558
  proposed_modes = NONE,
bulwahn@38790
   559
  proposed_names = [],
bulwahn@38790
   560
  show_steps = false,
bulwahn@38790
   561
  show_intermediate_results = false,
bulwahn@38790
   562
  show_proof_trace = false,
bulwahn@38790
   563
  show_modes = false,
bulwahn@38790
   564
  show_mode_inference = false,
bulwahn@38790
   565
  show_compilation = false,
bulwahn@38790
   566
  show_caught_failures = false,
bulwahn@38790
   567
  skip_proof = true,
bulwahn@38790
   568
  no_topmost_reordering = false,
bulwahn@38790
   569
  function_flattening = true,
bulwahn@38790
   570
  specialise = false,
bulwahn@38790
   571
  fail_safe_function_flattening = false,
bulwahn@38790
   572
  no_higher_order_predicate = [],
bulwahn@38790
   573
  inductify = false,
bulwahn@38790
   574
  detect_switches = true,
bulwahn@38790
   575
  compilation = Predicate_Compile_Aux.Pred
bulwahn@38790
   576
}
bulwahn@38790
   577
bulwahn@38075
   578
fun values ctxt soln t_compr =
bulwahn@38075
   579
  let
bulwahn@38727
   580
    val options = !options
bulwahn@38075
   581
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   582
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   583
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   584
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   585
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38080
   586
    val output_frees = rev (map2 (curry Free) output_names Ts)
bulwahn@38075
   587
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   588
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   589
      case strip_comb body of
bulwahn@38075
   590
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   591
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38075
   592
    val vnames =
bulwahn@38075
   593
      case try (map (fst o dest_Free)) all_args of
bulwahn@38075
   594
        SOME vs => vs
bulwahn@38075
   595
      | NONE => error ("Not only free variables in " ^ commas (map (Syntax.string_of_term ctxt) all_args))
bulwahn@38732
   596
    val _ = tracing "Preprocessing specification..."
bulwahn@38732
   597
    val T = Sign.the_const_type (ProofContext.theory_of ctxt) name
bulwahn@38732
   598
    val t = Const (name, T)
wenzelm@38755
   599
    val thy' =
wenzelm@38755
   600
      Theory.copy (ProofContext.theory_of ctxt)
wenzelm@38755
   601
      |> Predicate_Compile.preprocess preprocess_options t
wenzelm@38755
   602
    val ctxt' = ProofContext.init_global thy'
bulwahn@38079
   603
    val _ = tracing "Generating prolog program..."
wenzelm@38797
   604
    val (p, constant_table) = generate (#ensure_groundness options) ctxt' name
bulwahn@38789
   605
      |> (if #ensure_groundness options then
wenzelm@38797
   606
          add_ground_predicates ctxt' (#limited_types options)
bulwahn@38789
   607
        else I)
bulwahn@38079
   608
    val _ = tracing "Running prolog program..."
bulwahn@38792
   609
    val tss = run (#prolog_system options)
bulwahn@38792
   610
      p (translate_const constant_table name) (map first_upper vnames) soln
bulwahn@38079
   611
    val _ = tracing "Restoring terms..."
bulwahn@38115
   612
    val empty = Const("Orderings.bot_class.bot", fastype_of t_compr)
bulwahn@38115
   613
    fun mk_insert x S =
bulwahn@38115
   614
      Const (@{const_name "Set.insert"}, fastype_of x --> fastype_of S --> fastype_of S) $ x $ S 
bulwahn@38115
   615
    fun mk_set_compr in_insert [] xs =
bulwahn@38115
   616
       rev ((Free ("...", fastype_of t_compr)) ::
bulwahn@38115
   617
        (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))
bulwahn@38115
   618
      | mk_set_compr in_insert (t :: ts) xs =
bulwahn@38115
   619
        let
bulwahn@38115
   620
          val frees = Term.add_frees t []
bulwahn@38115
   621
        in
bulwahn@38115
   622
          if null frees then
bulwahn@38115
   623
            mk_set_compr (t :: in_insert) ts xs
bulwahn@38115
   624
          else
bulwahn@38115
   625
            let
wenzelm@38755
   626
              val uu as (uuN, uuT) = singleton (Variable.variant_frees ctxt' [t]) ("uu", fastype_of t)
bulwahn@38115
   627
              val set_compr =
bulwahn@38115
   628
                HOLogic.mk_Collect (uuN, uuT, fold (fn (s, T) => fn t => HOLogic.mk_exists (s, T, t))
bulwahn@38115
   629
                  frees (HOLogic.mk_conj (HOLogic.mk_eq (Free uu, t), @{term "True"})))
bulwahn@38115
   630
            in
bulwahn@38729
   631
              mk_set_compr [] ts
bulwahn@38729
   632
                (set_compr :: (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))  
bulwahn@38115
   633
            end
bulwahn@38115
   634
        end
bulwahn@38075
   635
  in
bulwahn@38115
   636
      foldl1 (HOLogic.mk_binop @{const_name sup}) (mk_set_compr []
wenzelm@38755
   637
        (map (fn ts => HOLogic.mk_tuple (map (restore_term ctxt' constant_table) (ts ~~ Ts))) tss) [])
bulwahn@38075
   638
  end
bulwahn@38075
   639
bulwahn@38075
   640
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   641
  let
bulwahn@38075
   642
    val ctxt = Toplevel.context_of state
bulwahn@38075
   643
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   644
    val t' = values ctxt soln t
bulwahn@38075
   645
    val ty' = Term.type_of t'
bulwahn@38075
   646
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38115
   647
    val _ = tracing "Printing terms..."
bulwahn@38075
   648
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   649
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   650
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   651
  in Pretty.writeln p end;
bulwahn@38075
   652
bulwahn@38075
   653
bulwahn@38075
   654
(* renewing the values command for Prolog queries *)
bulwahn@38075
   655
bulwahn@38075
   656
val opt_print_modes =
bulwahn@38075
   657
  Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
bulwahn@38075
   658
bulwahn@38075
   659
val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
bulwahn@38077
   660
  (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
bulwahn@38075
   661
   >> (fn ((print_modes, soln), t) => Toplevel.keep
haftmann@38504
   662
        (values_cmd print_modes soln t))); (*FIXME does not preserve the previous functionality*)
bulwahn@38075
   663
bulwahn@38733
   664
(* quickcheck generator *)
bulwahn@38733
   665
bulwahn@38733
   666
(* FIXME: large copy of Predicate_Compile_Quickcheck - refactor out commons *)
bulwahn@38733
   667
haftmann@38786
   668
fun strip_imp_prems (Const(@{const_name HOL.implies}, _) $ A $ B) = A :: strip_imp_prems B
bulwahn@38733
   669
  | strip_imp_prems _ = [];
bulwahn@38733
   670
haftmann@38786
   671
fun strip_imp_concl (Const(@{const_name HOL.implies}, _) $ A $ B) = strip_imp_concl B
bulwahn@38733
   672
  | strip_imp_concl A = A : term;
bulwahn@38733
   673
bulwahn@38733
   674
fun strip_horn A = (strip_imp_prems A, strip_imp_concl A);
bulwahn@38733
   675
bulwahn@38733
   676
fun quickcheck ctxt report t size =
bulwahn@38733
   677
  let
wenzelm@38755
   678
    val thy = Theory.copy (ProofContext.theory_of ctxt)
bulwahn@38733
   679
    val (vs, t') = strip_abs t
wenzelm@38755
   680
    val vs' = Variable.variant_frees ctxt [] vs
bulwahn@38733
   681
    val Ts = map snd vs'
bulwahn@38733
   682
    val t'' = subst_bounds (map Free (rev vs'), t')
bulwahn@38733
   683
    val (prems, concl) = strip_horn t''
bulwahn@38733
   684
    val constname = "quickcheck"
bulwahn@38733
   685
    val full_constname = Sign.full_bname thy constname
bulwahn@38733
   686
    val constT = Ts ---> @{typ bool}
bulwahn@38733
   687
    val thy1 = Sign.add_consts_i [(Binding.name constname, constT, NoSyn)] thy
bulwahn@38733
   688
    val const = Const (full_constname, constT)
bulwahn@38733
   689
    val t = Logic.list_implies
bulwahn@38733
   690
      (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
bulwahn@38733
   691
       HOLogic.mk_Trueprop (list_comb (Const (full_constname, constT), map Free vs')))
bulwahn@38733
   692
    val tac = fn _ => Skip_Proof.cheat_tac thy1
bulwahn@38733
   693
    val intro = Goal.prove (ProofContext.init_global thy1) (map fst vs') [] t tac
bulwahn@38733
   694
    val thy2 = Context.theory_map (Predicate_Compile_Alternative_Defs.add_thm intro) thy1
bulwahn@38733
   695
    val thy3 = Predicate_Compile.preprocess preprocess_options const thy2
wenzelm@38755
   696
    val ctxt' = ProofContext.init_global thy3
bulwahn@38733
   697
    val _ = tracing "Generating prolog program..."
wenzelm@38797
   698
    val (p, constant_table) = generate true ctxt' full_constname
wenzelm@38797
   699
      |> add_ground_predicates ctxt' (#limited_types (!options))
bulwahn@38733
   700
    val _ = tracing "Running prolog program..."
bulwahn@38792
   701
    val [ts] = run (#prolog_system (!options))
bulwahn@38792
   702
      p (translate_const constant_table full_constname) (map fst vs') (SOME 1)
bulwahn@38733
   703
    val _ = tracing "Restoring terms..."
wenzelm@38755
   704
    val res = SOME (map (restore_term ctxt' constant_table) (ts ~~ Ts))
bulwahn@38733
   705
    val empty_report = ([], false)
bulwahn@38733
   706
  in
bulwahn@38733
   707
    (res, empty_report)
bulwahn@38733
   708
  end; 
bulwahn@38732
   709
bulwahn@38073
   710
end;