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