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