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