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