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