src/HOL/Tools/Predicate_Compile/code_prolog.ML
author wenzelm
Fri Mar 16 18:20:12 2012 +0100 (2012-03-16)
changeset 46961 5c6955f487e5
parent 46949 94aa7b81bcf6
child 51126 df86080de4cb
permissions -rw-r--r--
outer syntax command definitions based on formal command_spec derived from theory header declarations;
bulwahn@38073
     1
(*  Title:      HOL/Tools/Predicate_Compile/code_prolog.ML
bulwahn@38073
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@38073
     3
wenzelm@41941
     4
Prototype of an code generator for logic programming languages
wenzelm@41941
     5
(a.k.a. Prolog).
bulwahn@38073
     6
*)
bulwahn@38073
     7
bulwahn@38073
     8
signature CODE_PROLOG =
bulwahn@38073
     9
sig
bulwahn@38792
    10
  datatype prolog_system = SWI_PROLOG | YAP
bulwahn@38792
    11
  type code_options =
bulwahn@38947
    12
    {ensure_groundness : bool,
bulwahn@39798
    13
     limit_globally : int option,
bulwahn@38947
    14
     limited_types : (typ * int) list,
bulwahn@38959
    15
     limited_predicates : (string list * int) list,
bulwahn@38947
    16
     replacing : ((string * string) * string) list,
bulwahn@39461
    17
     manual_reorder : ((string * int) * int list) list}
bulwahn@39461
    18
  val set_ensure_groundness : code_options -> code_options
bulwahn@39461
    19
  val map_limit_predicates : ((string list * int) list -> (string list * int) list)
bulwahn@39461
    20
    -> code_options -> code_options
bulwahn@38950
    21
  val code_options_of : theory -> code_options 
bulwahn@38950
    22
  val map_code_options : (code_options -> code_options) -> theory -> theory
bulwahn@39461
    23
  
bulwahn@38113
    24
  datatype arith_op = Plus | Minus
bulwahn@38112
    25
  datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    26
    | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    27
  datatype prem = Conj of prem list
bulwahn@38113
    28
    | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    29
    | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    30
    | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    31
    | Ground of string * typ;
bulwahn@38727
    32
bulwahn@38079
    33
  type clause = ((string * prol_term list) * prem);
bulwahn@38073
    34
  type logic_program = clause list;
bulwahn@38079
    35
  type constant_table = (string * string) list
bulwahn@39461
    36
  
bulwahn@39461
    37
  val generate : Predicate_Compile_Aux.mode option * bool ->
bulwahn@39461
    38
    Proof.context -> string -> (logic_program * constant_table)
bulwahn@38079
    39
  val write_program : logic_program -> string
bulwahn@43885
    40
  val run : (Time.time * prolog_system) -> logic_program -> (string * prol_term list) ->
bulwahn@43885
    41
    string list -> int option -> prol_term list list
bulwahn@39461
    42
  
bulwahn@43885
    43
  val active : bool Config.T
bulwahn@43885
    44
  val test_goals :
bulwahn@45442
    45
    Proof.context -> bool -> (string * typ) list -> (term * term list) list ->
bulwahn@43885
    46
      Quickcheck.result list
bulwahn@38733
    47
bulwahn@38079
    48
  val trace : bool Unsynchronized.ref
bulwahn@38947
    49
  
bulwahn@38947
    50
  val replace : ((string * string) * string) -> logic_program -> logic_program
bulwahn@38073
    51
end;
bulwahn@38073
    52
bulwahn@38073
    53
structure Code_Prolog : CODE_PROLOG =
bulwahn@38073
    54
struct
bulwahn@38073
    55
bulwahn@38079
    56
(* diagnostic tracing *)
bulwahn@38079
    57
bulwahn@38079
    58
val trace = Unsynchronized.ref false
bulwahn@38079
    59
bulwahn@38079
    60
fun tracing s = if !trace then Output.tracing s else () 
bulwahn@38727
    61
bulwahn@38727
    62
(* code generation options *)
bulwahn@38727
    63
bulwahn@38727
    64
bulwahn@38792
    65
type code_options =
bulwahn@38947
    66
  {ensure_groundness : bool,
bulwahn@39798
    67
   limit_globally : int option,
bulwahn@38947
    68
   limited_types : (typ * int) list,
bulwahn@38959
    69
   limited_predicates : (string list * int) list,
bulwahn@38947
    70
   replacing : ((string * string) * string) list,
bulwahn@39461
    71
   manual_reorder : ((string * int) * int list) list}
bulwahn@39461
    72
bulwahn@38792
    73
bulwahn@39798
    74
fun set_ensure_groundness {ensure_groundness, limit_globally, limited_types, limited_predicates,
bulwahn@39461
    75
  replacing, manual_reorder} =
bulwahn@39798
    76
  {ensure_groundness = true, limit_globally = limit_globally, limited_types = limited_types,
bulwahn@39461
    77
   limited_predicates = limited_predicates, replacing = replacing,
bulwahn@39461
    78
   manual_reorder = manual_reorder}
bulwahn@39461
    79
bulwahn@39798
    80
fun map_limit_predicates f {ensure_groundness, limit_globally, limited_types, limited_predicates,
bulwahn@39461
    81
  replacing, manual_reorder} =
bulwahn@39798
    82
  {ensure_groundness = ensure_groundness, limit_globally = limit_globally, limited_types = limited_types,
bulwahn@39461
    83
   limited_predicates = f limited_predicates, replacing = replacing,
bulwahn@39461
    84
   manual_reorder = manual_reorder}
bulwahn@39798
    85
bulwahn@39798
    86
fun merge_global_limit (NONE, NONE) = NONE
bulwahn@39798
    87
  | merge_global_limit (NONE, SOME n) = SOME n
bulwahn@39798
    88
  | merge_global_limit (SOME n, NONE) = SOME n
wenzelm@41472
    89
  | merge_global_limit (SOME n, SOME m) = SOME (Int.max (n, m))  (* FIXME odd merge *)
bulwahn@39798
    90
   
bulwahn@38950
    91
structure Options = Theory_Data
bulwahn@38950
    92
(
bulwahn@38950
    93
  type T = code_options
bulwahn@39798
    94
  val empty = {ensure_groundness = false, limit_globally = NONE,
bulwahn@39461
    95
    limited_types = [], limited_predicates = [], replacing = [], manual_reorder = []}
bulwahn@38950
    96
  val extend = I;
bulwahn@38950
    97
  fun merge
bulwahn@39798
    98
    ({ensure_groundness = ensure_groundness1, limit_globally = limit_globally1,
bulwahn@39798
    99
      limited_types = limited_types1, limited_predicates = limited_predicates1,
bulwahn@39798
   100
      replacing = replacing1, manual_reorder = manual_reorder1},
bulwahn@39798
   101
     {ensure_groundness = ensure_groundness2, limit_globally = limit_globally2,
bulwahn@39798
   102
      limited_types = limited_types2, limited_predicates = limited_predicates2,
bulwahn@39798
   103
      replacing = replacing2, manual_reorder = manual_reorder2}) =
wenzelm@41472
   104
    {ensure_groundness = ensure_groundness1 orelse ensure_groundness2 (* FIXME odd merge *),
bulwahn@39798
   105
     limit_globally = merge_global_limit (limit_globally1, limit_globally2),
bulwahn@38950
   106
     limited_types = AList.merge (op =) (K true) (limited_types1, limited_types2),
bulwahn@38950
   107
     limited_predicates = AList.merge (op =) (K true) (limited_predicates1, limited_predicates2),
bulwahn@38960
   108
     manual_reorder = AList.merge (op =) (K true) (manual_reorder1, manual_reorder2),
bulwahn@39461
   109
     replacing = Library.merge (op =) (replacing1, replacing2)};
bulwahn@38950
   110
);
bulwahn@38950
   111
bulwahn@38950
   112
val code_options_of = Options.get
bulwahn@38950
   113
bulwahn@38950
   114
val map_code_options = Options.map
bulwahn@38727
   115
bulwahn@39461
   116
(* system configuration *)
bulwahn@39461
   117
bulwahn@39461
   118
datatype prolog_system = SWI_PROLOG | YAP
bulwahn@39461
   119
bulwahn@39462
   120
fun string_of_system SWI_PROLOG = "swiprolog"
bulwahn@39462
   121
  | string_of_system YAP = "yap"
bulwahn@39462
   122
bulwahn@39461
   123
type system_configuration = {timeout : Time.time, prolog_system : prolog_system}
bulwahn@39462
   124
                                                
bulwahn@39461
   125
structure System_Config = Generic_Data
bulwahn@39461
   126
(
bulwahn@39461
   127
  type T = system_configuration
wenzelm@40301
   128
  val empty = {timeout = seconds 10.0, prolog_system = SWI_PROLOG}
bulwahn@39461
   129
  val extend = I;
wenzelm@41472
   130
  fun merge (a, _) = a
bulwahn@39461
   131
)
bulwahn@39461
   132
bulwahn@38073
   133
(* general string functions *)
bulwahn@38073
   134
bulwahn@40924
   135
val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o raw_explode;
bulwahn@40924
   136
