src/HOL/Tools/Predicate_Compile/code_prolog.ML
author bulwahn
Wed Aug 25 16:59:53 2010 +0200 (2010-08-25)
changeset 38734 e5508a74b11f
parent 38733 4b8fd91ea59a
child 38735 cb9031a9dccf
permissions -rw-r--r--
changing hotel trace definition; adding simple handling of numerals on natural numbers
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@38727
     9
  type code_options = {ensure_groundness : bool}
bulwahn@38727
    10
  val options : code_options ref
bulwahn@38727
    11
bulwahn@38113
    12
  datatype arith_op = Plus | Minus
bulwahn@38112
    13
  datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    14
    | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    15
  datatype prem = Conj of prem list
bulwahn@38113
    16
    | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    17
    | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    18
    | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    19
    | Ground of string * typ;
bulwahn@38727
    20
bulwahn@38079
    21
  type clause = ((string * prol_term list) * prem);
bulwahn@38073
    22
  type logic_program = clause list;
bulwahn@38079
    23
  type constant_table = (string * string) list
bulwahn@38727
    24
    
bulwahn@38731
    25
  val generate : code_options -> Proof.context -> string -> (logic_program * constant_table)
bulwahn@38079
    26
  val write_program : logic_program -> string
bulwahn@38079
    27
  val run : logic_program -> string -> string list -> int option -> prol_term list list
bulwahn@38073
    28
bulwahn@38733
    29
  val quickcheck : Proof.context -> bool -> term -> int -> term list option * (bool list * bool)
bulwahn@38733
    30
bulwahn@38079
    31
  val trace : bool Unsynchronized.ref
bulwahn@38073
    32
end;
bulwahn@38073
    33
bulwahn@38073
    34
structure Code_Prolog : CODE_PROLOG =
bulwahn@38073
    35
struct
bulwahn@38073
    36
bulwahn@38079
    37
(* diagnostic tracing *)
bulwahn@38079
    38
bulwahn@38079
    39
val trace = Unsynchronized.ref false
bulwahn@38079
    40
bulwahn@38079
    41
fun tracing s = if !trace then Output.tracing s else () 
bulwahn@38727
    42
bulwahn@38727
    43
(* code generation options *)
bulwahn@38727
    44
bulwahn@38727
    45
type code_options = {ensure_groundness : bool}
bulwahn@38727
    46
bulwahn@38727
    47
val options = Unsynchronized.ref {ensure_groundness = false};
bulwahn@38727
    48
bulwahn@38073
    49
(* general string functions *)
bulwahn@38073
    50
bulwahn@38073
    51
val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
bulwahn@38073
    52
val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
bulwahn@38073
    53
bulwahn@38073
    54
(* internal program representation *)
bulwahn@38073
    55
bulwahn@38113
    56
datatype arith_op = Plus | Minus
bulwahn@38113
    57
bulwahn@38112
    58
datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    59
  | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    60
bulwahn@38728
    61
fun maybe_AppF (c, []) = Cons c
bulwahn@38728
    62
  | maybe_AppF (c, xs) = AppF (c, xs)
bulwahn@38728
    63
bulwahn@38113
    64
fun is_Var (Var _) = true
bulwahn@38113
    65
  | is_Var _ = false
bulwahn@38113
    66
bulwahn@38113
    67
fun is_arith_term (Var _) = true
bulwahn@38113
    68
  | is_arith_term (Number _) = true
bulwahn@38113
    69
  | is_arith_term (ArithOp (_, operands)) = forall is_arith_term operands
bulwahn@38113
    70
  | is_arith_term _ = false
bulwahn@38073
    71
bulwahn@38081
    72
fun string_of_prol_term (Var s) = "Var " ^ s
bulwahn@38075
    73
  | string_of_prol_term (Cons s) = "Cons " ^ s
bulwahn@38075
    74
  | string_of_prol_term (AppF (f, args)) = f ^ "(" ^ commas (map string_of_prol_term args) ^ ")" 
bulwahn@38112
    75
  | string_of_prol_term (Number n) = "Number " ^ string_of_int n
bulwahn@38075
    76
bulwahn@38113
    77
datatype prem = Conj of prem list
bulwahn@38113
    78
  | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    79
  | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    80
  | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    81
  | Ground of string * typ;
bulwahn@38727
    82
  
bulwahn@38073
    83
fun dest_Rel (Rel (c, ts)) = (c, ts)
bulwahn@38073
    84
 
bulwahn@38079
    85
type clause = ((string * prol_term list) * prem);
bulwahn@38073
    86
bulwahn@38073
    87
type logic_program = clause list;
bulwahn@38073
    88
bulwahn@38073
    89
