src/HOL/Tools/recfun_codegen.ML
author berghofe
Mon Sep 22 16:14:58 2003 +0200 (2003-09-22)
changeset 14196 be5e838f37bd
parent 13105 3d1e7a199bdc
child 14981 e73f8140af78
permissions -rw-r--r--
Added "del" attribute for deleting equations.
     1 (*  Title:      HOL/recfun_codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 Code generator for recursive functions.
     7 *)
     8 
     9 signature RECFUN_CODEGEN =
    10 sig
    11   val add: theory attribute
    12   val setup: (theory -> theory) list
    13 end;
    14 
    15 structure RecfunCodegen : RECFUN_CODEGEN =
    16 struct
    17 
    18 open Codegen;
    19 
    20 structure CodegenArgs =
    21 struct
    22   val name = "HOL/recfun_codegen";
    23   type T = thm list Symtab.table;
    24   val empty = Symtab.empty;
    25   val copy = I;
    26   val prep_ext = I;
    27   val merge = Symtab.merge_multi Drule.eq_thm_prop;
    28   fun print _ _ = ();
    29 end;
    30 
    31 structure CodegenData = TheoryDataFun(CodegenArgs);
    32 
    33 val prop_of = #prop o rep_thm;
    34 val dest_eqn = HOLogic.dest_eq o HOLogic.dest_Trueprop;
    35 val const_of = dest_Const o head_of o fst o dest_eqn;
    36 
    37 fun warn thm = warning ("RecfunCodegen: Not a proper equation:\n" ^
    38   string_of_thm thm);
    39 
    40 fun add (p as (thy, thm)) =
    41   let
    42     val tsig = Sign.tsig_of (sign_of thy);
    43     val tab = CodegenData.get thy;
    44     val (s, _) = const_of (prop_of thm);
    45 
    46     val matches = curry
    47       (Pattern.matches tsig o pairself (fst o dest_eqn o prop_of));
    48 
    49   in (CodegenData.put (Symtab.update ((s,
    50     filter_out (matches thm) (if_none (Symtab.lookup (tab, s)) []) @ [thm]),
    51       tab)) thy, thm)
    52   end handle TERM _ => (warn thm; p) | Pattern.Pattern => (warn thm; p);
    53 
    54 fun del (p as (thy, thm)) =
    55   let
    56     val tab = CodegenData.get thy;
    57     val (s, _) = const_of (prop_of thm);
    58   in (CodegenData.put (Symtab.update ((s,
    59     gen_rem eq_thm (if_none (Symtab.lookup (tab, s)) [], thm)),
    60       tab)) thy, thm)
    61   end handle TERM _ => (warn thm; p);
    62 
    63 fun get_equations thy (s, T) =
    64   (case Symtab.lookup (CodegenData.get thy, s) of
    65      None => []
    66    | Some thms => filter (fn thm => is_instance thy T
    67        (snd (const_of (prop_of thm)))) thms);
    68 
    69 fun mk_poly_id thy (s, T) = mk_const_id (sign_of thy) s ^
    70   (case get_defn thy s T of
    71      Some (_, Some i) => "_def" ^ string_of_int i
    72    | _ => "");
    73 
    74 exception EQN of string * typ * string;
    75 
    76 fun cycle g (xs, x) =
    77   if x mem xs then xs
    78   else foldl (cycle g) (x :: xs, flat (Graph.find_paths g (x, x)));
    79 
    80 fun add_rec_funs thy gr dep eqs =
    81   let
    82     fun dest_eq t =
    83       (mk_poly_id thy (const_of t), dest_eqn (rename_term t));
    84     val eqs' = map dest_eq eqs;
    85     val (dname, _) :: _ = eqs';
    86     val (s, T) = const_of (hd eqs);
    87 
    88     fun mk_fundef fname prfx gr [] = (gr, [])
    89       | mk_fundef fname prfx gr ((fname', (lhs, rhs)) :: xs) =
    90       let
    91         val (gr1, pl) = invoke_codegen thy dname false (gr, lhs);
    92         val (gr2, pr) = invoke_codegen thy dname false (gr1, rhs);
    93         val (gr3, rest) = mk_fundef fname' "and " gr2 xs
    94       in
    95         (gr3, Pretty.blk (4, [Pretty.str (if fname = fname' then "  | " else prfx),
    96            pl, Pretty.str " =", Pretty.brk 1, pr]) :: rest)
    97       end;
    98 
    99     fun put_code fundef = Graph.map_node dname
   100       (K (Some (EQN ("", dummyT, dname)), Pretty.string_of (Pretty.blk (0,
   101       separate Pretty.fbrk fundef @ [Pretty.str ";"])) ^ "\n\n"));
   102 
   103   in
   104     (case try (Graph.get_node gr) dname of
   105        None =>
   106          let
   107            val gr1 = Graph.add_edge (dname, dep)
   108              (Graph.new_node (dname, (Some (EQN (s, T, "")), "")) gr);
   109            val (gr2, fundef) = mk_fundef "" "fun " gr1 eqs';
   110            val xs = cycle gr2 ([], dname);
   111            val cs = map (fn x => case Graph.get_node gr2 x of
   112                (Some (EQN (s, T, _)), _) => (s, T)
   113              | _ => error ("RecfunCodegen: illegal cyclic dependencies:\n" ^
   114                 implode (separate ", " xs))) xs
   115          in (case xs of
   116              [_] => put_code fundef gr2
   117            | _ =>
   118              if not (dep mem xs) then
   119                let
   120                  val eqs'' = map (dest_eq o prop_of)
   121                    (flat (map (get_equations thy) cs));
   122                  val (gr3, fundef') = mk_fundef "" "fun "
   123                    (Graph.add_edge (dname, dep)
   124                      (foldr (uncurry Graph.new_node) (map (fn k =>
   125                        (k, (Some (EQN ("", dummyT, dname)), ""))) xs,
   126                          Graph.del_nodes xs gr2))) eqs''
   127                in put_code fundef' gr3 end
   128              else gr2)
   129          end
   130      | Some (Some (EQN (_, _, s)), _) =>
   131          if s = "" then
   132            if dname = dep then gr else Graph.add_edge (dname, dep) gr
   133          else if s = dep then gr else Graph.add_edge (s, dep) gr)
   134   end;
   135 
   136 fun recfun_codegen thy gr dep brack t = (case strip_comb t of
   137     (Const p, ts) => (case get_equations thy p of
   138        [] => None
   139      | eqns =>
   140         let val (gr', ps) = foldl_map (invoke_codegen thy dep true) (gr, ts)
   141         in
   142           Some (add_rec_funs thy gr' dep (map prop_of eqns),
   143             mk_app brack (Pretty.str (mk_poly_id thy p)) ps)
   144         end)
   145   | _ => None);
   146 
   147 
   148 val setup =
   149   [CodegenData.init,
   150    add_codegen "recfun" recfun_codegen,
   151    add_attribute "" (Args.del |-- Scan.succeed del || Scan.succeed add)];
   152 
   153 end;