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