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