src/HOL/Tools/Predicate_Compile/code_prolog.ML
author bulwahn
Thu Jul 29 17:27:56 2010 +0200 (2010-07-29)
changeset 38077 46ff55ace18c
parent 38076 2a9c14d9d2ef
child 38078 2afb5f710b84
permissions -rw-r--r--
querying for multiple solutions in values command for prolog execution
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@38073
     9
  datatype term = Var of string * typ | Cons of string | AppF of string * term list;
bulwahn@38073
    10
  datatype prem = Conj of prem list | NotRel of string * term list | Rel of string * term list | Eq of term * term | NotEq of term * term;
bulwahn@38073
    11
  type clause = ((string * term list) * prem);
bulwahn@38073
    12
  type logic_program = clause list;
bulwahn@38073
    13
bulwahn@38073
    14
  val generate : Proof.context -> string list -> logic_program
bulwahn@38073
    15
  val write_program : logic_program -> string
bulwahn@38077
    16
  val run : logic_program -> string -> string list -> int option -> term list
bulwahn@38073
    17
bulwahn@38073
    18
end;
bulwahn@38073
    19
bulwahn@38073
    20
structure Code_Prolog : CODE_PROLOG =
bulwahn@38073
    21
struct
bulwahn@38073
    22
bulwahn@38073
    23
(* general string functions *)
bulwahn@38073
    24
bulwahn@38073
    25
val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
bulwahn@38073
    26
val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
bulwahn@38073
    27
bulwahn@38073
    28
(* internal program representation *)
bulwahn@38073
    29
bulwahn@38073
    30
datatype term = Var of string * typ | Cons of string | AppF of string * term list;
bulwahn@38073
    31
bulwahn@38075
    32
fun string_of_prol_term (Var (s, T)) = "Var " ^ s
bulwahn@38075
    33
  | string_of_prol_term (Cons s) = "Cons " ^ s
bulwahn@38075
    34
  | string_of_prol_term (AppF (f, args)) = f ^ "(" ^ commas (map string_of_prol_term args) ^ ")" 
bulwahn@38075
    35
bulwahn@38073
    36
datatype prem = Conj of prem list | NotRel of string * term list | Rel of string * term list | Eq of term * term | NotEq of term * term;
bulwahn@38073
    37
bulwahn@38073
    38
fun dest_Rel (Rel (c, ts)) = (c, ts)
bulwahn@38073
    39
 
bulwahn@38073
    40
type clause = ((string * term list) * prem);
bulwahn@38073
    41
bulwahn@38073
    42
type logic_program = clause list;
bulwahn@38073
    43
bulwahn@38073
    44
(* translation from introduction rules to internal representation *)
bulwahn@38073
    45
bulwahn@38073
    46
(* assuming no clashing *)
bulwahn@38073
    47
fun translate_const c = Long_Name.base_name c
bulwahn@38073
    48
bulwahn@38073
    49
fun translate_term ctxt t =
bulwahn@38073
    50
  case strip_comb t of
bulwahn@38073
    51
    (Free (v, T), []) => Var (v, T) 
bulwahn@38073
    52
  | (Const (c, _), []) => Cons (translate_const c)
bulwahn@38073
    53
  | (Const (c, _), args) => AppF (translate_const c, map (translate_term ctxt) args)
bulwahn@38073
    54
  | _ => error ("illegal term for translation: " ^ Syntax.string_of_term ctxt t)
bulwahn@38073
    55
bulwahn@38073
    56
bulwahn@38073
    57
fun translate_literal ctxt t =
bulwahn@38073
    58
  case strip_comb t of
bulwahn@38073
    59
    (Const (@{const_name "op ="}, _), [l, r]) => Eq (pairself (translate_term ctxt) (l, r))
bulwahn@38073
    60
  | (Const (c, _), args) => Rel (translate_const c, map (translate_term ctxt) args)
bulwahn@38073
    61
  | _ => error ("illegal literal for translation: " ^ Syntax.string_of_term ctxt t)
bulwahn@38073
    62
bulwahn@38073
    63
fun NegRel_of (Rel lit) = NotRel lit
bulwahn@38073
    64
  | NegRel_of (Eq eq) = NotEq eq
bulwahn@38073
    65
  
bulwahn@38073
    66
fun translate_prem ctxt t =  
bulwahn@38073
    67
    case try HOLogic.dest_not t of
bulwahn@38073
    68
      SOME t => NegRel_of (translate_literal ctxt t)
bulwahn@38073
    69
    | NONE => translate_literal ctxt t
bulwahn@38073
    70
bulwahn@38073
    71
fun translate_intros ctxt gr const =
bulwahn@38073
    72
  let
bulwahn@38073
    73
    val intros = Graph.get_node gr const
bulwahn@38073
    74
    val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
bulwahn@38073
    75
    fun translate_intro intro =
bulwahn@38073
    76
      let
bulwahn@38073
    77
        val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
bulwahn@38073
    78
        val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro) 
bulwahn@38073
    79
        val prems' = Conj (map (translate_prem ctxt') prems)