val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o raw_explode;
bulwahn@38073
   137
bulwahn@38073
   138
(* internal program representation *)
bulwahn@38073
   139
bulwahn@38113
   140
datatype arith_op = Plus | Minus
bulwahn@38113
   141
bulwahn@38112
   142
datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
   143
  | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
   144
bulwahn@38735
   145
fun dest_Var (Var v) = v
bulwahn@38735
   146
bulwahn@38735
   147
fun add_vars (Var v) = insert (op =) v
bulwahn@38735
   148
  | add_vars (ArithOp (_, ts)) = fold add_vars ts
bulwahn@38735
   149
  | add_vars (AppF (_, ts)) = fold add_vars ts
bulwahn@38735
   150
  | add_vars _ = I
bulwahn@38735
   151
bulwahn@38735
   152
fun map_vars f (Var v) = Var (f v)
bulwahn@38735
   153
  | map_vars f (ArithOp (opr, ts)) = ArithOp (opr, map (map_vars f) ts)
bulwahn@38735
   154
  | map_vars f (AppF (fs, ts)) = AppF (fs, map (map_vars f) ts)
bulwahn@38735
   155
  | map_vars f t = t
bulwahn@38735
   156
  
bulwahn@38728
   157
fun maybe_AppF (c, []) = Cons c
bulwahn@38728
   158
  | maybe_AppF (c, xs) = AppF (c, xs)
bulwahn@38728
   159
bulwahn@38113
   160
fun is_Var (Var _) = true
bulwahn@38113
   161
  | is_Var _ = false
bulwahn@38113
   162
bulwahn@38113
   163
fun is_arith_term (Var _) = true
bulwahn@38113
   164
  | is_arith_term (Number _) = true
bulwahn@38113
   165
  | is_arith_term (ArithOp (_, operands)) = forall is_arith_term operands
bulwahn@38113
   166
  | is_arith_term _ = false
bulwahn@38073
   167
bulwahn@38081
   168
fun string_of_prol_term (Var s) = "Var " ^ s
bulwahn@38075
   169
  | string_of_prol_term (Cons s) = "Cons " ^ s
bulwahn@38075
   170
  | string_of_prol_term (AppF (f, args)) = f ^ "(" ^ commas (map string_of_prol_term args) ^ ")" 
bulwahn@38112
   171
  | string_of_prol_term (Number n) = "Number " ^ string_of_int n
bulwahn@38075
   172
bulwahn@38113
   173
datatype prem = Conj of prem list
bulwahn@38113
   174
  | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
   175
  | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
   176
  | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
   177
  | Ground of string * typ;
bulwahn@38735
   178
bulwahn@38073
   179
fun dest_Rel (Rel (c, ts)) = (c, ts)
bulwahn@38735
   180
bulwahn@38735
   181
fun map_term_prem f (Conj prems) = Conj (map (map_term_prem f) prems)
bulwahn@38735
   182
  | map_term_prem f (Rel (r, ts)) = Rel (r, map f ts)
bulwahn@38735
   183
  | map_term_prem f (NotRel (r, ts)) = NotRel (r, map f ts)
bulwahn@38735
   184
  | map_term_prem f (Eq (l, r)) = Eq (f l, f r)
bulwahn@38735
   185
  | map_term_prem f (NotEq (l, r)) = NotEq (f l, f r)
bulwahn@38735
   186
  | map_term_prem f (ArithEq (l, r)) = ArithEq (f l, f r)
bulwahn@38735
   187
  | map_term_prem f (NotArithEq (l, r)) = NotArithEq (f l, f r)
bulwahn@38735
   188
  | map_term_prem f (Ground (v, T)) = Ground (dest_Var (f (Var v)), T)
bulwahn@38735
   189
bulwahn@38735
   190
fun fold_prem_terms f (Conj prems) = fold (fold_prem_terms f) prems
bulwahn@38735
   191
  | fold_prem_terms f (Rel (_, ts)) = fold f ts
bulwahn@38735
   192
  | fold_prem_terms f (NotRel (_, ts)) = fold f ts
bulwahn@38735
   193
  | fold_prem_terms f (Eq (l, r)) = f l #> f r
bulwahn@38735
   194
  | fold_prem_terms f (NotEq (l, r)) = f l #> f r
bulwahn@38735
   195
  | fold_prem_terms f (ArithEq (l, r)) = f l #> f r
bulwahn@38735
   196
  | fold_prem_terms f (NotArithEq (l, r)) = f l #> f r
bulwahn@38735
   197
  | fold_prem_terms f (Ground (v, T)) = f (Var v)
bulwahn@38735
   198
  
bulwahn@38079
   199
type clause = ((string * prol_term list) * prem);
bulwahn@38073
   200
bulwahn@38073
   201
type logic_program = clause list;
bulwahn@39798
   202
 
bulwahn@38073
   203
(* translation from introduction rules to internal representation *)
bulwahn@38073
   204
bulwahn@38958
   205
fun mk_conform f empty avoid name =
bulwahn@38956
   206
  let
bulwahn@38956
   207
    fun dest_Char (Symbol.Char c) = c
bulwahn@38956
   208
    val name' = space_implode "" (map (dest_Char o Symbol.decode)
bulwahn@38956
   209
      (filter (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s)
bulwahn@38956
   210
        (Symbol.explode name)))
bulwahn@38958
   211
    val name'' = f (if name' = "" then empty else name')
wenzelm@43324
   212
  in if member (op =) avoid name'' then singleton (Name.variant_list avoid) name'' else name'' end
bulwahn@38956
   213
bulwahn@38079
   214
(** constant table **)
bulwahn@38079
   215
bulwahn@38079
   216
type constant_table = (string * string) list
bulwahn@38079
   217
bulwahn@38079
   218
fun declare_consts consts constant_table =
bulwahn@38956
   219
  let
bulwahn@38956
   220
    fun update' c table =
bulwahn@38956
   221
      if AList.defined (op =) table c then table else
bulwahn@38956
   222
        let
bulwahn@38958
   223
          val c' = mk_conform first_lower "pred" (map snd table) (Long_Name.base_name c)
bulwahn@38956
   224
        in
