src/HOL/Tools/Predicate_Compile/code_prolog.ML
author bulwahn
Thu Jul 29 17:27:55 2010 +0200 (2010-07-29)
changeset 38075 3d5e2b7d1374
parent 38073 64062d56ad3c
child 38076 2a9c14d9d2ef
permissions -rw-r--r--
adding values command and parsing prolog output
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@38075
    16
  val run : logic_program -> string -> string list -> 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
    val _ = tracing (commas (flat scc))
bulwahn@38073
    91
  in
bulwahn@38073
    92
    maps (translate_intros ctxt gr) (flat scc)
bulwahn@38073
    93
  end
bulwahn@38073
    94
bulwahn@38073
    95
(* transform logic program *)
bulwahn@38073
    96
bulwahn@38073
    97
(** ensure groundness of terms before negation **)
bulwahn@38073
    98
bulwahn@38073
    99
fun add_vars (Var x) vs = insert (op =) x vs
bulwahn@38073
   100
  | add_vars (Cons c) vs = vs
bulwahn@38073
   101
  | add_vars (AppF (f, args)) vs = fold add_vars args vs
bulwahn@38073
   102
bulwahn@38073
   103
fun string_of_typ (Type (s, Ts)) = Long_Name.base_name s
bulwahn@38073
   104
bulwahn@38073
   105
fun mk_groundness_prems ts =
bulwahn@38073
   106
  let
bulwahn@38073
   107
    val vars = fold add_vars ts []
bulwahn@38073
   108
    fun mk_ground (v, T) =
bulwahn@38073
   109
      Rel ("ground_" ^ string_of_typ T, [Var (v, T)])
bulwahn@38073
   110
  in
bulwahn@38073
   111
    map mk_ground vars
bulwahn@38073
   112
  end
bulwahn@38073
   113
bulwahn@38073
   114
fun ensure_groundness_prem (NotRel (c, ts)) = Conj (mk_groundness_prems ts @ [NotRel (c, ts)]) 
bulwahn@38073
   115
  | ensure_groundness_prem (NotEq (l, r)) = Conj (mk_groundness_prems [l, r] @ [NotEq (l, r)])
bulwahn@38073
   116
  | ensure_groundness_prem (Conj ps) = Conj (map ensure_groundness_prem ps)
bulwahn@38073
   117
  | ensure_groundness_prem p = p
bulwahn@38073
   118
bulwahn@38073
   119
fun ensure_groundness_before_negation p =
bulwahn@38073
   120
  map (apsnd ensure_groundness_prem) p
bulwahn@38073
   121
bulwahn@38073
   122
(* code printer *)
bulwahn@38073
   123
bulwahn@38073
   124
fun write_term (Var (v, _)) = first_upper v
bulwahn@38073
   125
  | write_term (Cons c) = first_lower c
bulwahn@38073
   126
  | write_term (AppF (f, args)) = first_lower f ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   127
bulwahn@38073
   128
fun write_rel (pred, args) =
bulwahn@38073
   129
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   130
bulwahn@38073
   131
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   132
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   133
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   134
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   135
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38073
   136
bulwahn@38073
   137
fun write_clause (head, prem) =
bulwahn@38073
   138
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   139
bulwahn@38073
   140
fun write_program p =
bulwahn@38073
   141
  cat_lines (map write_clause p) 
bulwahn@38073
   142
bulwahn@38073
   143
fun query_first rel vnames =
bulwahn@38073
   144
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38073
   145
  "writef('" ^ implode (map (fn v => v ^ " = %w\\n") vnames) ^"', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38073
   146
bulwahn@38073
   147
val prelude =
bulwahn@38073
   148
  "#!/usr/bin/swipl -q -t main -f\n\n" ^
bulwahn@38073
   149
  ":- style_check(-singleton).\n\n" ^
bulwahn@38073
   150
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   151
  "main :- halt(1).\n"
bulwahn@38075
   152
bulwahn@38075
   153
(* parsing prolog solution *)
bulwahn@38075
   154
bulwahn@38075
   155
val scan_atom =
bulwahn@38075
   156
  Scan.repeat (Scan.one (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_quasi s))
bulwahn@38075
   157
bulwahn@38075
   158