(* translation from introduction rules to internal representation *)
bulwahn@38073
    90
bulwahn@38079
    91
(** constant table **)
bulwahn@38079
    92
bulwahn@38079
    93
type constant_table = (string * string) list
bulwahn@38079
    94
bulwahn@38073
    95
(* assuming no clashing *)
bulwahn@38079
    96
fun mk_constant_table consts =
bulwahn@38079
    97
  AList.make (first_lower o Long_Name.base_name) consts
bulwahn@38079
    98
bulwahn@38079
    99
fun declare_consts consts constant_table =
bulwahn@38079
   100
  fold (fn c => AList.update (op =) (c, first_lower (Long_Name.base_name c))) consts constant_table
bulwahn@38079
   101
  
bulwahn@38079
   102
fun translate_const constant_table c =
bulwahn@38079
   103
  case AList.lookup (op =) constant_table c of
bulwahn@38079
   104
    SOME c' => c'
bulwahn@38079
   105
  | NONE => error ("No such constant: " ^ c)
bulwahn@38073
   106
bulwahn@38079
   107
fun inv_lookup _ [] _ = NONE
bulwahn@38079
   108
  | inv_lookup eq ((key, value)::xs) value' =
bulwahn@38079
   109
      if eq (value', value) then SOME key
bulwahn@38079
   110
      else inv_lookup eq xs value';
bulwahn@38079
   111
bulwahn@38079
   112
fun restore_const constant_table c =
bulwahn@38079
   113
  case inv_lookup (op =) constant_table c of
bulwahn@38079
   114
    SOME c' => c'
bulwahn@38079
   115
  | NONE => error ("No constant corresponding to "  ^ c)
bulwahn@38727
   116
bulwahn@38079
   117
(** translation of terms, literals, premises, and clauses **)
bulwahn@38079
   118
bulwahn@38113
   119
fun translate_arith_const @{const_name "Groups.plus_class.plus"} = SOME Plus
bulwahn@38113
   120
  | translate_arith_const @{const_name "Groups.minus_class.minus"} = SOME Minus
bulwahn@38113
   121
  | translate_arith_const _ = NONE
bulwahn@38113
   122
bulwahn@38734
   123
fun mk_nat_term constant_table n =
bulwahn@38734
   124
  let
bulwahn@38734
   125
    val zero = translate_const constant_table @{const_name "Groups.zero_class.zero"}
bulwahn@38734
   126
    val Suc = translate_const constant_table @{const_name "Suc"}
bulwahn@38734
   127
  in funpow n (fn t => AppF (Suc, [t])) (Cons zero) end
bulwahn@38734
   128
bulwahn@38079
   129
fun translate_term ctxt constant_table t =
bulwahn@38112
   130
  case try HOLogic.dest_number t of
bulwahn@38112
   131
    SOME (@{typ "int"}, n) => Number n
bulwahn@38734
   132
  | SOME (@{typ "nat"}, n) => mk_nat_term constant_table n
bulwahn@38112
   133
  | NONE =>
bulwahn@38112
   134
      (case strip_comb t of
bulwahn@38112
   135
        (Free (v, T), []) => Var v 
bulwahn@38112
   136
      | (Const (c, _), []) => Cons (translate_const constant_table c)
bulwahn@38112
   137
      | (Const (c, _), args) =>
bulwahn@38113
   138
        (case translate_arith_const c of
bulwahn@38113
   139
          SOME aop => ArithOp (aop, map (translate_term ctxt constant_table) args)
bulwahn@38113
   140
        | NONE =>                                                             
bulwahn@38113
   141
            AppF (translate_const constant_table c, map (translate_term ctxt constant_table) args))
bulwahn@38112
   142
      | _ => error ("illegal term for translation: " ^ Syntax.string_of_term ctxt t))
bulwahn@38073
   143
bulwahn@38079
   144
fun translate_literal ctxt constant_table t =
bulwahn@38073
   145
  case strip_comb t of
bulwahn@38079
   146
    (Const (@{const_name "op ="}, _), [l, r]) =>
bulwahn@38113
   147
      let
bulwahn@38113
   148
        val l' = translate_term ctxt constant_table l
bulwahn@38113
   149
        val r' = translate_term ctxt constant_table r
bulwahn@38113
   150
      in
bulwahn@38728
   151
        (if is_Var l' andalso is_arith_term r' andalso not (is_Var r') then ArithEq else Eq) (l', r')
bulwahn@38113
   152
      end
bulwahn@38079
   153
  | (Const (c, _), args) =>
bulwahn@38079
   154
      Rel (translate_const constant_table c, map (translate_term ctxt constant_table) args)
bulwahn@38073
   155
  | _ => error ("illegal literal for translation: " ^ Syntax.string_of_term ctxt t)
bulwahn@38073
   156
bulwahn@38073
   157
fun NegRel_of (Rel lit) = NotRel lit
bulwahn@38073
   158
  | NegRel_of (Eq eq) = NotEq eq
bulwahn@38113
   159
  | NegRel_of (ArithEq eq) = NotArithEq eq
bulwahn@38113
   160
bulwahn@38727
   161
fun mk_groundness_prems t = map Ground (Term.add_frees t [])
bulwahn@38727
   162
  
bulwahn@38727
   163
fun translate_prem options ctxt constant_table t =  
bulwahn@38073
   164
    case try HOLogic.dest_not t of
bulwahn@38727
   165
      SOME t =>
bulwahn@38727
   166
        if #ensure_groundness options then
bulwahn@38727
   167
          Conj (mk_groundness_prems t @ [NegRel_of (translate_literal ctxt constant_table t)])
bulwahn@38727
   168
        else
bulwahn@38727
   169
          NegRel_of (translate_literal ctxt constant_table t)
bulwahn@38079
   170
    | NONE => translate_literal ctxt constant_table t
bulwahn@38114
   171
    
bulwahn@38114
   172
fun imp_prems_conv cv ct =
bulwahn@38114
   173
  case Thm.term_of ct of
bulwahn@38114
   174
    Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
bulwahn@38114
   175
  | _ => Conv.all_conv ct
bulwahn@38114
   176
bulwahn@38114
   177
fun Trueprop_conv cv ct =
bulwahn@38114
   178
  case Thm.term_of ct of
haftmann@38558
   179
    Const (@{const_name Trueprop}, _) $ _ => Conv.arg_conv cv ct  
bulwahn@38114
   180
  | _ => raise Fail "Trueprop_conv"
bulwahn@38114
   181
bulwahn@38114
   182
fun preprocess_intro thy rule =
bulwahn@38114
   183
  Conv.fconv_rule
bulwahn@38114
   184
    (imp_prems_conv
bulwahn@38114
   185
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv @{thm Predicate.eq_is_eq}))))
bulwahn@38114
   186
    (Thm.transfer thy rule)
