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