src/HOL/Tools/datatype_codegen.ML
author haftmann
Wed Jul 12 17:00:22 2006 +0200 (2006-07-12)
changeset 20105 454f4be984b7
parent 20071 8f3e1ddb50e6
child 20177 0af885e3dabf
permissions -rw-r--r--
adaptions in codegen
     1 (*  Title:      HOL/datatype_codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer & Florian Haftmann, TU Muenchen
     4 
     5 Code generator for inductive datatypes.
     6 *)
     7 
     8 signature DATATYPE_CODEGEN =
     9 sig
    10   val get_datatype_spec_thms: theory -> string
    11     -> (((string * sort) list * (string * typ list) list) * tactic) option
    12   val get_all_datatype_cons: theory -> (string * string) list
    13   val dest_case_expr: theory -> term
    14     -> ((string * typ) list * ((term * typ) * (term * term) list)) option;
    15   val add_datatype_case_const: string -> theory -> theory
    16   val add_datatype_case_defs: string -> theory -> theory
    17   val setup: theory -> theory
    18 end;
    19 
    20 structure DatatypeCodegen : DATATYPE_CODEGEN =
    21 struct
    22 
    23 open Codegen;
    24 
    25 fun mk_tuple [p] = p
    26   | mk_tuple ps = Pretty.block (Pretty.str "(" ::
    27       List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
    28         [Pretty.str ")"]);
    29 
    30 (**** datatype definition ****)
    31 
    32 (* find shortest path to constructor with no recursive arguments *)
    33 
    34 fun find_nonempty (descr: DatatypeAux.descr) is i =
    35   let
    36     val (_, _, constrs) = valOf (AList.lookup (op =) descr i);
    37     fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
    38           else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
    39       | arg_nonempty _ = SOME 0;
    40     fun max xs = Library.foldl
    41       (fn (NONE, _) => NONE
    42         | (SOME i, SOME j) => SOME (Int.max (i, j))
    43         | (_, NONE) => NONE) (SOME 0, xs);
    44     val xs = sort (int_ord o pairself snd)
    45       (List.mapPartial (fn (s, dts) => Option.map (pair s)
    46         (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
    47   in case xs of [] => NONE | x :: _ => SOME x end;
    48 
    49 fun add_dt_defs thy defs dep module gr (descr: DatatypeAux.descr) =
    50   let
    51     val sg = sign_of thy;
    52     val tab = DatatypePackage.get_datatypes thy;
    53 
    54     val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
    55     val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
    56       exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
    57 
    58     val (_, (tname, _, _)) :: _ = descr';
    59     val node_id = tname ^ " (type)";
    60     val module' = if_library (thyname_of_type tname thy) module;
    61 
    62     fun mk_dtdef gr prfx [] = (gr, [])
    63       | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
    64           let
    65             val tvs = map DatatypeAux.dest_DtTFree dts;
    66             val sorts = map (rpair []) tvs;
    67             val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
    68             val (gr', (_, type_id)) = mk_type_id module' tname gr;
    69             val (gr'', ps) =
    70               foldl_map (fn (gr, (cname, cargs)) =>
    71                 foldl_map (invoke_tycodegen thy defs node_id module' false)
    72                   (gr, cargs) |>>>
    73                 mk_const_id module' cname) (gr', cs');
    74             val (gr''', rest) = mk_dtdef gr'' "and " xs
    75           in
    76             (gr''',
    77              Pretty.block (Pretty.str prfx ::
    78                (if null tvs then [] else
    79                   [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
    80                [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
    81                List.concat (separate [Pretty.brk 1, Pretty.str "| "]
    82                  (map (fn (ps', (_, cname)) => [Pretty.block
    83                    (Pretty.str cname ::
    84                     (if null ps' then [] else
    85                      List.concat ([Pretty.str " of", Pretty.brk 1] ::
    86                        separate [Pretty.str " *", Pretty.brk 1]
    87                          (map single ps'))))]) ps))) :: rest)
    88           end;
    89 
    90     fun mk_term_of_def gr prfx [] = []
    91       | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
    92           let
    93             val tvs = map DatatypeAux.dest_DtTFree dts;
    94             val sorts = map (rpair []) tvs;
    95             val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
    96             val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
    97             val T = Type (tname, dts');
    98             val rest = mk_term_of_def gr "and " xs;
    99             val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
   100               let val args = map (fn i =>
   101                 Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
   102               in ("  | ", Pretty.blk (4,
   103                 [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
   104                  if null Ts then Pretty.str (snd (get_const_id cname gr))
   105                  else parens (Pretty.block
   106                    [Pretty.str (snd (get_const_id cname gr)),
   107                     Pretty.brk 1, mk_tuple args]),
   108                  Pretty.str " =", Pretty.brk 1] @
   109                  List.concat (separate [Pretty.str " $", Pretty.brk 1]
   110                    ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
   111                      mk_type false (Ts ---> T), Pretty.str ")"] ::
   112                     map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
   113                       Pretty.brk 1, x]]) (args ~~ Ts)))))
   114               end) (prfx, cs')
   115           in eqs @ rest end;
   116 
   117     fun mk_gen_of_def gr prfx [] = []
   118       | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
   119           let
   120             val tvs = map DatatypeAux.dest_DtTFree dts;
   121             val sorts = map (rpair []) tvs;
   122             val (cs1, cs2) =
   123               List.partition (exists DatatypeAux.is_rec_type o snd) cs;
   124             val SOME (cname, _) = find_nonempty descr [i] i;
   125 
   126             fun mk_delay p = Pretty.block
   127               [Pretty.str "fn () =>", Pretty.brk 1, p];
   128 
   129             fun mk_constr s b (cname, dts) =
   130               let
   131                 val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
   132                     (DatatypeAux.typ_of_dtyp descr sorts dt))
   133                   [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
   134                      else "j")]) dts;
   135                 val (_, id) = get_const_id cname gr
   136               in case gs of
   137                   _ :: _ :: _ => Pretty.block
   138                     [Pretty.str id, Pretty.brk 1, mk_tuple gs]
   139                 | _ => mk_app false (Pretty.str id) (map parens gs)
   140               end;
   141 
   142             fun mk_choice [c] = mk_constr "(i-1)" false c
   143               | mk_choice cs = Pretty.block [Pretty.str "one_of",
   144                   Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
   145                   List.concat (separate [Pretty.str ",", Pretty.fbrk]
   146                     (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
   147                   [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
   148 
   149             val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
   150             val gen_name = "gen_" ^ snd (get_type_id tname gr)
   151 
   152           in
   153             Pretty.blk (4, separate (Pretty.brk 1) 
   154                 (Pretty.str (prfx ^ gen_name ^
   155                    (if null cs1 then "" else "'")) :: gs @
   156                  (if null cs1 then [] else [Pretty.str "i"]) @
   157                  [Pretty.str "j"]) @
   158               [Pretty.str " =", Pretty.brk 1] @
   159               (if not (null cs1) andalso not (null cs2)
   160                then [Pretty.str "frequency", Pretty.brk 1,
   161                  Pretty.blk (1, [Pretty.str "[",
   162                    mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
   163                    Pretty.str ",", Pretty.fbrk,
   164                    mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
   165                    Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
   166                else if null cs2 then
   167                  [Pretty.block [Pretty.str "(case", Pretty.brk 1,
   168                    Pretty.str "i", Pretty.brk 1, Pretty.str "of",
   169                    Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
   170                    mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
   171                    Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
   172                    mk_choice cs1, Pretty.str ")"]]
   173                else [mk_choice cs2])) ::
   174             (if null cs1 then []
   175              else [Pretty.blk (4, separate (Pretty.brk 1) 
   176                  (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
   177                [Pretty.str " =", Pretty.brk 1] @
   178                separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
   179                  [Pretty.str "i", Pretty.str "i"]))]) @
   180             mk_gen_of_def gr "and " xs
   181           end
   182 
   183   in
   184     (add_edge_acyclic (node_id, dep) gr
   185         handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
   186          let
   187            val gr1 = add_edge (node_id, dep)
   188              (new_node (node_id, (NONE, "", "")) gr);
   189            val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
   190          in
   191            map_node node_id (K (NONE, module',
   192              Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
   193                [Pretty.str ";"])) ^ "\n\n" ^
   194              (if "term_of" mem !mode then
   195                 Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
   196                   (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
   197               else "") ^
   198              (if "test" mem !mode then
   199                 Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
   200                   (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
   201               else ""))) gr2
   202          end
   203   end;
   204 
   205 
   206 (**** case expressions ****)
   207 
   208 fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
   209   let val i = length constrs
   210   in if length ts <= i then
   211        invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
   212     else
   213       let
   214         val ts1 = Library.take (i, ts);
   215         val t :: ts2 = Library.drop (i, ts);
   216         val names = foldr add_term_names
   217           (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
   218         val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
   219 
   220         fun pcase gr [] [] [] = ([], gr)
   221           | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
   222               let
   223                 val j = length cargs;
   224                 val xs = Name.variant_list names (replicate j "x");
   225                 val Us' = Library.take (j, fst (strip_type U));
   226                 val frees = map Free (xs ~~ Us');
   227                 val (gr0, cp) = invoke_codegen thy defs dep module false
   228                   (gr, list_comb (Const (cname, Us' ---> dT), frees));
   229                 val t' = Envir.beta_norm (list_comb (t, frees));
   230                 val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
   231                 val (ps, gr2) = pcase gr1 cs ts Us;
   232               in
   233                 ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
   234               end;
   235 
   236         val (ps1, gr1) = pcase gr constrs ts1 Ts;
   237         val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
   238         val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
   239         val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
   240       in (gr3, (if not (null ts2) andalso brack then parens else I)
   241         (Pretty.block (separate (Pretty.brk 1)
   242           (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
   243              Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
   244       end
   245   end;
   246 
   247 
   248 (**** constructors ****)
   249 
   250 fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
   251   let val i = length args
   252   in if i > 1 andalso length ts < i then
   253       invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
   254      else
   255        let
   256          val id = mk_qual_id module (get_const_id s gr);
   257          val (gr', ps) = foldl_map
   258            (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
   259        in (case args of
   260           _ :: _ :: _ => (gr', (if brack then parens else I)
   261             (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
   262         | _ => (gr', mk_app brack (Pretty.str id) ps))
   263        end
   264   end;
   265 
   266 
   267 (**** code generators for terms and types ****)
   268 
   269 fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
   270    (c as Const (s, T), ts) =>
   271        (case Library.find_first (fn (_, {index, descr, case_name, ...}) =>
   272          s = case_name orelse
   273            AList.defined (op =) ((#3 o the o AList.lookup (op =) descr) index) s)
   274              (Symtab.dest (DatatypePackage.get_datatypes thy)) of
   275           NONE => NONE
   276         | SOME (tname, {index, descr, ...}) =>
   277            if is_some (get_assoc_code thy s T) then NONE else
   278            let val SOME (_, _, constrs) = AList.lookup (op =) descr index
   279            in (case (AList.lookup (op =) constrs s, strip_type T) of
   280                (NONE, _) => SOME (pretty_case thy defs gr dep module brack
   281                  ((#3 o the o AList.lookup (op =) descr) index) c ts)
   282              | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
   283                  (fst (invoke_tycodegen thy defs dep module false
   284                     (gr, snd (strip_type T))))
   285                  dep module brack args c ts)
   286              | _ => NONE)
   287            end)
   288  |  _ => NONE);
   289 
   290 fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   291       (case Symtab.lookup (DatatypePackage.get_datatypes thy) s of
   292          NONE => NONE
   293        | SOME {descr, ...} =>
   294            if isSome (get_assoc_type thy s) then NONE else
   295            let
   296              val (gr', ps) = foldl_map
   297                (invoke_tycodegen thy defs dep module false) (gr, Ts);
   298              val gr'' = add_dt_defs thy defs dep module gr' descr
   299            in SOME (gr'',
   300              Pretty.block ((if null Ts then [] else
   301                [mk_tuple ps, Pretty.str " "]) @
   302                [Pretty.str (mk_qual_id module (get_type_id s gr''))]))
   303            end)
   304   | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
   305 
   306 
   307 (** code 2nd generation **)
   308 
   309 fun dtyp_of_case_const thy c =
   310   get_first (fn (dtco, { case_name, ... }) => if case_name = c then SOME dtco else NONE)
   311     ((Symtab.dest o DatatypePackage.get_datatypes) thy);
   312 
   313 fun dest_case_app cs ts tys =
   314   let
   315     val abs = CodegenThingol.give_names [] (Library.drop (length ts, tys));
   316     val (ts', t) = split_last (ts @ map Free abs);
   317     val (tys', sty) = split_last tys;
   318     fun freenames_of t = fold_aterms
   319       (fn Free (v, _) => insert (op =) v | _ => I) t [];
   320     fun dest_case ((c, tys_decl), ty) t =
   321       let
   322         val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
   323         val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
   324       in (c', t') end;
   325   in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts')) end;
   326 
   327 fun dest_case_expr thy t =
   328   case strip_comb t
   329    of (Const (c, ty), ts) =>
   330         (case dtyp_of_case_const thy c
   331          of SOME dtco =>
   332               let val (vs, cs) = (the o DatatypePackage.get_datatype_spec thy) dtco;
   333               in SOME (dest_case_app cs ts (Library.take (length cs + 1, (fst o strip_type) ty))) end
   334           | _ => NONE)
   335     | _ => NONE;
   336 
   337 fun datatype_tac thy dtco =
   338   let
   339     val ctxt = Context.init_proof thy;
   340     val inject = (#inject o DatatypePackage.the_datatype thy) dtco;
   341     val simpset = Simplifier.context ctxt
   342       (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
   343   in
   344     (TRY o ALLGOALS o match_tac) [HOL.eq_reflection]
   345     THEN (
   346       (ALLGOALS o match_tac) (eqTrueI :: inject)
   347       ORELSE (ALLGOALS o simp_tac) simpset
   348     )
   349     THEN (ALLGOALS o match_tac) [HOL.refl, Drule.reflexive_thm]
   350   end;
   351 
   352 fun get_datatype_spec_thms thy dtco =
   353   case DatatypePackage.get_datatype_spec thy dtco
   354    of SOME vs_cos =>
   355         SOME (vs_cos, datatype_tac thy dtco)
   356     | NONE => NONE;
   357 
   358 fun get_all_datatype_cons thy =
   359   Symtab.fold (fn (dtco, _) => fold
   360     (fn (co, _) => cons (co, dtco))
   361       ((snd o the oo DatatypePackage.get_datatype_spec) thy dtco))
   362         (DatatypePackage.get_datatypes thy) [];
   363 
   364 fun add_datatype_case_const dtco thy =
   365   let
   366     val {case_name, index, descr, ...} = DatatypePackage.the_datatype thy dtco;
   367   in
   368     CodegenPackage.add_appconst_i (case_name, CodegenPackage.appgen_case dest_case_expr) thy
   369   end;
   370 
   371 fun add_datatype_case_defs dtco thy =
   372   let
   373     val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
   374   in
   375     fold CodegenTheorems.add_fun case_rewrites thy
   376   end;
   377 
   378 val setup = 
   379   add_codegen "datatype" datatype_codegen #>
   380   add_tycodegen "datatype" datatype_tycodegen #>
   381   CodegenTheorems.add_datatype_extr
   382     get_datatype_spec_thms #>
   383   CodegenPackage.set_get_all_datatype_cons
   384     get_all_datatype_cons #>
   385   DatatypeHooks.add add_datatype_case_const #>
   386   DatatypeHooks.add add_datatype_case_defs
   387 
   388 end;