src/HOL/Tools/Predicate_Compile/code_prolog.ML
author bulwahn
Sun Aug 01 10:15:43 2010 +0200 (2010-08-01)
changeset 38113 81f08bbb3be7
parent 38112 cf08f4780938
child 38114 0f06e3cc04a6
permissions -rw-r--r--
adding basic arithmetic support for prolog code generation
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@38079
   142
fun translate_intros ctxt gr const constant_table =
bulwahn@38073
   143
  let
bulwahn@38073
   144
    val intros = Graph.get_node gr const
bulwahn@38073
   145
    val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
bulwahn@38079
   146
    val constant_table' = declare_consts (fold Term.add_const_names intros' []) constant_table
bulwahn@38073
   147
    fun translate_intro intro =
bulwahn@38073
   148
      let
bulwahn@38073
   149
        val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
bulwahn@38073
   150
        val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro) 
bulwahn@38079
   151
        val prems' = Conj (map (translate_prem ctxt' constant_table') prems)
bulwahn@38079
   152
        val clause = (dest_Rel (translate_literal ctxt' constant_table' head), prems')
bulwahn@38073
   153
      in clause end
bulwahn@38079
   154
  in (map translate_intro intros', constant_table') end
bulwahn@38073
   155
bulwahn@38073
   156
fun generate ctxt const =
bulwahn@38073
   157
  let 
bulwahn@38073
   158
     fun strong_conn_of gr keys =
bulwahn@38073
   159
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@38073
   160
    val gr = Predicate_Compile_Core.intros_graph_of ctxt
bulwahn@38073
   161
    val scc = strong_conn_of gr const
bulwahn@38079
   162
    val constant_table = mk_constant_table (flat scc)
bulwahn@38073
   163
  in
bulwahn@38079
   164
    apfst flat (fold_map (translate_intros ctxt gr) (flat scc) constant_table)
bulwahn@38073
   165
  end
bulwahn@38073
   166
bulwahn@38073
   167
(* transform logic program *)
bulwahn@38073
   168
bulwahn@38073
   169
(** ensure groundness of terms before negation **)
bulwahn@38073
   170
bulwahn@38073
   171
fun add_vars (Var x) vs = insert (op =) x vs
bulwahn@38073
   172
  | add_vars (Cons c) vs = vs
bulwahn@38073
   173
  | add_vars (AppF (f, args)) vs = fold add_vars args vs
bulwahn@38073
   174
bulwahn@38073
   175
fun string_of_typ (Type (s, Ts)) = Long_Name.base_name s
bulwahn@38073
   176
bulwahn@38073
   177
fun mk_groundness_prems ts =
bulwahn@38073
   178
  let
bulwahn@38073
   179
    val vars = fold add_vars ts []
bulwahn@38081
   180
    fun mk_ground v =
bulwahn@38081
   181
      Rel ("ground", [Var v])
bulwahn@38073
   182
  in
bulwahn@38073
   183
    map mk_ground vars
bulwahn@38073
   184
  end
bulwahn@38073
   185
bulwahn@38073
   186
fun ensure_groundness_prem (NotRel (c, ts)) = Conj (mk_groundness_prems ts @ [NotRel (c, ts)]) 
bulwahn@38073
   187
  | ensure_groundness_prem (NotEq (l, r)) = Conj (mk_groundness_prems [l, r] @ [NotEq (l, r)])
bulwahn@38073
   188
  | ensure_groundness_prem (Conj ps) = Conj (map ensure_groundness_prem ps)
bulwahn@38073
   189
  | ensure_groundness_prem p = p
bulwahn@38073
   190
bulwahn@38073
   191
fun ensure_groundness_before_negation p =
bulwahn@38073
   192
  map (apsnd ensure_groundness_prem) p
bulwahn@38073
   193
bulwahn@38073
   194
(* code printer *)
bulwahn@38073
   195
bulwahn@38113
   196
fun write_arith_op Plus = "+"
bulwahn@38113
   197
  | write_arith_op Minus = "-"
bulwahn@38113
   198
bulwahn@38081
   199
fun write_term (Var v) = first_upper v
bulwahn@38079
   200
  | write_term (Cons c) = c
bulwahn@38113
   201
  | write_term (AppF (f, args)) = f ^ "(" ^ space_implode ", " (map write_term args) ^ ")"
bulwahn@38113
   202
  | write_term (ArithOp (oper, [a1, a2])) = write_term a1 ^ " " ^ write_arith_op oper ^ " " ^ write_term a2
bulwahn@38112
   203
  | write_term (Number n) = string_of_int n
bulwahn@38073
   204
bulwahn@38073
   205
fun write_rel (pred, args) =
bulwahn@38073
   206
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   207
bulwahn@38073
   208
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   209
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   210
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   211
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   212
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38113
   213
  | write_prem (ArithEq (l, r)) = write_term l ^ " is " ^ write_term r
bulwahn@38113
   214
  | write_prem (NotArithEq (l, r)) = write_term l ^ " =\\= " ^ write_term r
bulwahn@38073
   215
bulwahn@38073
   216
fun write_clause (head, prem) =
bulwahn@38073
   217
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   218
bulwahn@38073
   219
fun write_program p =
bulwahn@38073
   220
  cat_lines (map write_clause p) 
bulwahn@38073
   221
bulwahn@38078
   222
(** query templates **)
bulwahn@38078
   223
bulwahn@38073
   224
fun query_first rel vnames =
bulwahn@38073
   225
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38082
   226
  "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38082
   227
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38077
   228
  
bulwahn@38077
   229
fun query_firstn n rel vnames =
bulwahn@38077
   230
  "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
bulwahn@38077
   231
    rel ^ "(" ^ space_implode ", " vnames ^ "), Sols), writelist(Sols).\n" ^
bulwahn@38077
   232
    "writelist([]).\n" ^
bulwahn@38077
   233
    "writelist([(" ^ space_implode ", " vnames ^ ")|T]) :- " ^
bulwahn@38079
   234
    "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38079
   235
    "\\n', [" ^ space_implode ", " vnames ^ "]), writelist(T).\n"
bulwahn@38077
   236
  
bulwahn@38073
   237
val prelude =
bulwahn@38073
   238
  "#!/usr/bin/swipl -q -t main -f\n\n" ^
bulwahn@38077
   239
  ":- use_module(library('dialect/ciao/aggregates')).\n" ^
bulwahn@38073
   240
  ":- style_check(-singleton).\n\n" ^
bulwahn@38073
   241
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   242
  "main :- halt(1).\n"
bulwahn@38075
   243
bulwahn@38075
   244
(* parsing prolog solution *)
bulwahn@38075
   245
bulwahn@38075
   246
val scan_atom =
bulwahn@38078
   247
  Scan.many1 (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   248
bulwahn@38075
   249
val scan_var =
bulwahn@38078
   250
  Scan.many1
bulwahn@38078
   251
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   252
bulwahn@38076
   253
val scan_ident =
bulwahn@38076
   254
  Scan.repeat (Scan.one
bulwahn@38076
   255
    (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38076
   256
bulwahn@38075
   257
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   258
bulwahn@38075
   259
val string_of = concat o map (dest_Char o Symbol.decode)
bulwahn@38075
   260
bulwahn@38076
   261
val is_atom_ident = forall Symbol.is_ascii_lower
bulwahn@38076
   262
bulwahn@38076
   263
val is_var_ident =
bulwahn@38076
   264
  forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38078
   265
bulwahn@38078
   266
fun scan_terms xs = (((scan_term --| $$ ",") ::: scan_terms)
bulwahn@38078
   267
  || (scan_term >> single)) xs
bulwahn@38078
   268
and scan_term xs =
bulwahn@38081
   269
  ((scan_var >> (Var o string_of))
bulwahn@38078
   270
  || ((scan_atom -- ($$ "(" |-- scan_terms --| $$ ")"))
bulwahn@38079
   271
    >> (fn (f, ts) => AppF (string_of f, ts)))
bulwahn@38078
   272
  || (scan_atom >> (Cons o string_of))) xs
bulwahn@38079
   273
bulwahn@38075
   274
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38077
   275
    (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
bulwahn@38075
   276
  o explode
bulwahn@38075
   277
  
bulwahn@38079
   278
fun parse_solutions sol =
bulwahn@38075
   279
  let
bulwahn@38077
   280
    fun dest_eq s = case space_explode "=" s of
bulwahn@38075
   281
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38078
   282
      | _ => raise Fail "unexpected equation in prolog output"
bulwahn@38079
   283
    fun parse_solution s = map dest_eq (space_explode ";" s)
bulwahn@38075
   284
  in
bulwahn@38079
   285
    map parse_solution (fst (split_last (space_explode "\n" sol)))
bulwahn@38075
   286
  end 
bulwahn@38073
   287
  
bulwahn@38073
   288
(* calling external interpreter and getting results *)
bulwahn@38073
   289
bulwahn@38077
   290
fun run p query_rel vnames nsols =
bulwahn@38073
   291
  let
bulwahn@38073
   292
    val cmd = Path.named_root
bulwahn@38077
   293
    val query = case nsols of NONE => query_first | SOME n => query_firstn n 
bulwahn@38077
   294
    val prog = prelude ^ query query_rel vnames ^ write_program p
bulwahn@38079
   295
    val _ = tracing ("Generated prolog program:\n" ^ prog)
bulwahn@38073
   296
    val prolog_file = File.tmp_path (Path.basic "prolog_file")
bulwahn@38073
   297
    val _ = File.write prolog_file prog
bulwahn@38077
   298
    val (solution, _) = bash_output ("/usr/local/bin/swipl -f " ^ File.shell_path prolog_file)
bulwahn@38079
   299
    val _ = tracing ("Prolog returned solution(s):\n" ^ solution)
bulwahn@38079
   300
    val tss = parse_solutions solution
bulwahn@38073
   301
  in
bulwahn@38079
   302
    tss
bulwahn@38073
   303
  end
bulwahn@38073
   304
bulwahn@38075
   305
(* values command *)
bulwahn@38075
   306
bulwahn@38081
   307
fun restore_term ctxt constant_table (Var s, T) = Free (s, T)
bulwahn@38079
   308
  | restore_term ctxt constant_table (Cons s, T) = Const (restore_const constant_table s, T)
bulwahn@38079
   309
  | restore_term ctxt constant_table (AppF (f, args), T) =
bulwahn@38079
   310
    let
bulwahn@38079
   311
      val thy = ProofContext.theory_of ctxt
bulwahn@38079
   312
      val c = restore_const constant_table f
bulwahn@38079
   313
      val cT = Sign.the_const_type thy c
bulwahn@38079
   314
      val (argsT, resT) = strip_type cT
bulwahn@38079
   315
      val subst = Sign.typ_match thy (resT, T) Vartab.empty
bulwahn@38079
   316
      val argsT' = map (Envir.subst_type subst) argsT
bulwahn@38079
   317
    in
bulwahn@38079
   318
      list_comb (Const (c, Envir.subst_type subst cT),
bulwahn@38079
   319
        map (restore_term ctxt constant_table) (args ~~ argsT'))
bulwahn@38079
   320
    end
bulwahn@38079
   321
bulwahn@38075
   322
fun values ctxt soln t_compr =
bulwahn@38075
   323
  let
bulwahn@38075
   324
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   325
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   326
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   327
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   328
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38080
   329
    val output_frees = rev (map2 (curry Free) output_names Ts)
bulwahn@38075
   330
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   331
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   332
      case strip_comb body of
bulwahn@38075
   333
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   334
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38075
   335
    val vnames =
bulwahn@38075
   336
      case try (map (fst o dest_Free)) all_args of
bulwahn@38075
   337
        SOME vs => vs
bulwahn@38075
   338
      | NONE => error ("Not only free variables in " ^ commas (map (Syntax.string_of_term ctxt) all_args))
bulwahn@38079
   339
    val _ = tracing "Generating prolog program..."
bulwahn@38079
   340
    val (p, constant_table) = generate ctxt [name]
bulwahn@38079
   341
    val _ = tracing "Running prolog program..."
bulwahn@38079
   342
    val tss = run p (translate_const constant_table name) (map first_upper vnames) soln
bulwahn@38079
   343
    val _ = tracing "Restoring terms..."
bulwahn@38079
   344
    fun mk_set_comprehension t =
bulwahn@38079
   345
      let
bulwahn@38079
   346
        val frees = Term.add_frees t []
bulwahn@38079
   347
        val uu as (uuN, uuT) = singleton (Variable.variant_frees ctxt [t]) ("uu", fastype_of t)
bulwahn@38079
   348
      in HOLogic.mk_Collect (uuN, uuT, fold (fn (s, T) => fn t => HOLogic.mk_exists (s, T, t))
bulwahn@38079
   349
        frees (HOLogic.mk_conj (HOLogic.mk_eq (Free uu, t), @{term "True"}))) end
bulwahn@38079
   350
    val set_comprs = map (fn ts =>
bulwahn@38079
   351
      mk_set_comprehension (HOLogic.mk_tuple (map (restore_term ctxt constant_table) (ts ~~ Ts)))) tss
bulwahn@38075
   352
  in
bulwahn@38079
   353
    foldl1 (HOLogic.mk_binop @{const_name sup}) (set_comprs @ [Free ("...", fastype_of t_compr)])
bulwahn@38075
   354
  end
bulwahn@38075
   355
bulwahn@38075
   356
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   357
  let
bulwahn@38075
   358
    val ctxt = Toplevel.context_of state
bulwahn@38075
   359
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   360
    val t' = values ctxt soln t
bulwahn@38075
   361
    val ty' = Term.type_of t'
bulwahn@38075
   362
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38075
   363
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   364
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   365
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   366
  in Pretty.writeln p end;
bulwahn@38075
   367
bulwahn@38075
   368
bulwahn@38075
   369
(* renewing the values command for Prolog queries *)
bulwahn@38075
   370
bulwahn@38075
   371
val opt_print_modes =
bulwahn@38075
   372
  Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
bulwahn@38075
   373
bulwahn@38075
   374
val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
bulwahn@38077
   375
  (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
bulwahn@38075
   376
   >> (fn ((print_modes, soln), t) => Toplevel.keep
bulwahn@38075
   377
        (values_cmd print_modes soln t)));
bulwahn@38075
   378
bulwahn@38073
   379
end;