bulwahn@38956
   225
          AList.update (op =) (c, c') table
bulwahn@38956
   226
        end
bulwahn@38956
   227
  in
bulwahn@38956
   228
    fold update' consts constant_table
bulwahn@38956
   229
  end
bulwahn@38079
   230
  
bulwahn@38079
   231
fun translate_const constant_table c =
bulwahn@38079
   232
  case AList.lookup (op =) constant_table c of
bulwahn@38079
   233
    SOME c' => c'
bulwahn@38079
   234
  | NONE => error ("No such constant: " ^ c)
bulwahn@38073
   235
bulwahn@38079
   236
fun inv_lookup _ [] _ = NONE
bulwahn@38079
   237
  | inv_lookup eq ((key, value)::xs) value' =
bulwahn@38079
   238
      if eq (value', value) then SOME key
bulwahn@38079
   239
      else inv_lookup eq xs value';
bulwahn@38079
   240
bulwahn@38079
   241
fun restore_const constant_table c =
bulwahn@38079
   242
  case inv_lookup (op =) constant_table c of
bulwahn@38079
   243
    SOME c' => c'
bulwahn@38079
   244
  | NONE => error ("No constant corresponding to "  ^ c)
bulwahn@38727
   245
bulwahn@38079
   246
(** translation of terms, literals, premises, and clauses **)
bulwahn@38079
   247
bulwahn@38113
   248
fun translate_arith_const @{const_name "Groups.plus_class.plus"} = SOME Plus
bulwahn@38113
   249
  | translate_arith_const @{const_name "Groups.minus_class.minus"} = SOME Minus
bulwahn@38113
   250
  | translate_arith_const _ = NONE
bulwahn@38113
   251
bulwahn@38734
   252
fun mk_nat_term constant_table n =
bulwahn@38734
   253
  let
bulwahn@38734
   254
    val zero = translate_const constant_table @{const_name "Groups.zero_class.zero"}
bulwahn@38734
   255
    val Suc = translate_const constant_table @{const_name "Suc"}
bulwahn@38734
   256
  in funpow n (fn t => AppF (Suc, [t])) (Cons zero) end
bulwahn@38734
   257
bulwahn@38079
   258
fun translate_term ctxt constant_table t =
bulwahn@38112
   259
  case try HOLogic.dest_number t of
bulwahn@38112
   260
    SOME (@{typ "int"}, n) => Number n
bulwahn@38734
   261
  | SOME (@{typ "nat"}, n) => mk_nat_term constant_table n
bulwahn@38112
   262
  | NONE =>
bulwahn@38112
   263
      (case strip_comb t of
bulwahn@38112
   264
        (Free (v, T), []) => Var v 
bulwahn@38112
   265
      | (Const (c, _), []) => Cons (translate_const constant_table c)
bulwahn@38112
   266
      | (Const (c, _), args) =>
bulwahn@38113
   267
        (case translate_arith_const c of
bulwahn@38113
   268
          SOME aop => ArithOp (aop, map (translate_term ctxt constant_table) args)
bulwahn@38113
   269
        | NONE =>                                                             
bulwahn@38113
   270
            AppF (translate_const constant_table c, map (translate_term ctxt constant_table) args))
bulwahn@38112
   271
      | _ => error ("illegal term for translation: " ^ Syntax.string_of_term ctxt t))
bulwahn@38073
   272
bulwahn@38079
   273
fun translate_literal ctxt constant_table t =
bulwahn@38073
   274
  case strip_comb t of
haftmann@38864
   275
    (Const (@{const_name HOL.eq}, _), [l, r]) =>
bulwahn@38113
   276
      let
bulwahn@38113
   277
        val l' = translate_term ctxt constant_table l
bulwahn@38113
   278
        val r' = translate_term ctxt constant_table r
bulwahn@38113
   279
      in
bulwahn@38728
   280
        (if is_Var l' andalso is_arith_term r' andalso not (is_Var r') then ArithEq else Eq) (l', r')
bulwahn@38113
   281
      end
bulwahn@38079
   282
  | (Const (c, _), args) =>
bulwahn@38079
   283
      Rel (translate_const constant_table c, map (translate_term ctxt constant_table) args)
bulwahn@38073
   284
  | _ => error ("illegal literal for translation: " ^ Syntax.string_of_term ctxt t)
bulwahn@38073
   285
bulwahn@38073
   286
fun NegRel_of (Rel lit) = NotRel lit
bulwahn@38073
   287
  | NegRel_of (Eq eq) = NotEq eq
bulwahn@38113
   288
  | NegRel_of (ArithEq eq) = NotArithEq eq
bulwahn@38113
   289
bulwahn@38727
   290
fun mk_groundness_prems t = map Ground (Term.add_frees t [])
bulwahn@38727
   291
  
bulwahn@38792
   292
fun translate_prem ensure_groundness ctxt constant_table t =  
bulwahn@38073
   293
    case try HOLogic.dest_not t of
bulwahn@38727
   294
      SOME t =>
bulwahn@38792
   295
        if ensure_groundness then
bulwahn@38727
   296
          Conj (mk_groundness_prems t @ [NegRel_of (translate_literal ctxt constant_table t)])
bulwahn@38727
   297
        else
bulwahn@38727
   298
          NegRel_of (translate_literal ctxt constant_table t)
bulwahn@38079
   299
    | NONE => translate_literal ctxt constant_table t
bulwahn@38114
   300
    
bulwahn@38114
   301
fun imp_prems_conv cv ct =
bulwahn@38114
   302
  case Thm.term_of ct of
bulwahn@38114
   303
    Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
bulwahn@38114
   304
  | _ => Conv.all_conv ct
bulwahn@38114
   305
bulwahn@38114
   306
fun Trueprop_conv cv ct =
bulwahn@38114
   307
  case Thm.term_of ct of
haftmann@38558
   308
    Const (@{const_name Trueprop}, _) $ _ => Conv.arg_conv cv ct  
bulwahn@38114
   309
  | _ => raise Fail "Trueprop_conv"
bulwahn@38114
   310
bulwahn@38114
   311
fun preprocess_intro thy rule =
bulwahn@38114
   312
  Conv.fconv_rule
bulwahn@38114
   313
    (imp_prems_conv
bulwahn@38114
   314
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv @{thm Predicate.eq_is_eq}))))
bulwahn@38114
   315
    (Thm.transfer thy rule)
bulwahn@38114
   316
bulwahn@38792
   317
fun translate_intros ensure_groundness ctxt gr const constant_table =
bulwahn@38073
   318
  let
wenzelm@42361
   319
    val intros = map (preprocess_intro (Proof_Context.theory_of ctxt)) (Graph.get_node gr const)
bulwahn@38073
   320
    val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
bulwahn@38079
   321
    val constant_table' = declare_consts (fold Term.add_const_names intros' []) constant_table
bulwahn@38073
   322
    fun translate_intro intro =
bulwahn@38073
   323
      let
bulwahn@38073
   324
        val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
bulwahn@38727
   325
        val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro)
bulwahn@38792
   326
        val prems' = Conj (map (translate_prem ensure_groundness ctxt' constant_table') prems)
