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