bulwahn@38114
   187
bulwahn@38727
   188
fun translate_intros options ctxt gr const constant_table =
bulwahn@38073
   189
  let
bulwahn@38114
   190
    val intros = map (preprocess_intro (ProofContext.theory_of ctxt)) (Graph.get_node gr const)
bulwahn@38073
   191
    val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
bulwahn@38079
   192
    val constant_table' = declare_consts (fold Term.add_const_names intros' []) constant_table
bulwahn@38734
   193
      |> declare_consts [@{const_name "Groups.zero_class.zero"}, @{const_name "Suc"}]
bulwahn@38073
   194
    fun translate_intro intro =
bulwahn@38073
   195
      let
bulwahn@38073
   196
        val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
bulwahn@38727
   197
        val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro)
bulwahn@38727
   198
        val prems' = Conj (map (translate_prem options ctxt' constant_table') prems)
bulwahn@38079
   199
        val clause = (dest_Rel (translate_literal ctxt' constant_table' head), prems')
bulwahn@38073
   200
      in clause end
bulwahn@38079
   201
  in (map translate_intro intros', constant_table') end
bulwahn@38073
   202
bulwahn@38731
   203
val preprocess_options = Predicate_Compile_Aux.Options {
bulwahn@38731
   204
  expected_modes = NONE,
bulwahn@38731
   205
  proposed_modes = NONE,
bulwahn@38731
   206
  proposed_names = [],
bulwahn@38731
   207
  show_steps = false,
bulwahn@38731
   208
  show_intermediate_results = false,
bulwahn@38731
   209
  show_proof_trace = false,
bulwahn@38731
   210
  show_modes = false,
bulwahn@38731
   211
  show_mode_inference = false,
bulwahn@38731
   212
  show_compilation = false,
bulwahn@38731
   213
  show_caught_failures = false,
bulwahn@38731
   214
  skip_proof = true,
bulwahn@38731
   215
  no_topmost_reordering = false,
bulwahn@38731
   216
  function_flattening = true,
bulwahn@38731
   217
  specialise = false,
bulwahn@38731
   218
  fail_safe_function_flattening = false,
bulwahn@38731
   219
  no_higher_order_predicate = [],
bulwahn@38731
   220
  inductify = false,
bulwahn@38731
   221
  detect_switches = true,
bulwahn@38731
   222
  compilation = Predicate_Compile_Aux.Pred
bulwahn@38731
   223
}
bulwahn@38731
   224
bulwahn@38731
   225
fun depending_preds_of (key, intros) =
bulwahn@38731
   226
  fold Term.add_const_names (map Thm.prop_of intros) []
bulwahn@38731
   227
bulwahn@38731
   228
fun add_edges edges_of key G =
bulwahn@38731
   229
  let
bulwahn@38731
   230
    fun extend' key (G, visited) = 
bulwahn@38731
   231
      case try (Graph.get_node G) key of
bulwahn@38731
   232
          SOME v =>
bulwahn@38731
   233
            let
bulwahn@38731
   234
              val new_edges = filter (fn k => is_some (try (Graph.get_node G) k)) (edges_of (key, v))
bulwahn@38731
   235
              val (G', visited') = fold extend'
bulwahn@38731
   236
                (subtract (op =) (key :: visited) new_edges) (G, key :: visited)
bulwahn@38731
   237
            in
bulwahn@38731
   238
              (fold (Graph.add_edge o (pair key)) new_edges G', visited')
bulwahn@38731
   239
            end
bulwahn@38731
   240
        | NONE => (G, visited)
bulwahn@38731
   241
  in
bulwahn@38731
   242
    fst (extend' key (G, []))
bulwahn@38731
   243
  end
bulwahn@38731
   244
bulwahn@38727
   245
fun generate options ctxt const =
bulwahn@38073
   246
  let 
bulwahn@38731
   247
    fun strong_conn_of gr keys =
bulwahn@38073
   248
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@38732
   249
    val gr = Predicate_Compile_Core.intros_graph_of ctxt
bulwahn@38731
   250
    val gr' = add_edges depending_preds_of const gr
bulwahn@38731
   251
    val scc = strong_conn_of gr' [const]
bulwahn@38079
   252
    val constant_table = mk_constant_table (flat scc)
bulwahn@38073
   253
  in
bulwahn@38732
   254
    apfst flat (fold_map (translate_intros options ctxt gr) (flat scc) constant_table)
bulwahn@38073
   255
  end
bulwahn@38727
   256
  
bulwahn@38727
   257
(* add implementation for ground predicates *)
bulwahn@38073
   258
bulwahn@38727
   259
fun add_ground_typ (Conj prems) = fold add_ground_typ prems
bulwahn@38727
   260
  | add_ground_typ (Ground (_, T)) = insert (op =) T
bulwahn@38727
   261
  | add_ground_typ _ = I
bulwahn@38073
   262
bulwahn@38728
   263
fun mk_relname (Type (Tcon, Targs)) =
bulwahn@38728
   264
  first_lower (Long_Name.base_name Tcon) ^ space_implode "_" (map mk_relname Targs)
bulwahn@38728
   265
  | mk_relname _ = raise Fail "unexpected type"
bulwahn@38728
   266
bulwahn@38728
   267
(* This is copied from "pat_completeness.ML" *)
bulwahn@38728
   268
fun inst_constrs_of thy (T as Type (name, _)) =
bulwahn@38728
   269
  map (fn (Cn,CT) =>
bulwahn@38728
   270
    Envir.subst_term_types (Sign.typ_match thy (body_type CT, T) Vartab.empty) (Const (Cn, CT)))
bulwahn@38728
   271
    (the (Datatype.get_constrs thy name))
bulwahn@38728
   272
  | inst_constrs_of thy T = raise TYPE ("inst_constrs_of", [T], [])
bulwahn@38728
   273
  
bulwahn@38728
   274
fun mk_ground_impl ctxt (T as Type (Tcon, Targs)) (seen, constant_table) =
bulwahn@38728
   275
  if member (op =) seen T then ([], (seen, constant_table))
bulwahn@38728
   276
  else
bulwahn@38728
   277
    let
bulwahn@38728
   278
      val rel_name = mk_relname T
bulwahn@38728
   279
      fun mk_impl (Const (constr_name, T)) (seen, constant_table) =
bulwahn@38727
   280
        let
bulwahn@38727
   281
          val constant_table' = declare_consts [constr_name] constant_table
bulwahn@38728
   282
          val (rec_clauses, (seen', constant_table'')) =
bulwahn@38728
   283
            fold_map (mk_ground_impl ctxt) (binder_types T) (seen, constant_table')
bulwahn@38728
   284
          val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto (length (binder_types T)))    
bulwahn@38728
   285
          fun mk_prem v T = Rel (mk_relname T, [v])
bulwahn@38728
   286
          val clause =
bulwahn@38728
   287
            ((rel_name, [maybe_AppF (translate_const constant_table'' constr_name, vars)]),
bulwahn@38728
   288
             Conj (map2 mk_prem vars (binder_types T)))
bulwahn@38727
   289
        in
bulwahn@38728
   290
          (clause :: flat rec_clauses, (seen', constant_table''))
bulwahn@38727
   291
        end
bulwahn@38728
   292
      val constrs = inst_constrs_of (ProofContext.theory_of ctxt) T
bulwahn@38728
   293
    in apfst flat (fold_map mk_impl constrs (T :: seen, constant_table)) end
bulwahn@38728
   294
 | mk_ground_impl ctxt T (seen, constant_table) =
bulwahn@38728
   295
   raise Fail ("unexpected type :" ^ Syntax.string_of_typ ctxt T)
bulwahn@38728
   296
bulwahn@38727
   297
fun replace_ground (Conj prems) = Conj (map replace_ground prems)
bulwahn@38728
   298
  | replace_ground (Ground (x, T)) =
bulwahn@38728
   299
    Rel (mk_relname T, [Var x])  
bulwahn@38727
   300
  | replace_ground p = p
bulwahn@38727
   301
  
bulwahn@38727
   302
fun add_ground_predicates ctxt (p, constant_table) =
bulwahn@38727
   303
  let
bulwahn@38727
   304
    val ground_typs = fold (add_ground_typ o snd) p []
bulwahn@38728
   305
    val (grs, (_, constant_table')) = fold_map (mk_ground_impl ctxt) ground_typs ([], constant_table)
bulwahn@38727
   306
    val p' = map (apsnd replace_ground) p
bulwahn@38073
   307
  in
bulwahn@38727
   308
    ((flat grs) @ p', constant_table')
bulwahn@38073
   309
  end
bulwahn@38727
   310
    
bulwahn@38073
   311
(* code printer *)
bulwahn@38073
   312
bulwahn@38113
   313
fun write_arith_op Plus = "+"
bulwahn@38113
   314
  | write_arith_op Minus = "-"
bulwahn@38113
   315
bulwahn@38081
   316
fun write_term (Var v) = first_upper v
bulwahn@38079
   317
  | write_term (Cons c) = c
bulwahn@38113
   318
  | write_term (AppF (f, args)) = f ^ "(" ^ space_implode ", " (map write_term args) ^ ")"
bulwahn@38113
   319
  | write_term (ArithOp (oper, [a1, a2])) = write_term a1 ^ " " ^ write_arith_op oper ^ " " ^ write_term a2
bulwahn@38112
   320
  | write_term (Number n) = string_of_int n
bulwahn@38073
   321
bulwahn@38073
   322
fun write_rel (pred, args) =
bulwahn@38073
   323
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   324
bulwahn@38073
   325
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   326
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   327
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   328
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   329
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38113
   330
  | write_prem (ArithEq (l, r)) = write_term l ^ " is " ^ write_term r
bulwahn@38113
   331
  | write_prem (NotArithEq (l, r)) = write_term l ^ " =\\= " ^ write_term r
bulwahn@38073
   332
bulwahn@38073
   333
fun write_clause (head, prem) =
bulwahn@38073
   334
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   335
bulwahn@38073
   336
fun write_program p =
bulwahn@38073
   337
  cat_lines (map write_clause p) 
bulwahn@38073
   338
bulwahn@38078
   339
(** query templates **)
bulwahn@38078
   340
bulwahn@38073
   341
fun query_first rel vnames =
bulwahn@38073
   342
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38082
   343
  "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38082
   344
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38077
   345
  
bulwahn@38077
   346
fun query_firstn n rel vnames =
bulwahn@38077
   347
  "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
bulwahn@38077
   348
    rel ^ "(" ^ space_implode ", " vnames ^ "), Sols), writelist(Sols).\n" ^
bulwahn@38077
   349
    "writelist([]).\n" ^
bulwahn@38077
   350
    "writelist([(" ^ space_implode ", " vnames ^ ")|T]) :- " ^
bulwahn@38079
   351
    "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38079
   352
    "\\n', [" ^ space_implode ", " vnames ^ "]), writelist(T).\n"
bulwahn@38077
   353
  
bulwahn@38073
   354
val prelude =
bulwahn@38073
   355
  "#!/usr/bin/swipl -q -t main -f\n\n" ^
bulwahn@38077
   356
  ":- use_module(library('dialect/ciao/aggregates')).\n" ^
bulwahn@38729
   357
  ":- style_check(-singleton).\n" ^
bulwahn@38729
   358
  ":- style_check(-discontiguous).\n" ^ 	
bulwahn@38729
   359
  ":- style_check(-atom).\n\n" ^
bulwahn@38073
   360
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   361
  "main :- halt(1).\n"
bulwahn@38075
   362
bulwahn@38075
   363
(* parsing prolog solution *)
bulwahn@38115
   364
val scan_number =
bulwahn@38115
   365
  Scan.many1 Symbol.is_ascii_digit
bulwahn@38075
   366
bulwahn@38075
   367
val scan_atom =
bulwahn@38728
   368
  Scan.many1 (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   369
bulwahn@38075
   370
val scan_var =
bulwahn@38078
   371
  Scan.many1
bulwahn@38078
   372
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   373
bulwahn@38076
   374
val scan_ident =
bulwahn@38076
   375
  Scan.repeat (Scan.one
bulwahn@38076
   376
    (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38076
   377
bulwahn@38075
   378
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   379
bulwahn@38075
   380
val string_of = concat o map (dest_Char o Symbol.decode)
bulwahn@38075
   381
bulwahn@38076
   382
val is_atom_ident = forall Symbol.is_ascii_lower
bulwahn@38076
   383
bulwahn@38076
   384
val is_var_ident =
bulwahn@38076
   385
  forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38078
   386
bulwahn@38115
   387
fun int_of_symbol_list xs = fold (fn x => fn s => s * 10 + (ord x - ord "0")) xs 0
bulwahn@38115
   388
bulwahn@38078
   389
fun scan_terms xs = (((scan_term --| $$ ",") ::: scan_terms)
bulwahn@38078
   390
  || (scan_term >> single)) xs
bulwahn@38078
   391
and scan_term xs =
bulwahn@38115
   392
  ((scan_number >> (Number o int_of_symbol_list))
bulwahn@38115
   393
  || (scan_var >> (Var o string_of))
bulwahn@38078
   394
  || ((scan_atom -- ($$ "(" |-- scan_terms --| $$ ")"))
bulwahn@38079
   395
    >> (fn (f, ts) => AppF (string_of f, ts)))
bulwahn@38078
   396
  || (scan_atom >> (Cons o string_of))) xs
bulwahn@38079
   397
bulwahn@38075
   398
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38077
   399
    (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
bulwahn@38075
   400
  o explode
bulwahn@38075
   401
  
bulwahn@38079
   402
fun parse_solutions sol =
bulwahn@38075
   403
  let
bulwahn@38077
   404
    fun dest_eq s = case space_explode "=" s of
bulwahn@38075
   405
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38078
   406
      | _ => raise Fail "unexpected equation in prolog output"
bulwahn@38079
   407
    fun parse_solution s = map dest_eq (space_explode ";" s)
bulwahn@38075
   408
  in
bulwahn@38079
   409
    map parse_solution (fst (split_last (space_explode "\n" sol)))
bulwahn@38075
   410
  end 
bulwahn@38073
   411
  
bulwahn@38073
   412
(* calling external interpreter and getting results *)
bulwahn@38073
   413
bulwahn@38077
   414
fun run p query_rel vnames nsols =
bulwahn@38073
   415
  let
bulwahn@38073
   416
    val cmd = Path.named_root
bulwahn@38077
   417
    val query = case nsols of NONE => query_first | SOME n => query_firstn n 
bulwahn@38077
   418
    val prog = prelude ^ query query_rel vnames ^ write_program p
bulwahn@38079
   419
    val _ = tracing ("Generated prolog program:\n" ^ prog)
bulwahn@38073
   420
    val prolog_file = File.tmp_path (Path.basic "prolog_file")
bulwahn@38073
   421
    val _ = File.write prolog_file prog
bulwahn@38077
   422
    val (solution, _) = bash_output ("/usr/local/bin/swipl -f " ^ File.shell_path prolog_file)
bulwahn@38079
   423
    val _ = tracing ("Prolog returned solution(s):\n" ^ solution)
bulwahn@38079
   424
    val tss = parse_solutions solution
bulwahn@38073
   425
  in
bulwahn@38079
   426
    tss
bulwahn@38073
   427
  end
bulwahn@38073
   428
bulwahn@38075
   429
(* values command *)
bulwahn@38075
   430
bulwahn@38081
   431
fun restore_term ctxt constant_table (Var s, T) = Free (s, T)
bulwahn@38115
   432
  | restore_term ctxt constant_table (Number n, @{typ "int"}) = HOLogic.mk_number @{typ "int"} n
bulwahn@38115
   433
  | restore_term ctxt constant_table (Number n, _) = raise (Fail "unexpected type for number") 
bulwahn@38079
   434
  | restore_term ctxt constant_table (Cons s, T) = Const (restore_const constant_table s, T)
bulwahn@38079
   435
  | restore_term ctxt constant_table (AppF (f, args), T) =
bulwahn@38079
   436
    let
bulwahn@38079
   437
      val thy = ProofContext.theory_of ctxt
bulwahn@38079
   438
      val c = restore_const constant_table f
bulwahn@38079
   439
      val cT = Sign.the_const_type thy c
bulwahn@38079
   440
      val (argsT, resT) = strip_type cT
bulwahn@38079
   441
      val subst = Sign.typ_match thy (resT, T) Vartab.empty
bulwahn@38079
   442
      val argsT' = map (Envir.subst_type subst) argsT
bulwahn@38079
   443
    in
bulwahn@38079
   444
      list_comb (Const (c, Envir.subst_type subst cT),
bulwahn@38079
   445
        map (restore_term ctxt constant_table) (args ~~ argsT'))
bulwahn@38079
   446
    end
bulwahn@38079
   447
bulwahn@38075
   448
fun values ctxt soln t_compr =
bulwahn@38075
   449
  let
bulwahn@38727
   450
    val options = !options
bulwahn@38075
   451
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   452
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   453
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   454
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   455
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38080
   456
    val output_frees = rev (map2 (curry Free) output_names Ts)
bulwahn@38075
   457
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   458
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   459
      case strip_comb body of
bulwahn@38075
   460
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   461
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38075
   462
    val vnames =
bulwahn@38075
   463
      case try (map (fst o dest_Free)) all_args of
bulwahn@38075
   464
        SOME vs => vs
bulwahn@38075
   465
      | NONE => error ("Not only free variables in " ^ commas (map (Syntax.string_of_term ctxt) all_args))
bulwahn@38732
   466
    val _ = tracing "Preprocessing specification..."
bulwahn@38732
   467
    val T = Sign.the_const_type (ProofContext.theory_of ctxt) name
bulwahn@38732
   468
    val t = Const (name, T)
bulwahn@38732
   469
    val ctxt' = ProofContext.theory (Context.copy_thy) ctxt
bulwahn@38732
   470
    val thy' = Predicate_Compile.preprocess preprocess_options t (ProofContext.theory_of ctxt')
bulwahn@38732
   471
    val ctxt'' = ProofContext.init_global thy'
bulwahn@38079
   472
    val _ = tracing "Generating prolog program..."
bulwahn@38732
   473
    val (p, constant_table) = generate options ctxt'' name
bulwahn@38732
   474
      |> (if #ensure_groundness options then add_ground_predicates ctxt'' else I)
bulwahn@38079
   475
    val _ = tracing "Running prolog program..."
bulwahn@38079
   476
    val tss = run p (translate_const constant_table name) (map first_upper vnames) soln
bulwahn@38079
   477
    val _ = tracing "Restoring terms..."
bulwahn@38115
   478
    val empty = Const("Orderings.bot_class.bot", fastype_of t_compr)
bulwahn@38115
   479
    fun mk_insert x S =
bulwahn@38115
   480
      Const (@{const_name "Set.insert"}, fastype_of x --> fastype_of S --> fastype_of S) $ x $ S 
bulwahn@38115
   481
    fun mk_set_compr in_insert [] xs =
bulwahn@38115
   482
       rev ((Free ("...", fastype_of t_compr)) ::
bulwahn@38115
   483
        (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))
bulwahn@38115
   484
      | mk_set_compr in_insert (t :: ts) xs =
bulwahn@38115
   485
        let
bulwahn@38115
   486
          val frees = Term.add_frees t []
bulwahn@38115
   487
        in
bulwahn@38115
   488
          if null frees then
bulwahn@38115
   489
            mk_set_compr (t :: in_insert) ts xs
bulwahn@38115
   490
          else
bulwahn@38115
   491
            let
bulwahn@38732
   492
              val uu as (uuN, uuT) = singleton (Variable.variant_frees ctxt'' [t]) ("uu", fastype_of t)
bulwahn@38115
   493
              val set_compr =
bulwahn@38115
   494
                HOLogic.mk_Collect (uuN, uuT, fold (fn (s, T) => fn t => HOLogic.mk_exists (s, T, t))
bulwahn@38115
   495
                  frees (HOLogic.mk_conj (HOLogic.mk_eq (Free uu, t), @{term "True"})))
bulwahn@38115
   496
            in
bulwahn@38729
   497
              mk_set_compr [] ts
bulwahn@38729
   498
                (set_compr :: (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))  
bulwahn@38115
   499
            end
bulwahn@38115
   500
        end
bulwahn@38075
   501
  in
bulwahn@38115
   502
      foldl1 (HOLogic.mk_binop @{const_name sup}) (mk_set_compr []
bulwahn@38732
   503
        (map (fn ts => HOLogic.mk_tuple (map (restore_term ctxt'' constant_table) (ts ~~ Ts))) tss) [])
bulwahn@38075
   504
  end
bulwahn@38075
   505
bulwahn@38075
   506
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   507
  let
bulwahn@38075
   508
    val ctxt = Toplevel.context_of state
bulwahn@38075
   509
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   510
    val t' = values ctxt soln t
bulwahn@38075
   511
    val ty' = Term.type_of t'
bulwahn@38075
   512
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38115
   513
    val _ = tracing "Printing terms..."
bulwahn@38075
   514
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   515
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   516
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   517
  in Pretty.writeln p end;
bulwahn@38075
   518
bulwahn@38075
   519
bulwahn@38075
   520
(* renewing the values command for Prolog queries *)
bulwahn@38075
   521
bulwahn@38075
   522
val opt_print_modes =
bulwahn@38075
   523
  Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
bulwahn@38075
   524
bulwahn@38075
   525
val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
bulwahn@38077
   526
  (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
bulwahn@38075
   527
   >> (fn ((print_modes, soln), t) => Toplevel.keep
haftmann@38504
   528
        (values_cmd print_modes soln t))); (*FIXME does not preserve the previous functionality*)
bulwahn@38075
   529
bulwahn@38733
   530
(* quickcheck generator *)
bulwahn@38733
   531
bulwahn@38733
   532
(* FIXME: large copy of Predicate_Compile_Quickcheck - refactor out commons *)
bulwahn@38733
   533
bulwahn@38733
   534
fun strip_imp_prems (Const(@{const_name "op -->"}, _) $ A $ B) = A :: strip_imp_prems B
bulwahn@38733
   535
  | strip_imp_prems _ = [];
bulwahn@38733
   536
bulwahn@38733
   537
fun strip_imp_concl (Const(@{const_name "op -->"}, _) $ A $ B) = strip_imp_concl B
bulwahn@38733
   538
  | strip_imp_concl A = A : term;
bulwahn@38733
   539
bulwahn@38733
   540
fun strip_horn A = (strip_imp_prems A, strip_imp_concl A);
bulwahn@38733
   541
bulwahn@38733
   542
fun quickcheck ctxt report t size =
bulwahn@38733
   543
  let
bulwahn@38733
   544
    val ctxt' = ProofContext.theory (Context.copy_thy) ctxt
bulwahn@38733
   545
    val thy = (ProofContext.theory_of ctxt')
bulwahn@38733
   546
    val (vs, t') = strip_abs t
bulwahn@38733
   547
    val vs' = Variable.variant_frees ctxt' [] vs
bulwahn@38733
   548
    val Ts = map snd vs'
bulwahn@38733
   549
    val t'' = subst_bounds (map Free (rev vs'), t')
bulwahn@38733
   550
    val (prems, concl) = strip_horn t''
bulwahn@38733
   551
    val constname = "quickcheck"
bulwahn@38733
   552
    val full_constname = Sign.full_bname thy constname
bulwahn@38733
   553
    val constT = Ts ---> @{typ bool}
bulwahn@38733
   554
    val thy1 = Sign.add_consts_i [(Binding.name constname, constT, NoSyn)] thy
bulwahn@38733
   555
    val const = Const (full_constname, constT)
bulwahn@38733
   556
    val t = Logic.list_implies
bulwahn@38733
   557
      (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
bulwahn@38733
   558
       HOLogic.mk_Trueprop (list_comb (Const (full_constname, constT), map Free vs')))
bulwahn@38733
   559
    val tac = fn _ => Skip_Proof.cheat_tac thy1
bulwahn@38733
   560
    val intro = Goal.prove (ProofContext.init_global thy1) (map fst vs') [] t tac
bulwahn@38733
   561
    val thy2 = Context.theory_map (Predicate_Compile_Alternative_Defs.add_thm intro) thy1
bulwahn@38733
   562
    val thy3 = Predicate_Compile.preprocess preprocess_options const thy2
bulwahn@38733
   563
    val ctxt'' = ProofContext.init_global thy3
bulwahn@38733
   564
    val _ = tracing "Generating prolog program..."
bulwahn@38733
   565
    val (p, constant_table) = generate {ensure_groundness = true} ctxt'' full_constname
bulwahn@38733
   566
      |> add_ground_predicates ctxt''
bulwahn@38733
   567
    val _ = tracing "Running prolog program..."
bulwahn@38733
   568
    val [ts] = run p (translate_const constant_table full_constname) (map (first_upper o fst) vs')
bulwahn@38733
   569
      (SOME 1)
bulwahn@38733
   570
    val _ = tracing "Restoring terms..."
bulwahn@38733
   571
    val res = SOME (map (restore_term ctxt'' constant_table) (ts ~~ Ts))
bulwahn@38733
   572
    val empty_report = ([], false)
bulwahn@38733
   573
  in
bulwahn@38733
   574
    (res, empty_report)
bulwahn@38733
   575
  end; 
bulwahn@38732
   576
bulwahn@38073
   577
end;