src/HOL/Tools/recfun_codegen.ML
author haftmann
Thu, 14 May 2009 15:09:48 +0200
changeset 31156 90fed3d4430f
parent 31125 80218ee73167
child 31954 8db19c99b00a
child 31957 a9742afd403e
permissions -rw-r--r--
merged module code_unit.ML into code.ML
     1 (*  Title:      HOL/Tools/recfun_codegen.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Code generator for recursive functions.
     5 *)
     6 
     7 signature RECFUN_CODEGEN =
     8 sig
     9   val setup: theory -> theory
    10 end;
    11 
    12 structure RecfunCodegen : RECFUN_CODEGEN =
    13 struct
    14 
    15 open Codegen;
    16 
    17 structure ModuleData = TheoryDataFun
    18 (
    19   type T = string Symtab.table;
    20   val empty = Symtab.empty;
    21   val copy = I;
    22   val extend = I;
    23   fun merge _ = Symtab.merge (K true);
    24 );
    25 
    26 fun add_thm NONE thm thy = Code.add_eqn thm thy
    27   | add_thm (SOME module_name) thm thy =
    28       let
    29         val (thm', _) = Code.mk_eqn thy (K false) (thm, true)
    30       in
    31         thy
    32         |> ModuleData.map (Symtab.update (Code.const_eqn thy thm', module_name))
    33         |> Code.add_eqn thm'
    34       end;
    35 
    36 fun meta_eq_to_obj_eq thy thm =
    37   let
    38     val T = (fastype_of o fst o Logic.dest_equals o Thm.prop_of) thm;
    39   in if Sign.of_sort thy (T, @{sort type})
    40     then SOME (Conv.fconv_rule Drule.beta_eta_conversion (@{thm meta_eq_to_obj_eq} OF [thm]))
    41     else NONE
    42   end;
    43 
    44 fun expand_eta thy [] = []
    45   | expand_eta thy (thms as thm :: _) =
    46       let
    47         val (_, ty) = Code.const_typ_eqn thm;
    48       in if null (Term.add_tvarsT ty []) orelse (null o fst o strip_type) ty
    49         then thms
    50         else map (Code.expand_eta thy 1) thms
    51       end;
    52 
    53 fun retrieve_equations thy (c, T) = if c = @{const_name "op ="} then NONE else
    54   let
    55     val c' = AxClass.unoverload_const thy (c, T);
    56     val opt_name = Symtab.lookup (ModuleData.get thy) c';
    57     val thms = Code.these_eqns thy c'
    58       |> map_filter (fn (thm, linear) => if linear then SOME thm else NONE)
    59       |> expand_eta thy
    60       |> map_filter (meta_eq_to_obj_eq thy)
    61       |> Code.norm_varnames thy
    62       |> map (rpair opt_name)
    63   in if null thms then NONE else SOME thms end;
    64 
    65 val dest_eqn = HOLogic.dest_eq o HOLogic.dest_Trueprop;
    66 val const_of = dest_Const o head_of o fst o dest_eqn;
    67 
    68 fun get_equations thy defs (s, T) =
    69   (case retrieve_equations thy (s, T) of
    70      NONE => ([], "")
    71    | SOME thms => 
    72        let val thms' = filter (fn (thm, _) => is_instance T
    73            (snd (const_of (prop_of thm)))) thms
    74        in if null thms' then ([], "")
    75          else (preprocess thy (map fst thms'),
    76            case snd (snd (split_last thms')) of
    77                NONE => (case get_defn thy defs s T of
    78                    NONE => Codegen.thyname_of_const thy s
    79                  | SOME ((_, (thyname, _)), _) => thyname)
    80              | SOME thyname => thyname)
    81        end);
    82 
    83 fun mk_suffix thy defs (s, T) = (case get_defn thy defs s T of
    84   SOME (_, SOME i) => " def" ^ string_of_int i | _ => "");
    85 
    86 exception EQN of string * typ * string;
    87 
    88 fun cycle g (xs, x : string) =
    89   if member (op =) xs x then xs
    90   else Library.foldl (cycle g) (x :: xs, flat (Graph.all_paths (fst g) (x, x)));
    91 
    92 fun add_rec_funs thy defs dep module eqs gr =
    93   let
    94     fun dest_eq t = (fst (const_of t) ^ mk_suffix thy defs (const_of t),
    95       dest_eqn (rename_term t));
    96     val eqs' = map dest_eq eqs;
    97     val (dname, _) :: _ = eqs';
    98     val (s, T) = const_of (hd eqs);
    99 
   100     fun mk_fundef module fname first [] gr = ([], gr)
   101       | mk_fundef module fname first ((fname' : string, (lhs, rhs)) :: xs) gr =
   102       let
   103         val (pl, gr1) = invoke_codegen thy defs dname module false lhs gr;
   104         val (pr, gr2) = invoke_codegen thy defs dname module false rhs gr1;
   105         val (rest, gr3) = mk_fundef module fname' false xs gr2 ;
   106         val (ty, gr4) = invoke_tycodegen thy defs dname module false T gr3;
   107         val num_args = (length o snd o strip_comb) lhs;
   108         val prfx = if fname = fname' then "  |"
   109           else if not first then "and"
   110           else if num_args = 0 then "val"
   111           else "fun";
   112         val pl' = Pretty.breaks (str prfx
   113           :: (if num_args = 0 then [pl, str ":", ty] else [pl]));
   114       in
   115         (Pretty.blk (4, pl'
   116            @ [str " =", Pretty.brk 1, pr]) :: rest, gr4)
   117       end;
   118 
   119     fun put_code module fundef = map_node dname
   120       (K (SOME (EQN ("", dummyT, dname)), module, string_of (Pretty.blk (0,
   121       separate Pretty.fbrk fundef @ [str ";"])) ^ "\n\n"));
   122 
   123   in
   124     (case try (get_node gr) dname of
   125        NONE =>
   126          let
   127            val gr1 = add_edge (dname, dep)
   128              (new_node (dname, (SOME (EQN (s, T, "")), module, "")) gr);
   129            val (fundef, gr2) = mk_fundef module "" true eqs' gr1 ;
   130            val xs = cycle gr2 ([], dname);
   131            val cs = map (fn x => case get_node gr2 x of
   132                (SOME (EQN (s, T, _)), _, _) => (s, T)
   133              | _ => error ("RecfunCodegen: illegal cyclic dependencies:\n" ^
   134                 implode (separate ", " xs))) xs
   135          in (case xs of
   136              [_] => (module, put_code module fundef gr2)
   137            | _ =>
   138              if not (dep mem xs) then
   139                let
   140                  val thmss as (_, thyname) :: _ = map (get_equations thy defs) cs;
   141                  val module' = if_library thyname module;
   142                  val eqs'' = map (dest_eq o prop_of) (List.concat (map fst thmss));
   143                  val (fundef', gr3) = mk_fundef module' "" true eqs''
   144                    (add_edge (dname, dep)
   145                      (List.foldr (uncurry new_node) (del_nodes xs gr2)
   146                        (map (fn k =>
   147                          (k, (SOME (EQN ("", dummyT, dname)), module', ""))) xs)))
   148                in (module', put_code module' fundef' gr3) end
   149              else (module, gr2))
   150          end
   151      | SOME (SOME (EQN (_, _, s)), module', _) =>
   152          (module', if s = "" then
   153             if dname = dep then gr else add_edge (dname, dep) gr
   154           else if s = dep then gr else add_edge (s, dep) gr))
   155   end;
   156 
   157 fun recfun_codegen thy defs dep module brack t gr = (case strip_comb t of
   158     (Const (p as (s, T)), ts) => (case (get_equations thy defs p, get_assoc_code thy (s, T)) of
   159        (([], _), _) => NONE
   160      | (_, SOME _) => NONE
   161      | ((eqns, thyname), NONE) =>
   162         let
   163           val module' = if_library thyname module;
   164           val (ps, gr') = fold_map
   165             (invoke_codegen thy defs dep module true) ts gr;
   166           val suffix = mk_suffix thy defs p;
   167           val (module'', gr'') =
   168             add_rec_funs thy defs dep module' (map prop_of eqns) gr';
   169           val (fname, gr''') = mk_const_id module'' (s ^ suffix) gr''
   170         in
   171           SOME (mk_app brack (str (mk_qual_id module fname)) ps, gr''')
   172         end)
   173   | _ => NONE);
   174 
   175 val setup = let
   176   fun add opt_module = Thm.declaration_attribute (fn thm => Context.mapping
   177     (add_thm opt_module thm) I);
   178   val del = Thm.declaration_attribute (fn thm => Context.mapping
   179     (Code.del_eqn thm) I);
   180 in
   181   add_codegen "recfun" recfun_codegen
   182   #> Code.add_attribute ("", Args.del |-- Scan.succeed del
   183      || Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) >> add)
   184 end;
   185 
   186 end;