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