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