bulwahn@38073
    80
        val clause = (dest_Rel (translate_literal ctxt' head), prems')
bulwahn@38073
    81
      in clause end
bulwahn@38073
    82
  in map translate_intro intros' end
bulwahn@38073
    83
bulwahn@38073
    84
fun generate ctxt const =
bulwahn@38073
    85
  let 
bulwahn@38073
    86
     fun strong_conn_of gr keys =
bulwahn@38073
    87
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@38073
    88
    val gr = Predicate_Compile_Core.intros_graph_of ctxt
bulwahn@38073
    89
    val scc = strong_conn_of gr const
bulwahn@38073
    90
  in
bulwahn@38073
    91
    maps (translate_intros ctxt gr) (flat scc)
bulwahn@38073
    92
  end
bulwahn@38073
    93
bulwahn@38073
    94
(* transform logic program *)
bulwahn@38073
    95
bulwahn@38073
    96
(** ensure groundness of terms before negation **)
bulwahn@38073
    97
bulwahn@38073
    98
fun add_vars (Var x) vs = insert (op =) x vs
bulwahn@38073
    99
  | add_vars (Cons c) vs = vs
bulwahn@38073
   100
  | add_vars (AppF (f, args)) vs = fold add_vars args vs
bulwahn@38073
   101
bulwahn@38073
   102
fun string_of_typ (Type (s, Ts)) = Long_Name.base_name s
bulwahn@38073
   103
bulwahn@38073
   104
fun mk_groundness_prems ts =
bulwahn@38073
   105
  let
bulwahn@38073
   106
    val vars = fold add_vars ts []
bulwahn@38073
   107
    fun mk_ground (v, T) =
bulwahn@38073
   108
      Rel ("ground_" ^ string_of_typ T, [Var (v, T)])
bulwahn@38073
   109
  in
bulwahn@38073
   110
    map mk_ground vars
bulwahn@38073
   111
  end
bulwahn@38073
   112
bulwahn@38073
   113
fun ensure_groundness_prem (NotRel (c, ts)) = Conj (mk_groundness_prems ts @ [NotRel (c, ts)]) 
bulwahn@38073
   114
  | ensure_groundness_prem (NotEq (l, r)) = Conj (mk_groundness_prems [l, r] @ [NotEq (l, r)])
bulwahn@38073
   115
  | ensure_groundness_prem (Conj ps) = Conj (map ensure_groundness_prem ps)
bulwahn@38073
   116
  | ensure_groundness_prem p = p
bulwahn@38073
   117
bulwahn@38073
   118
fun ensure_groundness_before_negation p =
bulwahn@38073
   119
  map (apsnd ensure_groundness_prem) p
bulwahn@38073
   120
bulwahn@38073
   121
(* code printer *)
bulwahn@38073
   122
bulwahn@38073
   123
fun write_term (Var (v, _)) = first_upper v
bulwahn@38073
   124
  | write_term (Cons c) = first_lower c
bulwahn@38073
   125
  | write_term (AppF (f, args)) = first_lower f ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   126
bulwahn@38073
   127
fun write_rel (pred, args) =
bulwahn@38073
   128
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   129
bulwahn@38073
   130
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   131
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   132
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   133
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   134
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38073
   135
bulwahn@38073
   136
fun write_clause (head, prem) =
bulwahn@38073
   137
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   138
bulwahn@38073
   139
fun write_program p =
bulwahn@38073
   140
  cat_lines (map write_clause p) 
bulwahn@38073
   141
bulwahn@38073
   142
fun query_first rel vnames =
bulwahn@38073
   143
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38073
   144
  "writef('" ^ implode (map (fn v => v ^ " = %w\\n") vnames) ^"', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38077
   145
  
bulwahn@38077
   146
fun query_firstn n rel vnames =
bulwahn@38077
   147
  "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
bulwahn@38077
   148
    rel ^ "(" ^ space_implode ", " vnames ^ "), Sols), writelist(Sols).\n" ^
bulwahn@38077
   149
    "writelist([]).\n" ^
bulwahn@38077
   150
    "writelist([(" ^ space_implode ", " vnames ^ ")|T]) :- " ^
bulwahn@38077
   151
    "writef('" ^ implode (map (fn v => v ^ " = %w\\n") vnames) ^
bulwahn@38077
   152
    "', [" ^ space_implode ", " vnames ^ "]), writelist(T).\n"
bulwahn@38077
   153
  
bulwahn@38073
   154
val prelude =
bulwahn@38073
   155
  "#!/usr/bin/swipl -q -t main -f\n\n" ^
bulwahn@38077
   156
  ":- use_module(library('dialect/ciao/aggregates')).\n" ^
bulwahn@38073
   157
  ":- style_check(-singleton).\n\n" ^
bulwahn@38073
   158
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   159
  "main :- halt(1).\n"
bulwahn@38075
   160
bulwahn@38075
   161
(* parsing prolog solution *)
bulwahn@38075
   162
bulwahn@38075
   163
val scan_atom =
bulwahn@38075
   164
  Scan.repeat (Scan.one (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_quasi s))
bulwahn@38075
   165
bulwahn@38075
   166
val scan_var =
bulwahn@38075
   167
  Scan.repeat (Scan.one
bulwahn@38075
   168
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38075
   169
bulwahn@38076
   170
val scan_ident =
bulwahn@38076
   171
  Scan.repeat (Scan.one
bulwahn@38076
   172
    (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38076
   173
bulwahn@38075
   174
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   175
bulwahn@38075
   176
val string_of = concat o map (dest_Char o Symbol.decode)
bulwahn@38075
   177
bulwahn@38076
   178
val is_atom_ident = forall Symbol.is_ascii_lower
bulwahn@38076
   179
bulwahn@38076
   180
val is_var_ident =
bulwahn@38076
   181
  forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38076
   182
bulwahn@38075
   183
val scan_term =
bulwahn@38076
   184
  scan_ident >> (fn s => 
bulwahn@38076
   185
    if is_var_ident s then (Var (string_of s, dummyT))
bulwahn@38077
   186
    else if is_atom_ident s then
bulwahn@38077
   187
    else   Cons (string_of s)
bulwahn@38076
   188
    else raise Fail "unexpected")
bulwahn@38076
   189
    
bulwahn@38075
   190
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38077
   191
    (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
bulwahn@38075
   192
  o explode
bulwahn@38075
   193
  
bulwahn@38075
   194
fun parse_solution sol =
bulwahn@38075
   195
  let
bulwahn@38077
   196
    fun dest_eq s = case space_explode "=" s of
bulwahn@38075
   197
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38075
   198
      | _ => raise Fail "unexpected equation in prolog output")
bulwahn@38075
   199
  in
bulwahn@38075
   200
    map dest_eq (fst (split_last (space_explode "\n" sol)))
bulwahn@38075
   201
  end 
bulwahn@38073
   202
  
bulwahn@38073
   203
(* calling external interpreter and getting results *)
bulwahn@38073
   204
bulwahn@38077
   205
fun run p query_rel vnames nsols =
bulwahn@38073
   206
  let
bulwahn@38073
   207
    val cmd = Path.named_root
bulwahn@38077
   208
    val query = case nsols of NONE => query_first | SOME n => query_firstn n 
bulwahn@38077
   209
    val prog = prelude ^ query query_rel vnames ^ write_program p
bulwahn@38073
   210
    val prolog_file = File.tmp_path (Path.basic "prolog_file")
bulwahn@38073
   211
    val _ = File.write prolog_file prog
bulwahn@38077
   212
    val (solution, _) = bash_output ("/usr/local/bin/swipl -f " ^ File.shell_path prolog_file)
bulwahn@38075
   213
    val ts = parse_solution solution
bulwahn@38073
   214
  in
bulwahn@38075
   215
    ts
bulwahn@38073
   216
  end
bulwahn@38073
   217
bulwahn@38075
   218
(* values command *)
bulwahn@38075
   219
bulwahn@38075
   220
fun mk_term (Var (s, T)) = Free (s, T)
bulwahn@38075
   221
  | mk_term (Cons s) = Const (s, dummyT)
bulwahn@38075
   222
  | mk_term (AppF (f, args)) = list_comb (Const (f, dummyT), map mk_term args)
bulwahn@38075
   223
  
bulwahn@38075
   224
fun values ctxt soln t_compr =
bulwahn@38075
   225
  let
bulwahn@38075
   226
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   227
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   228
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   229
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   230
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38075
   231
    val output_frees = map2 (curry Free) output_names (rev Ts)
bulwahn@38075
   232
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   233
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   234
      case strip_comb body of
bulwahn@38075
   235
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   236
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38075
   237
    val vnames =
bulwahn@38075
   238
      case try (map (fst o dest_Free)) all_args of
bulwahn@38075
   239
        SOME vs => vs
bulwahn@38075
   240
      | NONE => error ("Not only free variables in " ^ commas (map (Syntax.string_of_term ctxt) all_args))
bulwahn@38077
   241
    val ts = run (generate ctxt [name]) (translate_const name) (map first_upper vnames) soln
bulwahn@38075
   242
  in
bulwahn@38075
   243
    HOLogic.mk_tuple (map mk_term ts)
bulwahn@38075
   244
  end
bulwahn@38075
   245
bulwahn@38075
   246
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   247
  let
bulwahn@38075
   248
    val ctxt = Toplevel.context_of state
bulwahn@38075
   249
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   250
    val t' = values ctxt soln t
bulwahn@38075
   251
    val ty' = Term.type_of t'
bulwahn@38075
   252
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38075
   253
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   254
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   255
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   256
  in Pretty.writeln p end;
bulwahn@38075
   257
bulwahn@38075
   258
bulwahn@38075
   259
(* renewing the values command for Prolog queries *)
bulwahn@38075
   260
bulwahn@38075
   261
val opt_print_modes =
bulwahn@38075
   262
  Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
bulwahn@38075
   263
bulwahn@38075
   264
val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
bulwahn@38077
   265
  (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
bulwahn@38075
   266
   >> (fn ((print_modes, soln), t) => Toplevel.keep
bulwahn@38075
   267
        (values_cmd print_modes soln t)));
bulwahn@38075
   268
bulwahn@38073
   269
end;