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