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