bulwahn@38079
   327
        val clause = (dest_Rel (translate_literal ctxt' constant_table' head), prems')
bulwahn@38073
   328
      in clause end
bulwahn@39724
   329
  in
bulwahn@39724
   330
    (map translate_intro intros', constant_table')
bulwahn@39724
   331
  end
bulwahn@38073
   332
bulwahn@38731
   333
fun depending_preds_of (key, intros) =
bulwahn@38731
   334
  fold Term.add_const_names (map Thm.prop_of intros) []
bulwahn@38731
   335
bulwahn@38731
   336
fun add_edges edges_of key G =
bulwahn@38731
   337
  let
bulwahn@38731
   338
    fun extend' key (G, visited) = 
bulwahn@38731
   339
      case try (Graph.get_node G) key of
bulwahn@38731
   340
          SOME v =>
bulwahn@38731
   341
            let
bulwahn@38731
   342
              val new_edges = filter (fn k => is_some (try (Graph.get_node G) k)) (edges_of (key, v))
bulwahn@38731
   343
              val (G', visited') = fold extend'
bulwahn@38731
   344
                (subtract (op =) (key :: visited) new_edges) (G, key :: visited)
bulwahn@38731
   345
            in
bulwahn@38731
   346
              (fold (Graph.add_edge o (pair key)) new_edges G', visited')
bulwahn@38731
   347
            end
bulwahn@38731
   348
        | NONE => (G, visited)
bulwahn@38731
   349
  in
bulwahn@38731
   350
    fst (extend' key (G, []))
bulwahn@38731
   351
  end
bulwahn@38731
   352
bulwahn@39183
   353
fun print_intros ctxt gr consts =
bulwahn@39183
   354
  tracing (cat_lines (map (fn const =>
bulwahn@39183
   355
    "Constant " ^ const ^ "has intros:\n" ^
bulwahn@39183
   356
    cat_lines (map (Display.string_of_thm ctxt) (Graph.get_node gr const))) consts))
bulwahn@39461
   357
bulwahn@39461
   358
(* translation of moded predicates *)
bulwahn@39461
   359
bulwahn@39461
   360
(** generating graph of moded predicates **)
bulwahn@39461
   361
bulwahn@39461
   362
(* could be moved to Predicate_Compile_Core *)
bulwahn@39461
   363
fun requires_modes polarity cls =
bulwahn@39461
   364
  let
bulwahn@39461
   365
    fun req_mode_of pol (t, derivation) =
bulwahn@39461
   366
      (case fst (strip_comb t) of
bulwahn@39461
   367
        Const (c, _) => SOME (c, (pol, Predicate_Compile_Core.head_mode_of derivation))
bulwahn@39461
   368
      | _ => NONE)
bulwahn@39461
   369
    fun req (Predicate_Compile_Aux.Prem t, derivation) = req_mode_of polarity (t, derivation)
bulwahn@39461
   370
      | req (Predicate_Compile_Aux.Negprem t, derivation) = req_mode_of (not polarity) (t, derivation)
bulwahn@39461
   371
      | req _ = NONE
bulwahn@39461
   372
  in      
bulwahn@39461
   373
    maps (fn (_, prems) => map_filter req prems) cls
bulwahn@39461
   374
  end
bulwahn@39461
   375
 
bulwahn@39461
   376
structure Mode_Graph = Graph(type key = string * (bool * Predicate_Compile_Aux.mode)
bulwahn@39461
   377
  val ord = prod_ord fast_string_ord (prod_ord bool_ord Predicate_Compile_Aux.mode_ord));
bulwahn@39461
   378
bulwahn@39461
   379
fun mk_moded_clauses_graph ctxt scc gr =
bulwahn@39461
   380
  let
bulwahn@39461
   381
    val options = Predicate_Compile_Aux.default_options
bulwahn@39461
   382
    val mode_analysis_options =
bulwahn@39761
   383
      {use_generators = true, reorder_premises = true, infer_pos_and_neg_modes = true}
bulwahn@39461
   384
    fun infer prednames (gr, (pos_modes, neg_modes, random)) =
bulwahn@39461
   385
      let
bulwahn@39461
   386
        val (lookup_modes, lookup_neg_modes, needs_random) =
bulwahn@39461
   387
          ((fn s => the (AList.lookup (op =) pos_modes s)),
bulwahn@39461
   388
           (fn s => the (AList.lookup (op =) neg_modes s)),
bulwahn@39461
   389
           (fn s => member (op =) (the (AList.lookup (op =) random s))))
bulwahn@39461
   390
        val (preds, all_vs, param_vs, all_modes, clauses) =
bulwahn@39461
   391
          Predicate_Compile_Core.prepare_intrs options ctxt prednames
bulwahn@40054
   392
            (maps (Core_Data.intros_of ctxt) prednames)
bulwahn@39461
   393
        val ((moded_clauses, random'), _) =
bulwahn@40054
   394
          Mode_Inference.infer_modes mode_analysis_options options 
bulwahn@39461
   395
            (lookup_modes, lookup_neg_modes, needs_random) ctxt preds all_modes param_vs clauses
bulwahn@39461
   396
        val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
bulwahn@39461
   397
        val pos_modes' = map (apsnd (map_filter (fn (true, m) => SOME m | _ => NONE))) modes
bulwahn@39461
   398
        val neg_modes' = map (apsnd (map_filter (fn (false, m) => SOME m | _ => NONE))) modes
bulwahn@39461
   399
        val _ = tracing ("Inferred modes:\n" ^
bulwahn@39461
   400
          cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
bulwahn@39461
   401
            (fn (p, m) => Predicate_Compile_Aux.string_of_mode m ^ (if p then "pos" else "neg")) ms)) modes))
bulwahn@39461
   402
        val gr' = gr
bulwahn@39461
   403
          |> fold (fn (p, mps) => fold (fn (mode, cls) =>
bulwahn@39461
   404
                Mode_Graph.new_node ((p, mode), cls)) mps)
bulwahn@39461
   405
            moded_clauses
bulwahn@39461
   406
          |> fold (fn (p, mps) => fold (fn (mode, cls) => fold (fn req =>
bulwahn@39461
   407
              Mode_Graph.add_edge ((p, mode), req)) (requires_modes (fst mode) cls)) mps)
bulwahn@39461
   408
            moded_clauses
bulwahn@39461
   409
      in
bulwahn@39461
   410
        (gr', (AList.merge (op =) (op =) (pos_modes, pos_modes'),
bulwahn@39461
   411
          AList.merge (op =) (op =) (neg_modes, neg_modes'),
bulwahn@39461
   412
          AList.merge (op =) (op =) (random, random')))
bulwahn@39461
   413
      end
bulwahn@39461
   414
  in  
bulwahn@39461
   415
    fst (fold infer (rev scc) (Mode_Graph.empty, ([], [], []))) 
bulwahn@39461
   416
  end
bulwahn@39461
   417
bulwahn@39461
   418
fun declare_moded_predicate moded_preds table =
bulwahn@39461
   419
  let
bulwahn@39461
   420
    fun update' (p as (pred, (pol, mode))) table =
bulwahn@39461
   421
      if AList.defined (op =) table p then table else
bulwahn@39461
   422
        let
bulwahn@39461
   423
          val name = Long_Name.base_name pred ^ (if pol then "p" else "n")
bulwahn@39461
   424
            ^ Predicate_Compile_Aux.ascii_string_of_mode mode
bulwahn@39461
   425
          val p' = mk_conform first_lower "pred" (map snd table) name
bulwahn@39461
   426
        in
bulwahn@39461
   427
          AList.update (op =) (p, p') table
bulwahn@39461
   428
        end
bulwahn@39461
   429
  in
bulwahn@39461
   430
    fold update' moded_preds table
bulwahn@39461
   431
  end
bulwahn@39461
   432
bulwahn@39461
   433
fun mk_program ctxt moded_gr moded_preds (prog, (moded_pred_table, constant_table)) =
bulwahn@39461
   434
  let
bulwahn@39461
   435
    val moded_pred_table' = declare_moded_predicate moded_preds moded_pred_table
bulwahn@39461
   436
    fun mk_literal pol derivation constant_table' t =
bulwahn@39461
   437
      let
bulwahn@39461
   438
        val (p, args) = strip_comb t
bulwahn@39461
   439
        val mode = Predicate_Compile_Core.head_mode_of derivation 
bulwahn@39461
   440
        val name = fst (dest_Const p)
bulwahn@39461
   441
        
bulwahn@39461
   442
        val p' = the (AList.lookup (op =) moded_pred_table' (name, (pol, mode)))
bulwahn@39461
   443
        val args' = map (translate_term ctxt constant_table') args
bulwahn@39461
   444
      in
bulwahn@39461
   445
        Rel (p', args')
bulwahn@39461
   446
      end
bulwahn@39461
   447
    fun mk_prem pol (indprem, derivation) constant_table =
bulwahn@39461
   448
      case indprem of
bulwahn@39461
   449
        Predicate_Compile_Aux.Generator (s, T) => (Ground (s, T), constant_table)
bulwahn@39461
   450
      | _ =>
bulwahn@39461
   451
        declare_consts (Term.add_const_names (Predicate_Compile_Aux.dest_indprem indprem) []) constant_table
bulwahn@39461
   452
        |> (fn constant_table' =>
bulwahn@39461
   453
          (case indprem of Predicate_Compile_Aux.Negprem t =>
bulwahn@39461
   454
            NegRel_of (mk_literal (not pol) derivation constant_table' t)
bulwahn@39461
   455
          | _ =>
bulwahn@39461
   456
            mk_literal pol derivation constant_table' (Predicate_Compile_Aux.dest_indprem indprem), constant_table'))
bulwahn@39461
   457
    fun mk_clause pred_name pol (ts, prems) (prog, constant_table) =
bulwahn@39461
   458
    let
bulwahn@39461
   459
      val constant_table' = declare_consts (fold Term.add_const_names ts []) constant_table
bulwahn@39461
   460
      val args = map (translate_term ctxt constant_table') ts
bulwahn@39461
   461
      val (prems', constant_table'') = fold_map (mk_prem pol) prems constant_table'
bulwahn@39461
   462
    in
bulwahn@39461
   463
      (((pred_name, args), Conj prems') :: prog, constant_table'')
bulwahn@39461
   464
    end
bulwahn@39461
   465
    fun mk_clauses (pred, mode as (pol, _)) =
bulwahn@39461
   466
      let
bulwahn@39461
   467
        val clauses = Mode_Graph.get_node moded_gr (pred, mode)
bulwahn@39461
   468
        val pred_name = the (AList.lookup (op =) moded_pred_table' (pred, mode))
bulwahn@39461
   469
      in
bulwahn@39461
   470
        fold (mk_clause pred_name pol) clauses
bulwahn@39461
   471
      end
bulwahn@39461
   472
  in
bulwahn@39461
   473
    apsnd (pair moded_pred_table') (fold mk_clauses moded_preds (prog, constant_table))
bulwahn@39461
   474
  end
bulwahn@39461
   475
bulwahn@39461
   476
fun generate (use_modes, ensure_groundness) ctxt const =
bulwahn@38073
   477
  let 
bulwahn@38731
   478
    fun strong_conn_of gr keys =
wenzelm@46614
   479
      Graph.strong_conn (Graph.restrict (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@40054
   480
    val gr = Core_Data.intros_graph_of ctxt
bulwahn@38731
   481
    val gr' = add_edges depending_preds_of const gr
bulwahn@38731
   482
    val scc = strong_conn_of gr' [const]
bulwahn@39461
   483
    val initial_constant_table = 
bulwahn@39461
   484
      declare_consts [@{const_name "Groups.zero_class.zero"}, @{const_name "Suc"}] []
bulwahn@38073
   485
  in
bulwahn@39461
   486
    case use_modes of
bulwahn@39461
   487
      SOME mode =>
bulwahn@39461
   488
        let
bulwahn@39461
   489
          val moded_gr = mk_moded_clauses_graph ctxt scc gr
wenzelm@46614
   490
          val moded_gr' = Mode_Graph.restrict
bulwahn@39461
   491
            (member (op =) (Mode_Graph.all_succs moded_gr [(const, (true, mode))])) moded_gr
bulwahn@39461
   492
          val scc = Mode_Graph.strong_conn moded_gr' 
bulwahn@39461
   493
        in
bulwahn@39461
   494
          apfst rev (apsnd snd
bulwahn@39461
   495
            (fold (mk_program ctxt moded_gr') (rev scc) ([], ([], initial_constant_table))))
bulwahn@39461
   496
        end
bulwahn@39461
   497
      | NONE =>
bulwahn@39461
   498
        let 
bulwahn@39461
   499
          val _ = print_intros ctxt gr (flat scc)
bulwahn@39461
   500
          val constant_table = declare_consts (flat scc) initial_constant_table
bulwahn@39461
   501
        in
bulwahn@39461
   502
          apfst flat (fold_map (translate_intros ensure_groundness ctxt gr) (flat scc) constant_table)
bulwahn@39461
   503
        end
bulwahn@38073
   504
  end
bulwahn@38727
   505
  
bulwahn@38789
   506
(* implementation for fully enumerating predicates and
bulwahn@38789
   507
  for size-limited predicates for enumerating the values of a datatype upto a specific size *)
bulwahn@38073
   508
bulwahn@38727
   509
fun add_ground_typ (Conj prems) = fold add_ground_typ prems
bulwahn@38727
   510
  | add_ground_typ (Ground (_, T)) = insert (op =) T
bulwahn@38727
   511
  | add_ground_typ _ = I
bulwahn@38073
   512
bulwahn@38728
   513
fun mk_relname (Type (Tcon, Targs)) =
bulwahn@38728
   514
  first_lower (Long_Name.base_name Tcon) ^ space_implode "_" (map mk_relname Targs)
bulwahn@38728
   515
  | mk_relname _ = raise Fail "unexpected type"
bulwahn@38728
   516
bulwahn@38789
   517
fun mk_lim_relname T = "lim_" ^  mk_relname T
bulwahn@38789
   518
bulwahn@38728
   519
(* This is copied from "pat_completeness.ML" *)
bulwahn@38728
   520
fun inst_constrs_of thy (T as Type (name, _)) =
bulwahn@38728
   521
  map (fn (Cn,CT) =>
bulwahn@38728
   522
    Envir.subst_term_types (Sign.typ_match thy (body_type CT, T) Vartab.empty) (Const (Cn, CT)))
bulwahn@38728
   523
    (the (Datatype.get_constrs thy name))
bulwahn@38728
   524
  | inst_constrs_of thy T = raise TYPE ("inst_constrs_of", [T], [])
bulwahn@38789
   525
bulwahn@38789
   526
fun is_recursive_constr T (Const (constr_name, T')) = member (op =) (binder_types T') T
bulwahn@38728
   527
  
bulwahn@38789
   528
fun mk_ground_impl ctxt limited_types (T as Type (Tcon, Targs)) (seen, constant_table) =
bulwahn@38728
   529
  if member (op =) seen T then ([], (seen, constant_table))
bulwahn@38728
   530
  else
bulwahn@38728
   531
    let
bulwahn@38789
   532
      val (limited, size) = case AList.lookup (op =) limited_types T of
bulwahn@38789
   533
        SOME s => (true, s)
bulwahn@38789
   534
      | NONE => (false, 0)      
bulwahn@38789
   535
      val rel_name = (if limited then mk_lim_relname else mk_relname) T
bulwahn@38789
   536
      fun mk_impl (Const (constr_name, cT), recursive) (seen, constant_table) =
bulwahn@38727
   537
        let
bulwahn@38727
   538
          val constant_table' = declare_consts [constr_name] constant_table
bulwahn@38789
   539
          val Ts = binder_types cT
bulwahn@38728
   540
          val (rec_clauses, (seen', constant_table'')) =
bulwahn@38789
   541
            fold_map (mk_ground_impl ctxt limited_types) Ts (seen, constant_table')
bulwahn@38789
   542
          val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto (length Ts))
bulwahn@38789
   543
          val lim_var =
bulwahn@38789
   544
            if limited then
bulwahn@38789
   545
              if recursive then [AppF ("suc", [Var "Lim"])]              
bulwahn@38789
   546
              else [Var "Lim"]
bulwahn@38789
   547
            else [] 
bulwahn@38789
   548
          fun mk_prem v T' =
bulwahn@38789
   549
            if limited andalso T' = T then Rel (mk_lim_relname T', [Var "Lim", v])
bulwahn@38789
   550
            else Rel (mk_relname T', [v])
bulwahn@38728
   551
          val clause =
bulwahn@38789
   552
            ((rel_name, lim_var @ [maybe_AppF (translate_const constant_table'' constr_name, vars)]),
bulwahn@38789
   553
             Conj (map2 mk_prem vars Ts))
bulwahn@38727
   554
        in
bulwahn@38728
   555
          (clause :: flat rec_clauses, (seen', constant_table''))
bulwahn@38727
   556
        end
wenzelm@42361
   557
      val constrs = inst_constrs_of (Proof_Context.theory_of ctxt) T
bulwahn@38789
   558
      val constrs' = (constrs ~~ map (is_recursive_constr T) constrs)
bulwahn@38789
   559
        |> (fn cs => filter_out snd cs @ filter snd cs)
bulwahn@38789
   560
      val (clauses, constant_table') =
bulwahn@38789
   561
        apfst flat (fold_map mk_impl constrs' (T :: seen, constant_table))
bulwahn@38789
   562
      val size_term = funpow size (fn t => AppF ("suc", [t])) (Cons "zero")
bulwahn@38789
   563
    in
bulwahn@38789
   564
      ((if limited then
bulwahn@38789
   565
        cons ((mk_relname T, [Var "x"]), Rel (mk_lim_relname T, [size_term, Var "x"]))
bulwahn@38789
   566
      else I) clauses, constant_table')
bulwahn@38789
   567
    end
bulwahn@38789
   568
 | mk_ground_impl ctxt _ T (seen, constant_table) =
bulwahn@38728
   569
   raise Fail ("unexpected type :" ^ Syntax.string_of_typ ctxt T)
bulwahn@38728
   570
bulwahn@38727
   571
fun replace_ground (Conj prems) = Conj (map replace_ground prems)
bulwahn@38728
   572
  | replace_ground (Ground (x, T)) =
bulwahn@38728
   573
    Rel (mk_relname T, [Var x])  
bulwahn@38727
   574
  | replace_ground p = p
bulwahn@38727
   575
  
bulwahn@38789
   576
fun add_ground_predicates ctxt limited_types (p, constant_table) =
bulwahn@38727
   577
  let
bulwahn@38727
   578
    val ground_typs = fold (add_ground_typ o snd) p []
bulwahn@38789
   579
    val (grs, (_, constant_table')) = fold_map (mk_ground_impl ctxt limited_types) ground_typs ([], constant_table)
bulwahn@38727
   580
    val p' = map (apsnd replace_ground) p
bulwahn@38073
   581
  in
bulwahn@38727
   582
    ((flat grs) @ p', constant_table')
bulwahn@38073
   583
  end
bulwahn@38789
   584
bulwahn@38947
   585
(* make depth-limited version of predicate *)
bulwahn@38947
   586
bulwahn@38947
   587
fun mk_lim_rel_name rel_name = "lim_" ^ rel_name
bulwahn@38947
   588
bulwahn@38959
   589
fun mk_depth_limited rel_names ((rel_name, ts), prem) =
bulwahn@38947
   590
  let
bulwahn@38947
   591
    fun has_positive_recursive_prems (Conj prems) = exists has_positive_recursive_prems prems
bulwahn@38959
   592
      | has_positive_recursive_prems (Rel (rel, ts)) = member (op =) rel_names rel
bulwahn@38947
   593
      | has_positive_recursive_prems _ = false
bulwahn@38947
   594
    fun mk_lim_prem (Conj prems) = Conj (map mk_lim_prem prems)
bulwahn@38947
   595
      | mk_lim_prem (p as Rel (rel, ts)) =
bulwahn@38959
   596
        if member (op =) rel_names rel then Rel (mk_lim_rel_name rel, Var "Lim" :: ts) else p
bulwahn@38947
   597
      | mk_lim_prem p = p
bulwahn@38947
   598
  in
bulwahn@38947
   599
    if has_positive_recursive_prems prem then
bulwahn@38947
   600
      ((mk_lim_rel_name rel_name, (AppF ("suc", [Var "Lim"]))  :: ts), mk_lim_prem prem)
bulwahn@38947
   601
    else
bulwahn@38947
   602
      ((mk_lim_rel_name rel_name, (Var "Lim") :: ts), prem)
bulwahn@38947
   603
  end
bulwahn@38947
   604
bulwahn@39798
   605
fun nat_term_of n = funpow n (fn t => AppF ("suc", [t])) (Cons "zero")
bulwahn@39798
   606
bulwahn@39798
   607
fun add_limited_predicates limited_predicates (p, constant_table) =
bulwahn@38956
   608
  let                                     
bulwahn@39798
   609
    fun add (rel_names, limit) p = 
bulwahn@38947
   610
      let
bulwahn@38959
   611
        val clauses = filter (fn ((rel, _), _) => member (op =) rel_names rel) p
bulwahn@38959
   612
        val clauses' = map (mk_depth_limited rel_names) clauses
bulwahn@38959
   613
        fun mk_entry_clause rel_name =
bulwahn@38959
   614
          let
bulwahn@38959
   615
            val nargs = length (snd (fst
bulwahn@38959
   616
              (the (find_first (fn ((rel, _), _) => rel = rel_name) clauses))))
bulwahn@38959
   617
            val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto nargs)        
bulwahn@38959
   618
          in
bulwahn@38959
   619
            (("limited_" ^ rel_name, vars), Rel ("lim_" ^ rel_name, nat_term_of limit :: vars))
bulwahn@38959
   620
          end
bulwahn@39798
   621
      in (p @ (map mk_entry_clause rel_names) @ clauses') end
bulwahn@38947
   622
  in
bulwahn@39798
   623
    (fold add limited_predicates p, constant_table)
bulwahn@38947
   624
  end
bulwahn@38947
   625
bulwahn@38947
   626
bulwahn@38947
   627
(* replace predicates in clauses *)
bulwahn@38947
   628
bulwahn@38947
   629
(* replace (A, B, C) p = replace A by B in clauses of C *)
bulwahn@38947
   630
fun replace ((from, to), location) p =
bulwahn@38947
   631
  let
bulwahn@38947
   632
    fun replace_prem (Conj prems) = Conj (map replace_prem prems)
bulwahn@38947
   633
      | replace_prem (r as Rel (rel, ts)) =
bulwahn@38947
   634
          if rel = from then Rel (to, ts) else r
bulwahn@38947
   635
      | replace_prem r = r
bulwahn@38947
   636
  in
bulwahn@38947
   637
    map (fn ((rel, args), prem) => ((rel, args), (if rel = location then replace_prem else I) prem)) p
bulwahn@38947
   638
  end
bulwahn@38947
   639
bulwahn@38960
   640
  
bulwahn@38960
   641
(* reorder manually : reorder premises of ith clause of predicate p by a permutation perm *)
bulwahn@38947
   642
bulwahn@38960
   643
fun reorder_manually reorder p =
bulwahn@38960
   644
  let
bulwahn@38960
   645
    fun reorder' (clause as ((rel, args), prem)) seen =
bulwahn@38960
   646
      let
bulwahn@38960
   647
        val seen' = AList.map_default (op =) (rel, 0) (fn x => x + 1) seen
bulwahn@38960
   648
        val i = the (AList.lookup (op =) seen' rel)
bulwahn@38960
   649
        val perm = AList.lookup (op =) reorder (rel, i)
bulwahn@38960
   650
        val prem' = (case perm of 
bulwahn@38960
   651
          SOME p => (case prem of Conj prems => Conj (map (nth prems) p) | _ => prem)
bulwahn@38960
   652
        | NONE => prem)
bulwahn@38960
   653
      in (((rel, args), prem'), seen') end
bulwahn@38960
   654
  in
bulwahn@38960
   655
    fst (fold_map reorder' p [])
bulwahn@38960
   656
  end
bulwahn@39462
   657
bulwahn@38735
   658
(* rename variables to prolog-friendly names *)
bulwahn@38735
   659
bulwahn@38735
   660
fun rename_vars_term renaming = map_vars (fn v => the (AList.lookup (op =) renaming v))
bulwahn@38735
   661
bulwahn@38735
   662
fun rename_vars_prem renaming = map_term_prem (rename_vars_term renaming)
bulwahn@38735
   663
bulwahn@38735
   664
fun is_prolog_conform v =
bulwahn@38735
   665
  forall (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s) (Symbol.explode v)
bulwahn@38735
   666
  
bulwahn@38735
   667
fun mk_renaming v renaming =
bulwahn@38958
   668
  (v, mk_conform first_upper "Var" (map snd renaming) v) :: renaming
bulwahn@38735
   669
bulwahn@38735
   670
fun rename_vars_clause ((rel, args), prem) =
bulwahn@38735
   671
  let
bulwahn@38735
   672
    val vars = fold_prem_terms add_vars prem (fold add_vars args [])
bulwahn@38735
   673
    val renaming = fold mk_renaming vars []
bulwahn@38735
   674
  in ((rel, map (rename_vars_term renaming) args), rename_vars_prem renaming prem) end
bulwahn@38735
   675
  
bulwahn@38735
   676
val rename_vars_program = map rename_vars_clause
bulwahn@38956
   677
bulwahn@39798
   678
(* limit computation globally by some threshold *)
bulwahn@39798
   679
bulwahn@39798
   680
fun limit_globally ctxt limit const_name (p, constant_table) =
bulwahn@39798
   681
  let
bulwahn@39798
   682
    val rel_names = fold (fn ((r, _), _) => insert (op =) r) p []
bulwahn@39798
   683
    val p' = map (mk_depth_limited rel_names) p
bulwahn@39798
   684
    val rel_name = translate_const constant_table const_name
bulwahn@39798
   685
    val nargs = length (snd (fst
bulwahn@39798
   686
      (the (find_first (fn ((rel, _), _) => rel = rel_name) p))))
bulwahn@39798
   687
    val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto nargs)
bulwahn@39798
   688
    val entry_clause = ((rel_name, vars), Rel ("lim_" ^ rel_name, nat_term_of limit :: vars))
bulwahn@39798
   689
    val p'' = filter_out (fn ((rel, _), _) => rel = rel_name) p
bulwahn@39798
   690
  in
bulwahn@39798
   691
    (entry_clause :: p' @ p'', constant_table)
bulwahn@39798
   692
  end
bulwahn@39798
   693
bulwahn@39542
   694
(* post processing of generated prolog program *)
bulwahn@39542
   695
bulwahn@39798
   696
fun post_process ctxt options const_name (p, constant_table) =
bulwahn@39542
   697
  (p, constant_table)
bulwahn@39798
   698
  |> (case #limit_globally options of
bulwahn@39798
   699
        SOME limit => limit_globally ctxt limit const_name
bulwahn@39798
   700
      | NONE => I)
bulwahn@39542
   701
  |> (if #ensure_groundness options then
bulwahn@39542
   702
        add_ground_predicates ctxt (#limited_types options)
bulwahn@39542
   703
      else I)
bulwahn@39724
   704
  |> tap (fn _ => tracing "Adding limited predicates...")
bulwahn@39542
   705
  |> add_limited_predicates (#limited_predicates options)
bulwahn@39724
   706
  |> tap (fn _ => tracing "Replacing predicates...")
bulwahn@39542
   707
  |> apfst (fold replace (#replacing options))
bulwahn@39542
   708
  |> apfst (reorder_manually (#manual_reorder options))
bulwahn@39542
   709
  |> apfst rename_vars_program
bulwahn@39542
   710
bulwahn@38073
   711
(* code printer *)
bulwahn@38073
   712
bulwahn@38113
   713
fun write_arith_op Plus = "+"
bulwahn@38113
   714
  | write_arith_op Minus = "-"
bulwahn@38113
   715
bulwahn@38735
   716
fun write_term (Var v) = v
bulwahn@38079
   717
  | write_term (Cons c) = c
bulwahn@38113
   718
  | write_term (AppF (f, args)) = f ^ "(" ^ space_implode ", " (map write_term args) ^ ")"
bulwahn@38113
   719
  | write_term (ArithOp (oper, [a1, a2])) = write_term a1 ^ " " ^ write_arith_op oper ^ " " ^ write_term a2
bulwahn@38112
   720
  | write_term (Number n) = string_of_int n
bulwahn@38073
   721
bulwahn@38073
   722
fun write_rel (pred, args) =
bulwahn@38073
   723
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   724
bulwahn@38073
   725
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   726
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   727
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   728
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   729
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38113
   730
  | write_prem (ArithEq (l, r)) = write_term l ^ " is " ^ write_term r
bulwahn@38113
   731
  | write_prem (NotArithEq (l, r)) = write_term l ^ " =\\= " ^ write_term r
bulwahn@39461
   732
  | write_prem _ = raise Fail "Not a valid prolog premise"
bulwahn@38073
   733
bulwahn@38073
   734
fun write_clause (head, prem) =
bulwahn@38073
   735
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   736
bulwahn@38073
   737
fun write_program p =
bulwahn@38073
   738
  cat_lines (map write_clause p) 
bulwahn@38073
   739
bulwahn@38790
   740
(* query templates *)
bulwahn@38078
   741
bulwahn@38792
   742
(** query and prelude for swi-prolog **)
bulwahn@38792
   743
bulwahn@39464
   744
fun swi_prolog_query_first (rel, args) vnames =
bulwahn@39464
   745
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " (map write_term args) ^ ")),\n" ^
bulwahn@38082
   746
  "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38082
   747
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38077
   748
  
bulwahn@39464
   749
fun swi_prolog_query_firstn n (rel, args) vnames =
bulwahn@38077
   750
  "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
bulwahn@39464
   751
    rel ^ "(" ^ space_implode ", " (map write_term args) ^ "), Sols), writelist(Sols).\n" ^
bulwahn@38077
   752
    "writelist([]).\n" ^
bulwahn@39546
   753
    "writelist([(" ^ space_implode ", " vnames ^ ")|SolutionTail]) :- " ^
bulwahn@38079
   754
    "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@39546
   755
    "\\n', [" ^ space_implode ", " vnames ^ "]), writelist(SolutionTail).\n"
bulwahn@38077
   756
  
bulwahn@38792
   757
val swi_prolog_prelude =
wenzelm@41952
   758
  "#!/usr/bin/swipl -q -t main -f\n\n" ^  (* FIXME hardwired executable!? *)
bulwahn@38077
   759
  ":- use_module(library('dialect/ciao/aggregates')).\n" ^
bulwahn@38729
   760
  ":- style_check(-singleton).\n" ^
wenzelm@41067
   761
  ":- style_check(-discontiguous).\n" ^
bulwahn@38729
   762
  ":- style_check(-atom).\n\n" ^
bulwahn@38073
   763
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   764
  "main :- halt(1).\n"
bulwahn@38075
   765
bulwahn@38792
   766
(** query and prelude for yap **)
bulwahn@38792
   767
bulwahn@39464
   768
fun yap_query_first (rel, args) vnames =
bulwahn@39464
   769
  "eval :- once(" ^ rel ^ "(" ^ space_implode ", " (map write_term args) ^ ")),\n" ^
bulwahn@38792
   770
  "format('" ^ space_implode ";" (map (fn v => v ^ " = ~w") vnames) ^
bulwahn@38792
   771
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38792
   772
bulwahn@38792
   773
val yap_prelude =
bulwahn@38792
   774
  "#!/usr/bin/yap -L\n\n" ^
bulwahn@38792
   775
  ":- initialization(eval).\n"
bulwahn@38792
   776
bulwahn@38792
   777
(* system-dependent query, prelude and invocation *)
bulwahn@38792
   778
bulwahn@38792
   779
fun query system nsols = 
bulwahn@38792
   780
  case system of
bulwahn@38792
   781
    SWI_PROLOG =>
bulwahn@38792
   782
      (case nsols of NONE => swi_prolog_query_first | SOME n => swi_prolog_query_firstn n)
bulwahn@38792
   783
  | YAP =>
bulwahn@38792
   784
      case nsols of NONE => yap_query_first | SOME n =>
bulwahn@38792
   785
        error "No support for querying multiple solutions in the prolog system yap"
bulwahn@38792
   786
bulwahn@38792
   787
fun prelude system =
bulwahn@38792
   788
  case system of SWI_PROLOG => swi_prolog_prelude | YAP => yap_prelude
bulwahn@38792
   789
wenzelm@41940
   790
fun invoke system file =
bulwahn@38792
   791
  let
wenzelm@41940
   792
    val (env_var, cmd) =
wenzelm@41940
   793
      (case system of
wenzelm@41952
   794
        SWI_PROLOG => ("ISABELLE_SWIPL", "\"$ISABELLE_SWIPL\" -f ")
wenzelm@41952
   795
      | YAP => ("ISABELLE_YAP", "\"$ISABELLE_YAP\" -L "))
bulwahn@39462
   796
  in
wenzelm@41940
   797
    if getenv env_var = "" then
bulwahn@39462
   798
      (warning (env_var ^ " not set; could not execute code for " ^ string_of_system system); "")
wenzelm@43850
   799
    else fst (Isabelle_System.bash_output (cmd ^ File.shell_path file))
bulwahn@39462
   800
  end
bulwahn@38792
   801
wenzelm@41952
   802
bulwahn@38075
   803
(* parsing prolog solution *)
bulwahn@38790
   804
bulwahn@38115
   805
val scan_number =
bulwahn@38115
   806
  Scan.many1 Symbol.is_ascii_digit
bulwahn@38075
   807
bulwahn@38075
   808
val scan_atom =
bulwahn@38728
   809
  Scan.many1 (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   810
bulwahn@38075
   811
val scan_var =
bulwahn@38078
   812
  Scan.many1
bulwahn@38078
   813
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   814
bulwahn@38076
   815
val scan_ident =
bulwahn@38076
   816
  Scan.repeat (Scan.one
bulwahn@38076
   817
    (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38076
   818
bulwahn@38075
   819
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   820
bulwahn@43735
   821
val string_of = implode o map (dest_Char o Symbol.decode)
bulwahn@38075
   822
bulwahn@38076
   823
val is_atom_ident = forall Symbol.is_ascii_lower
bulwahn@38076
   824
bulwahn@38076
   825
val is_var_ident =
bulwahn@38076
   826
  forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38078
   827
bulwahn@38115
   828
fun int_of_symbol_list xs = fold (fn x => fn s => s * 10 + (ord x - ord "0")) xs 0
bulwahn@38115
   829
bulwahn@38078
   830
fun scan_terms xs = (((scan_term --| $$ ",") ::: scan_terms)
bulwahn@38078
   831
  || (scan_term >> single)) xs
bulwahn@38078
   832
and scan_term xs =
bulwahn@38115
   833
  ((scan_number >> (Number o int_of_symbol_list))
bulwahn@38115
   834
  || (scan_var >> (Var o string_of))
bulwahn@38078
   835
  || ((scan_atom -- ($$ "(" |-- scan_terms --| $$ ")"))
bulwahn@38079
   836
    >> (fn (f, ts) => AppF (string_of f, ts)))
bulwahn@38078
   837
  || (scan_atom >> (Cons o string_of))) xs
bulwahn@38079
   838
bulwahn@38075
   839
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38077
   840
    (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
bulwahn@40924
   841
  o raw_explode
bulwahn@38075
   842
  
bulwahn@38079
   843
fun parse_solutions sol =
bulwahn@38075
   844
  let
bulwahn@38077
   845
    fun dest_eq s = case space_explode "=" s of
bulwahn@38075
   846
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38078
   847
      | _ => raise Fail "unexpected equation in prolog output"
bulwahn@38079
   848
    fun parse_solution s = map dest_eq (space_explode ";" s)
bulwahn@38961
   849
    val sols = case space_explode "\n" sol of [] => [] | s => fst (split_last s)  
bulwahn@38075
   850
  in
bulwahn@38961
   851
    map parse_solution sols
bulwahn@38075
   852
  end 
bulwahn@38073
   853
  
bulwahn@38073
   854
(* calling external interpreter and getting results *)
bulwahn@38073
   855
bulwahn@39464
   856
fun run (timeout, system) p (query_rel, args) vnames nsols =
bulwahn@38073
   857
  let
bulwahn@39464
   858
    val renaming = fold mk_renaming (fold add_vars args vnames) [] 
bulwahn@38735
   859
    val vnames' = map (fn v => the (AList.lookup (op =) renaming v)) vnames
bulwahn@39464
   860
    val args' = map (rename_vars_term renaming) args
bulwahn@39542
   861
    val prog = prelude system ^ query system nsols (query_rel, args') vnames' ^ write_program p
bulwahn@38079
   862
    val _ = tracing ("Generated prolog program:\n" ^ prog)
wenzelm@41307
   863
    val solution = TimeLimit.timeLimit timeout (fn prog =>
wenzelm@42127
   864
      Isabelle_System.with_tmp_file "prolog_file" "" (fn prolog_file =>
wenzelm@41940
   865
        (File.write prolog_file prog; invoke system prolog_file))) prog
bulwahn@38079
   866
    val _ = tracing ("Prolog returned solution(s):\n" ^ solution)
bulwahn@38079
   867
    val tss = parse_solutions solution
bulwahn@38073
   868
  in
bulwahn@38079
   869
    tss
bulwahn@38073
   870
  end
bulwahn@38073
   871
bulwahn@38790
   872
(* restoring types in terms *)
bulwahn@38075
   873
bulwahn@38081
   874
fun restore_term ctxt constant_table (Var s, T) = Free (s, T)
bulwahn@38115
   875
  | restore_term ctxt constant_table (Number n, @{typ "int"}) = HOLogic.mk_number @{typ "int"} n
bulwahn@38115
   876
  | restore_term ctxt constant_table (Number n, _) = raise (Fail "unexpected type for number") 
bulwahn@38079
   877
  | restore_term ctxt constant_table (Cons s, T) = Const (restore_const constant_table s, T)
bulwahn@38079
   878
  | restore_term ctxt constant_table (AppF (f, args), T) =
bulwahn@38079
   879
    let
wenzelm@42361
   880
      val thy = Proof_Context.theory_of ctxt
bulwahn@38079
   881
      val c = restore_const constant_table f
bulwahn@38079
   882
      val cT = Sign.the_const_type thy c
bulwahn@38079
   883
      val (argsT, resT) = strip_type cT
bulwahn@38079
   884
      val subst = Sign.typ_match thy (resT, T) Vartab.empty
bulwahn@38079
   885
      val argsT' = map (Envir.subst_type subst) argsT
bulwahn@38079
   886
    in
bulwahn@38079
   887
      list_comb (Const (c, Envir.subst_type subst cT),
bulwahn@38079
   888
        map (restore_term ctxt constant_table) (args ~~ argsT'))
bulwahn@38079
   889
    end
bulwahn@38079
   890
bulwahn@39465
   891
    
bulwahn@39465
   892
(* restore numerals in natural numbers *)
bulwahn@39465
   893
bulwahn@39465
   894
fun restore_nat_numerals t =
bulwahn@39465
   895
  if fastype_of t = @{typ nat} andalso is_some (try HOLogic.dest_nat t) then
bulwahn@39465
   896
    HOLogic.mk_number @{typ nat} (HOLogic.dest_nat t)
bulwahn@39465
   897
  else
bulwahn@39465
   898
    (case t of
bulwahn@39465
   899
        t1 $ t2 => restore_nat_numerals t1 $ restore_nat_numerals t2
bulwahn@39465
   900
      | t => t)
bulwahn@39465
   901
  
bulwahn@38790
   902
(* values command *)
bulwahn@38790
   903
bulwahn@38790
   904
val preprocess_options = Predicate_Compile_Aux.Options {
bulwahn@38790
   905
  expected_modes = NONE,
bulwahn@39383
   906
  proposed_modes = [],
bulwahn@38790
   907
  proposed_names = [],
bulwahn@38790
   908
  show_steps = false,
bulwahn@38790
   909
  show_intermediate_results = false,
bulwahn@38790
   910
  show_proof_trace = false,
bulwahn@38790
   911
  show_modes = false,
bulwahn@38790
   912
  show_mode_inference = false,
bulwahn@38790
   913
  show_compilation = false,
bulwahn@38790
   914
  show_caught_failures = false,
bulwahn@39383
   915
  show_invalid_clauses = false,
bulwahn@38790
   916
  skip_proof = true,
bulwahn@38790
   917
  no_topmost_reordering = false,
bulwahn@38790
   918
  function_flattening = true,
bulwahn@38790
   919
  specialise = false,
bulwahn@38790
   920
  fail_safe_function_flattening = false,
bulwahn@38790
   921
  no_higher_order_predicate = [],
bulwahn@38790
   922
  inductify = false,
bulwahn@38790
   923
  detect_switches = true,
bulwahn@40054
   924
  smart_depth_limiting = true,
bulwahn@38790
   925
  compilation = Predicate_Compile_Aux.Pred
bulwahn@38790
   926
}
bulwahn@38790
   927
bulwahn@38075
   928
fun values ctxt soln t_compr =
bulwahn@38075
   929
  let
wenzelm@42361
   930
    val options = code_options_of (Proof_Context.theory_of ctxt)
bulwahn@38075
   931
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   932
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   933
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   934
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   935
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38080
   936
    val output_frees = rev (map2 (curry Free) output_names Ts)
bulwahn@38075
   937
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   938
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   939
      case strip_comb body of
bulwahn@38075
   940
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   941
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38732
   942
    val _ = tracing "Preprocessing specification..."
wenzelm@42361
   943
    val T = Sign.the_const_type (Proof_Context.theory_of ctxt) name
bulwahn@38732
   944
    val t = Const (name, T)
wenzelm@38755
   945
    val thy' =
wenzelm@42361
   946
      Theory.copy (Proof_Context.theory_of ctxt)
wenzelm@38755
   947
      |> Predicate_Compile.preprocess preprocess_options t
wenzelm@42361
   948
    val ctxt' = Proof_Context.init_global thy'
bulwahn@38079
   949
    val _ = tracing "Generating prolog program..."
bulwahn@39461
   950
    val (p, constant_table) = generate (NONE, #ensure_groundness options) ctxt' name (* FIXME *)
bulwahn@39798
   951
      |> post_process ctxt' options name
bulwahn@39464
   952
    val constant_table' = declare_consts (fold Term.add_const_names all_args []) constant_table
bulwahn@39464
   953
    val args' = map (translate_term ctxt constant_table') all_args
bulwahn@38079
   954
    val _ = tracing "Running prolog program..."
bulwahn@39461
   955
    val system_config = System_Config.get (Context.Proof ctxt)
bulwahn@39461
   956
    val tss = run (#timeout system_config, #prolog_system system_config)
bulwahn@39464
   957
      p (translate_const constant_table' name, args') output_names soln
bulwahn@38079
   958
    val _ = tracing "Restoring terms..."
bulwahn@38115
   959
    val empty = Const("Orderings.bot_class.bot", fastype_of t_compr)
bulwahn@38115
   960
    fun mk_insert x S =
bulwahn@38115
   961
      Const (@{const_name "Set.insert"}, fastype_of x --> fastype_of S --> fastype_of S) $ x $ S 
bulwahn@38115
   962
    fun mk_set_compr in_insert [] xs =
wenzelm@42489
   963
       rev ((Free ("dots", fastype_of t_compr)) ::  (* FIXME proper name!? *)
bulwahn@38115
   964
        (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))
bulwahn@38115
   965
      | mk_set_compr in_insert (t :: ts) xs =
bulwahn@38115
   966
        let
bulwahn@38115
   967
          val frees = Term.add_frees t []
bulwahn@38115
   968
        in
bulwahn@38115
   969
          if null frees then
bulwahn@38115
   970
            mk_set_compr (t :: in_insert) ts xs
bulwahn@38115
   971
          else
bulwahn@38115
   972
            let
wenzelm@38755
   973
              val uu as (uuN, uuT) = singleton (Variable.variant_frees ctxt' [t]) ("uu", fastype_of t)
bulwahn@38115
   974
              val set_compr =
bulwahn@38115
   975
                HOLogic.mk_Collect (uuN, uuT, fold (fn (s, T) => fn t => HOLogic.mk_exists (s, T, t))
bulwahn@38115
   976
                  frees (HOLogic.mk_conj (HOLogic.mk_eq (Free uu, t), @{term "True"})))
bulwahn@38115
   977
            in
bulwahn@38729
   978
              mk_set_compr [] ts
bulwahn@38729
   979
                (set_compr :: (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))  
bulwahn@38115
   980
            end
bulwahn@38115
   981
        end
bulwahn@38075
   982
  in
bulwahn@38115
   983
      foldl1 (HOLogic.mk_binop @{const_name sup}) (mk_set_compr []
bulwahn@39465
   984
        (map (fn ts => HOLogic.mk_tuple 
bulwahn@39465
   985
          (map (restore_nat_numerals o restore_term ctxt' constant_table) (ts ~~ Ts))) tss) [])
bulwahn@38075
   986
  end
bulwahn@38075
   987
bulwahn@38075
   988
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   989
  let
bulwahn@38075
   990
    val ctxt = Toplevel.context_of state
bulwahn@38075
   991
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   992
    val t' = values ctxt soln t
bulwahn@38075
   993
    val ty' = Term.type_of t'
bulwahn@38075
   994
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38115
   995
    val _ = tracing "Printing terms..."
bulwahn@38075
   996
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   997
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   998
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   999
  in Pretty.writeln p end;
bulwahn@38075
  1000
bulwahn@38075
  1001
bulwahn@38075
  1002
(* renewing the values command for Prolog queries *)
bulwahn@38075
  1003
bulwahn@38075
  1004
val opt_print_modes =
wenzelm@46949
  1005
  Scan.optional (@{keyword "("} |-- Parse.!!! (Scan.repeat1 Parse.xname --| @{keyword ")"})) [];
bulwahn@38075
  1006
wenzelm@46961
  1007
val _ =
wenzelm@46961
  1008
  Outer_Syntax.improper_command @{command_spec "values"}
wenzelm@46961
  1009
    "enumerate and print comprehensions"
wenzelm@46961
  1010
    (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
wenzelm@46961
  1011
     >> (fn ((print_modes, soln), t) => Toplevel.keep
wenzelm@46961
  1012
          (values_cmd print_modes soln t))); (*FIXME does not preserve the previous functionality*)
wenzelm@46961
  1013
bulwahn@38075
  1014
bulwahn@38733
  1015
(* quickcheck generator *)
bulwahn@38733
  1016
bulwahn@39541
  1017
(* FIXME: a small clone of Predicate_Compile_Quickcheck - maybe refactor out commons *)
bulwahn@38733
  1018
bulwahn@43885
  1019
val active = Attrib.setup_config_bool @{binding quickcheck_prolog_active} (K true);
bulwahn@43885
  1020
bulwahn@45442
  1021
fun test_term ctxt (t, eval_terms) =
bulwahn@38733
  1022
  let
wenzelm@44241
  1023
    val t' = fold_rev absfree (Term.add_frees t []) t
wenzelm@42361
  1024
    val options = code_options_of (Proof_Context.theory_of ctxt)
wenzelm@42361
  1025
    val thy = Theory.copy (Proof_Context.theory_of ctxt)
bulwahn@39541
  1026
    val ((((full_constname, constT), vs'), intro), thy1) =
bulwahn@42091
  1027
      Predicate_Compile_Aux.define_quickcheck_predicate t' thy
bulwahn@38733
  1028
    val thy2 = Context.theory_map (Predicate_Compile_Alternative_Defs.add_thm intro) thy1
bulwahn@39541
  1029
    val thy3 = Predicate_Compile.preprocess preprocess_options (Const (full_constname, constT)) thy2
wenzelm@42361
  1030
    val ctxt' = Proof_Context.init_global thy3
bulwahn@38733
  1031
    val _ = tracing "Generating prolog program..."
bulwahn@39461
  1032
    val (p, constant_table) = generate (NONE, true) ctxt' full_constname
bulwahn@39798
  1033
      |> post_process ctxt' (set_ensure_groundness options) full_constname
bulwahn@38733
  1034
    val _ = tracing "Running prolog program..."
bulwahn@39461
  1035
    val system_config = System_Config.get (Context.Proof ctxt)
bulwahn@39461
  1036
    val tss = run (#timeout system_config, #prolog_system system_config)
bulwahn@39464
  1037
      p (translate_const constant_table full_constname, map (Var o fst) vs') (map fst vs') (SOME 1)
bulwahn@38733
  1038
    val _ = tracing "Restoring terms..."
bulwahn@43885
  1039
    val counterexample =
bulwahn@38961
  1040
      case tss of
bulwahn@39541
  1041
        [ts] => SOME (map (restore_term ctxt' constant_table) (ts ~~ map snd vs'))
bulwahn@38961
  1042
      | _ => NONE
bulwahn@38733
  1043
  in
bulwahn@43885
  1044
    Quickcheck.Result
bulwahn@45750
  1045
      {counterexample = Option.map (pair true o curry (op ~~) (Term.add_free_names t [])) counterexample,
bulwahn@43885
  1046
       evaluation_terms = Option.map (K []) counterexample, timings = [], reports = []}
bulwahn@43885
  1047
  end;
bulwahn@38732
  1048
bulwahn@45442
  1049
fun test_goals ctxt _ insts goals =
bulwahn@43885
  1050
  let
bulwahn@45226
  1051
    val correct_inst_goals = Quickcheck_Common.instantiate_goals ctxt insts goals
bulwahn@43885
  1052
  in
bulwahn@45442
  1053
    Quickcheck_Common.collect_results (test_term ctxt) (maps (map snd) correct_inst_goals) []
bulwahn@43885
  1054
  end
bulwahn@43885
  1055
  
bulwahn@43885
  1056
  
bulwahn@38073
  1057
end;