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