val scan_var =
bulwahn@38075
   159
  Scan.repeat (Scan.one
bulwahn@38075
   160
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38075
   161
bulwahn@38075
   162
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   163
bulwahn@38075
   164
val string_of = concat o map (dest_Char o Symbol.decode)
bulwahn@38075
   165
bulwahn@38075
   166
val scan_term =
bulwahn@38075
   167
  scan_atom >> (Cons o string_of) || scan_var >> (Var o rpair dummyT o string_of)
bulwahn@38075
   168
bulwahn@38075
   169
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38075
   170
            (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed"))
bulwahn@38075
   171
                            scan_term)
bulwahn@38075
   172
  o explode
bulwahn@38075
   173
  
bulwahn@38075
   174
fun parse_solution sol =
bulwahn@38075
   175
  let
bulwahn@38075
   176
    fun dest_eq s = (tracing s; tracing(commas (space_explode "=" s)); case space_explode "=" s of
bulwahn@38075
   177
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38075
   178
      | _ => raise Fail "unexpected equation in prolog output")
bulwahn@38075
   179
  in
bulwahn@38075
   180
    map dest_eq (fst (split_last (space_explode "\n" sol)))
bulwahn@38075
   181
  end 
bulwahn@38073
   182
  
bulwahn@38073
   183
(* calling external interpreter and getting results *)
bulwahn@38073
   184
bulwahn@38073
   185
fun run p query_rel vnames =
bulwahn@38073
   186
  let
bulwahn@38073
   187
    val cmd = Path.named_root
bulwahn@38073
   188
    val prog = prelude ^ query_first query_rel vnames ^ write_program p
bulwahn@38073
   189
    val prolog_file = File.tmp_path (Path.basic "prolog_file")
bulwahn@38073
   190
    val _ = File.write prolog_file prog
bulwahn@38073
   191
    val (solution, _) = bash_output ("/usr/bin/swipl -f " ^ File.shell_path prolog_file)
bulwahn@38075
   192
    val ts = parse_solution solution
bulwahn@38075
   193
    val _ = tracing (commas (map string_of_prol_term ts)) 
bulwahn@38073
   194
  in
bulwahn@38075
   195
    ts
bulwahn@38073
   196
  end
bulwahn@38073
   197
bulwahn@38075
   198
(* values command *)
bulwahn@38075
   199
bulwahn@38075
   200
fun mk_term (Var (s, T)) = Free (s, T)
bulwahn@38075
   201
  | mk_term (Cons s) = Const (s, dummyT)
bulwahn@38075
   202
  | mk_term (AppF (f, args)) = list_comb (Const (f, dummyT), map mk_term args)
bulwahn@38075
   203
  
bulwahn@38075
   204
fun values ctxt soln t_compr =
bulwahn@38075
   205
  let
bulwahn@38075
   206
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   207
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   208
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   209
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   210
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38075
   211
    val output_frees = map2 (curry Free) output_names (rev Ts)
bulwahn@38075
   212
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   213
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   214
      case strip_comb body of
bulwahn@38075
   215
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   216
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38075
   217
    val vnames =
bulwahn@38075
   218
      case try (map (fst o dest_Free)) all_args of
bulwahn@38075
   219
        SOME vs => vs
bulwahn@38075
   220
      | NONE => error ("Not only free variables in " ^ commas (map (Syntax.string_of_term ctxt) all_args))
bulwahn@38075
   221
    val ts = run (generate ctxt [name]) (translate_const name) (map first_upper vnames)
bulwahn@38075
   222
  in
bulwahn@38075
   223
    HOLogic.mk_tuple (map mk_term ts)
bulwahn@38075
   224
  end
bulwahn@38075
   225
bulwahn@38075
   226
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   227
  let
bulwahn@38075
   228
    val ctxt = Toplevel.context_of state
bulwahn@38075
   229
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   230
    val t' = values ctxt soln t
bulwahn@38075
   231
    val ty' = Term.type_of t'
bulwahn@38075
   232
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38075
   233
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   234
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   235
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   236
  in Pretty.writeln p end;
bulwahn@38075
   237
bulwahn@38075
   238
bulwahn@38075
   239
(* renewing the values command for Prolog queries *)
bulwahn@38075
   240
bulwahn@38075
   241
val opt_print_modes =
bulwahn@38075
   242
  Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
bulwahn@38075
   243
bulwahn@38075
   244
val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
bulwahn@38075
   245
  (opt_print_modes -- Scan.optional Parse.nat ~1 -- Parse.term
bulwahn@38075
   246
   >> (fn ((print_modes, soln), t) => Toplevel.keep
bulwahn@38075
   247
        (values_cmd print_modes soln t)));
bulwahn@38075
   248
bulwahn@38073
   249
end;