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