src/Pure/codegen.ML
author haftmann
Thu Oct 22 13:48:06 2009 +0200 (2009-10-22)
changeset 33063 4d462963a7db
parent 33042 ddf1f03a9ad9
child 33092 c859019d3ac5
permissions -rw-r--r--
map_range (and map_index) combinator
     1 (*  Title:      Pure/codegen.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Generic code generator.
     5 *)
     6 
     7 signature CODEGEN =
     8 sig
     9   val quiet_mode : bool Unsynchronized.ref
    10   val message : string -> unit
    11   val mode : string list Unsynchronized.ref
    12   val margin : int Unsynchronized.ref
    13   val string_of : Pretty.T -> string
    14   val str : string -> Pretty.T
    15 
    16   datatype 'a mixfix =
    17       Arg
    18     | Ignore
    19     | Module
    20     | Pretty of Pretty.T
    21     | Quote of 'a;
    22 
    23   type deftab
    24   type node
    25   type codegr
    26   type 'a codegen
    27 
    28   val add_codegen: string -> term codegen -> theory -> theory
    29   val add_tycodegen: string -> typ codegen -> theory -> theory
    30   val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory
    31   val preprocess: theory -> thm list -> thm list
    32   val preprocess_term: theory -> term -> term
    33   val print_codegens: theory -> unit
    34   val generate_code: theory -> string list -> string -> (string * string) list ->
    35     (string * string) list * codegr
    36   val generate_code_i: theory -> string list -> string -> (string * term) list ->
    37     (string * string) list * codegr
    38   val assoc_const: string * (term mixfix list *
    39     (string * string) list) -> theory -> theory
    40   val assoc_const_i: (string * typ) * (term mixfix list *
    41     (string * string) list) -> theory -> theory
    42   val assoc_type: xstring * (typ mixfix list *
    43     (string * string) list) -> theory -> theory
    44   val get_assoc_code: theory -> string * typ ->
    45     (term mixfix list * (string * string) list) option
    46   val get_assoc_type: theory -> string ->
    47     (typ mixfix list * (string * string) list) option
    48   val codegen_error: codegr -> string -> string -> 'a
    49   val invoke_codegen: theory -> deftab -> string -> string -> bool ->
    50     term -> codegr -> Pretty.T * codegr
    51   val invoke_tycodegen: theory -> deftab -> string -> string -> bool ->
    52     typ -> codegr -> Pretty.T * codegr
    53   val mk_id: string -> string
    54   val mk_qual_id: string -> string * string -> string
    55   val mk_const_id: string -> string -> codegr -> (string * string) * codegr
    56   val get_const_id: codegr -> string -> string * string
    57   val mk_type_id: string -> string -> codegr -> (string * string) * codegr
    58   val get_type_id: codegr -> string -> string * string
    59   val thyname_of_type: theory -> string -> string
    60   val thyname_of_const: theory -> string -> string
    61   val rename_terms: term list -> term list
    62   val rename_term: term -> term
    63   val new_names: term -> string list -> string list
    64   val new_name: term -> string -> string
    65   val if_library: 'a -> 'a -> 'a
    66   val get_defn: theory -> deftab -> string -> typ ->
    67     ((typ * (string * thm)) * int option) option
    68   val is_instance: typ -> typ -> bool
    69   val parens: Pretty.T -> Pretty.T
    70   val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
    71   val mk_tuple: Pretty.T list -> Pretty.T
    72   val mk_let: (Pretty.T * Pretty.T) list -> Pretty.T -> Pretty.T
    73   val eta_expand: term -> term list -> int -> term
    74   val strip_tname: string -> string
    75   val mk_type: bool -> typ -> Pretty.T
    76   val mk_term_of: codegr -> string -> bool -> typ -> Pretty.T
    77   val mk_gen: codegr -> string -> bool -> string list -> string -> typ -> Pretty.T
    78   val test_fn: (int -> term list option) Unsynchronized.ref
    79   val test_term: Proof.context -> term -> int -> term list option
    80   val eval_result: (unit -> term) Unsynchronized.ref
    81   val eval_term: theory -> term -> term
    82   val evaluation_conv: cterm -> thm
    83   val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    84   val quotes_of: 'a mixfix list -> 'a list
    85   val num_args_of: 'a mixfix list -> int
    86   val replace_quotes: 'b list -> 'a mixfix list -> 'b mixfix list
    87   val mk_deftab: theory -> deftab
    88   val map_unfold: (simpset -> simpset) -> theory -> theory
    89   val add_unfold: thm -> theory -> theory
    90   val del_unfold: thm -> theory -> theory
    91 
    92   val get_node: codegr -> string -> node
    93   val add_edge: string * string -> codegr -> codegr
    94   val add_edge_acyclic: string * string -> codegr -> codegr
    95   val del_nodes: string list -> codegr -> codegr
    96   val map_node: string -> (node -> node) -> codegr -> codegr
    97   val new_node: string * node -> codegr -> codegr
    98 
    99   val setup: theory -> theory
   100 end;
   101 
   102 structure Codegen : CODEGEN =
   103 struct
   104 
   105 val quiet_mode = Unsynchronized.ref true;
   106 fun message s = if !quiet_mode then () else writeln s;
   107 
   108 val mode = Unsynchronized.ref ([] : string list);
   109 
   110 val margin = Unsynchronized.ref 80;
   111 
   112 fun string_of p = (Pretty.string_of |>
   113   PrintMode.setmp [] |>
   114   Pretty.setmp_margin_CRITICAL (!margin)) p;
   115 
   116 val str = PrintMode.setmp [] Pretty.str;
   117 
   118 (**** Mixfix syntax ****)
   119 
   120 datatype 'a mixfix =
   121     Arg
   122   | Ignore
   123   | Module
   124   | Pretty of Pretty.T
   125   | Quote of 'a;
   126 
   127 fun is_arg Arg = true
   128   | is_arg Ignore = true
   129   | is_arg _ = false;
   130 
   131 fun quotes_of [] = []
   132   | quotes_of (Quote q :: ms) = q :: quotes_of ms
   133   | quotes_of (_ :: ms) = quotes_of ms;
   134 
   135 fun args_of [] xs = ([], xs)
   136   | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
   137   | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
   138   | args_of (_ :: ms) xs = args_of ms xs;
   139 
   140 fun num_args_of x = length (List.filter is_arg x);
   141 
   142 
   143 (**** theory data ****)
   144 
   145 (* preprocessed definition table *)
   146 
   147 type deftab =
   148   (typ *              (* type of constant *)
   149     (string *         (* name of theory containing definition of constant *)
   150       thm))           (* definition theorem *)
   151   list Symtab.table;
   152 
   153 (* code dependency graph *)
   154 
   155 type nametab = (string * string) Symtab.table * unit Symtab.table;
   156 
   157 fun merge_nametabs ((tab, used) : nametab, (tab', used')) =
   158   (Symtab.merge op = (tab, tab'), Symtab.merge op = (used, used'));
   159 
   160 type node =
   161   (exn option *    (* slot for arbitrary data *)
   162    string *        (* name of structure containing piece of code *)
   163    string);        (* piece of code *)
   164 
   165 type codegr =
   166   node Graph.T *
   167   (nametab *       (* table for assigned constant names *)
   168    nametab);       (* table for assigned type names *)
   169 
   170 val emptygr : codegr = (Graph.empty,
   171   ((Symtab.empty, Symtab.empty), (Symtab.empty, Symtab.empty)));
   172 
   173 (* type of code generators *)
   174 
   175 type 'a codegen =
   176   theory ->    (* theory in which generate_code was called *)
   177   deftab ->    (* definition table (for efficiency) *)
   178   string ->    (* node name of caller (for recording dependencies) *)
   179   string ->    (* module name of caller (for modular code generation) *)
   180   bool ->      (* whether to parenthesize generated expression *)
   181   'a ->        (* item to generate code from *)
   182   codegr ->    (* code dependency graph *)
   183   (Pretty.T * codegr) option;
   184 
   185 
   186 (* theory data *)
   187 
   188 structure CodegenData = TheoryDataFun
   189 (
   190   type T =
   191     {codegens : (string * term codegen) list,
   192      tycodegens : (string * typ codegen) list,
   193      consts : ((string * typ) * (term mixfix list * (string * string) list)) list,
   194      types : (string * (typ mixfix list * (string * string) list)) list,
   195      preprocs: (stamp * (theory -> thm list -> thm list)) list,
   196      modules: codegr Symtab.table};
   197 
   198   val empty =
   199     {codegens = [], tycodegens = [], consts = [], types = [],
   200      preprocs = [], modules = Symtab.empty};
   201   val copy = I;
   202   val extend = I;
   203 
   204   fun merge _
   205     ({codegens = codegens1, tycodegens = tycodegens1,
   206       consts = consts1, types = types1,
   207       preprocs = preprocs1, modules = modules1} : T,
   208      {codegens = codegens2, tycodegens = tycodegens2,
   209       consts = consts2, types = types2,
   210       preprocs = preprocs2, modules = modules2}) =
   211     {codegens = AList.merge (op =) (K true) (codegens1, codegens2),
   212      tycodegens = AList.merge (op =) (K true) (tycodegens1, tycodegens2),
   213      consts = AList.merge (op =) (K true) (consts1, consts2),
   214      types = AList.merge (op =) (K true) (types1, types2),
   215      preprocs = AList.merge (op =) (K true) (preprocs1, preprocs2),
   216      modules = Symtab.merge (K true) (modules1, modules2)};
   217 );
   218 
   219 fun print_codegens thy =
   220   let val {codegens, tycodegens, ...} = CodegenData.get thy in
   221     Pretty.writeln (Pretty.chunks
   222       [Pretty.strs ("term code generators:" :: map fst codegens),
   223        Pretty.strs ("type code generators:" :: map fst tycodegens)])
   224   end;
   225 
   226 
   227 
   228 (**** access modules ****)
   229 
   230 fun get_modules thy = #modules (CodegenData.get thy);
   231 
   232 fun map_modules f thy =
   233   let val {codegens, tycodegens, consts, types, preprocs, modules} =
   234     CodegenData.get thy;
   235   in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
   236     consts = consts, types = types, preprocs = preprocs,
   237     modules = f modules} thy
   238   end;
   239 
   240 
   241 (**** add new code generators to theory ****)
   242 
   243 fun add_codegen name f thy =
   244   let val {codegens, tycodegens, consts, types, preprocs, modules} =
   245     CodegenData.get thy
   246   in (case AList.lookup (op =) codegens name of
   247       NONE => CodegenData.put {codegens = (name, f) :: codegens,
   248         tycodegens = tycodegens, consts = consts, types = types,
   249         preprocs = preprocs, modules = modules} thy
   250     | SOME _ => error ("Code generator " ^ name ^ " already declared"))
   251   end;
   252 
   253 fun add_tycodegen name f thy =
   254   let val {codegens, tycodegens, consts, types, preprocs, modules} =
   255     CodegenData.get thy
   256   in (case AList.lookup (op =) tycodegens name of
   257       NONE => CodegenData.put {tycodegens = (name, f) :: tycodegens,
   258         codegens = codegens, consts = consts, types = types,
   259         preprocs = preprocs, modules = modules} thy
   260     | SOME _ => error ("Code generator " ^ name ^ " already declared"))
   261   end;
   262 
   263 
   264 (**** preprocessors ****)
   265 
   266 fun add_preprocessor p thy =
   267   let val {codegens, tycodegens, consts, types, preprocs, modules} =
   268     CodegenData.get thy
   269   in CodegenData.put {tycodegens = tycodegens,
   270     codegens = codegens, consts = consts, types = types,
   271     preprocs = (stamp (), p) :: preprocs,
   272     modules = modules} thy
   273   end;
   274 
   275 fun preprocess thy =
   276   let val {preprocs, ...} = CodegenData.get thy
   277   in fold (fn (_, f) => f thy) preprocs end;
   278 
   279 fun preprocess_term thy t =
   280   let
   281     val x = Free (Name.variant (OldTerm.add_term_names (t, [])) "x", fastype_of t);
   282     (* fake definition *)
   283     val eq = Skip_Proof.make_thm thy (Logic.mk_equals (x, t));
   284     fun err () = error "preprocess_term: bad preprocessor"
   285   in case map prop_of (preprocess thy [eq]) of
   286       [Const ("==", _) $ x' $ t'] => if x = x' then t' else err ()
   287     | _ => err ()
   288   end;
   289 
   290 structure UnfoldData = TheoryDataFun
   291 (
   292   type T = simpset;
   293   val empty = empty_ss;
   294   val copy = I;
   295   val extend = I;
   296   fun merge _ = merge_ss;
   297 );
   298 
   299 val map_unfold = UnfoldData.map;
   300 val add_unfold = map_unfold o MetaSimplifier.add_simp;
   301 val del_unfold = map_unfold o MetaSimplifier.del_simp;
   302 
   303 fun unfold_preprocessor thy =
   304   let val ss = Simplifier.theory_context thy (UnfoldData.get thy)
   305   in map (Thm.transfer thy #> Simplifier.full_simplify ss) end;
   306 
   307 
   308 (**** associate constants with target language code ****)
   309 
   310 fun gen_assoc_const prep_const (raw_const, syn) thy =
   311   let
   312     val {codegens, tycodegens, consts, types, preprocs, modules} =
   313       CodegenData.get thy;
   314     val (cname, T) = prep_const thy raw_const;
   315   in
   316     if num_args_of (fst syn) > length (binder_types T) then
   317       error ("More arguments than in corresponding type of " ^ cname)
   318     else case AList.lookup (op =) consts (cname, T) of
   319       NONE => CodegenData.put {codegens = codegens,
   320         tycodegens = tycodegens,
   321         consts = ((cname, T), syn) :: consts,
   322         types = types, preprocs = preprocs,
   323         modules = modules} thy
   324     | SOME _ => error ("Constant " ^ cname ^ " already associated with code")
   325   end;
   326 
   327 val assoc_const_i = gen_assoc_const (K I);
   328 val assoc_const = gen_assoc_const Code.read_bare_const;
   329 
   330 
   331 (**** associate types with target language types ****)
   332 
   333 fun assoc_type (s, syn) thy =
   334   let
   335     val {codegens, tycodegens, consts, types, preprocs, modules} =
   336       CodegenData.get thy;
   337     val tc = Sign.intern_type thy s;
   338   in
   339     case Symtab.lookup (snd (#types (Type.rep_tsig (Sign.tsig_of thy)))) tc of
   340       SOME ((Type.LogicalType i, _), _) =>
   341         if num_args_of (fst syn) > i then
   342           error ("More arguments than corresponding type constructor " ^ s)
   343         else (case AList.lookup (op =) types tc of
   344           NONE => CodegenData.put {codegens = codegens,
   345             tycodegens = tycodegens, consts = consts,
   346             types = (tc, syn) :: types,
   347             preprocs = preprocs, modules = modules} thy
   348         | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
   349     | _ => error ("Not a type constructor: " ^ s)
   350   end;
   351 
   352 fun get_assoc_type thy = AList.lookup (op =) ((#types o CodegenData.get) thy);
   353 
   354 
   355 (**** make valid ML identifiers ****)
   356 
   357 fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
   358   Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
   359 
   360 fun dest_sym s = (case split_last (snd (take_prefix (fn c => c = "\\") (explode s))) of
   361     ("<" :: "^" :: xs, ">") => (true, implode xs)
   362   | ("<" :: xs, ">") => (false, implode xs)
   363   | _ => sys_error "dest_sym");
   364 
   365 fun mk_id s = if s = "" then "" else
   366   let
   367     fun check_str [] = []
   368       | check_str xs = (case take_prefix is_ascii_letdig xs of
   369           ([], " " :: zs) => check_str zs
   370         | ([], z :: zs) =>
   371           if size z = 1 then string_of_int (ord z) :: check_str zs
   372           else (case dest_sym z of
   373               (true, "isub") => check_str zs
   374             | (true, "isup") => "" :: check_str zs
   375             | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
   376         | (ys, zs) => implode ys :: check_str zs);
   377     val s' = space_implode "_" (maps (check_str o Symbol.explode) (Long_Name.explode s))
   378   in
   379     if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
   380   end;
   381 
   382 fun mk_long_id (p as (tab, used)) module s =
   383   let
   384     fun find_name [] = sys_error "mk_long_id"
   385       | find_name (ys :: yss) =
   386           let
   387             val s' = Long_Name.implode ys
   388             val s'' = Long_Name.append module s'
   389           in case Symtab.lookup used s'' of
   390               NONE => ((module, s'),
   391                 (Symtab.update_new (s, (module, s')) tab,
   392                  Symtab.update_new (s'', ()) used))
   393             | SOME _ => find_name yss
   394           end
   395   in case Symtab.lookup tab s of
   396       NONE => find_name (Library.suffixes1 (Long_Name.explode s))
   397     | SOME name => (name, p)
   398   end;
   399 
   400 (* module:  module name for caller                                        *)
   401 (* module': module name for callee                                        *)
   402 (* if caller and callee reside in different modules, use qualified access *)
   403 
   404 fun mk_qual_id module (module', s) =
   405   if module = module' orelse module' = "" then s else module' ^ "." ^ s;
   406 
   407 fun mk_const_id module cname (gr, (tab1, tab2)) =
   408   let
   409     val ((module, s), tab1') = mk_long_id tab1 module cname
   410     val s' = mk_id s;
   411     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   412   in (((module, s'')), (gr, (tab1', tab2))) end;
   413 
   414 fun get_const_id (gr, (tab1, tab2)) cname =
   415   case Symtab.lookup (fst tab1) cname of
   416     NONE => error ("get_const_id: no such constant: " ^ quote cname)
   417   | SOME (module, s) =>
   418       let
   419         val s' = mk_id s;
   420         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   421       in (module, s'') end;
   422 
   423 fun mk_type_id module tyname (gr, (tab1, tab2)) =
   424   let
   425     val ((module, s), tab2') = mk_long_id tab2 module tyname
   426     val s' = mk_id s;
   427     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   428   in ((module, s''), (gr, (tab1, tab2'))) end;
   429 
   430 fun get_type_id (gr, (tab1, tab2)) tyname =
   431   case Symtab.lookup (fst tab2) tyname of
   432     NONE => error ("get_type_id: no such type: " ^ quote tyname)
   433   | SOME (module, s) =>
   434       let
   435         val s' = mk_id s;
   436         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   437       in (module, s'') end;
   438 
   439 fun get_type_id' f tab tyname = apsnd f (get_type_id tab tyname);
   440 
   441 fun get_node (gr, x) k = Graph.get_node gr k;
   442 fun add_edge e (gr, x) = (Graph.add_edge e gr, x);
   443 fun add_edge_acyclic e (gr, x) = (Graph.add_edge_acyclic e gr, x);
   444 fun del_nodes ks (gr, x) = (Graph.del_nodes ks gr, x);
   445 fun map_node k f (gr, x) = (Graph.map_node k f gr, x);
   446 fun new_node p (gr, x) = (Graph.new_node p gr, x);
   447 
   448 fun thyname_of thy f x = the (AList.lookup (op =) (f x) Markup.theory_nameN);
   449 
   450 fun thyname_of_type thy =
   451   thyname_of thy (Type.the_tags (Sign.tsig_of thy));
   452 
   453 fun thyname_of_const thy =
   454   thyname_of thy (Consts.the_tags (Sign.consts_of thy));
   455 
   456 fun rename_terms ts =
   457   let
   458     val names = List.foldr OldTerm.add_term_names
   459       (map (fst o fst) (rev (fold Term.add_vars ts []))) ts;
   460     val reserved = filter ML_Syntax.is_reserved names;
   461     val (illegal, alt_names) = split_list (map_filter (fn s =>
   462       let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
   463     val ps = (reserved @ illegal) ~~
   464       Name.variant_list names (map (suffix "'") reserved @ alt_names);
   465 
   466     fun rename_id s = AList.lookup (op =) ps s |> the_default s;
   467 
   468     fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
   469       | rename (Free (a, T)) = Free (rename_id a, T)
   470       | rename (Abs (s, T, t)) = Abs (s, T, rename t)
   471       | rename (t $ u) = rename t $ rename u
   472       | rename t = t;
   473   in
   474     map rename ts
   475   end;
   476 
   477 val rename_term = hd o rename_terms o single;
   478 
   479 
   480 (**** retrieve definition of constant ****)
   481 
   482 fun is_instance T1 T2 =
   483   Type.raw_instance (T1, if null (OldTerm.typ_tfrees T2) then T2 else Logic.varifyT T2);
   484 
   485 fun get_assoc_code thy (s, T) = Option.map snd (find_first (fn ((s', T'), _) =>
   486   s = s' andalso is_instance T T') (#consts (CodegenData.get thy)));
   487 
   488 fun get_aux_code xs = map_filter (fn (m, code) =>
   489   if m = "" orelse member (op =) (!mode) m then SOME code else NONE) xs;
   490 
   491 fun dest_prim_def t =
   492   let
   493     val (lhs, rhs) = Logic.dest_equals t;
   494     val (c, args) = strip_comb lhs;
   495     val (s, T) = dest_Const c
   496   in if forall is_Var args then SOME (s, (T, (args, rhs))) else NONE
   497   end handle TERM _ => NONE;
   498 
   499 fun mk_deftab thy =
   500   let
   501     val axmss = map (fn thy' => (Context.theory_name thy', Theory.axiom_table thy'))
   502       (thy :: Theory.ancestors_of thy);
   503     fun add_def thyname (name, t) = (case dest_prim_def t of
   504         NONE => I
   505       | SOME (s, (T, _)) => Symtab.map_default (s, [])
   506           (cons (T, (thyname, Thm.axiom thy name))));
   507   in
   508     fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
   509   end;
   510 
   511 fun prep_prim_def thy thm =
   512   let
   513     val prop = case preprocess thy [thm]
   514      of [thm'] => Thm.prop_of thm'
   515       | _ => error "mk_deftab: bad preprocessor"
   516   in ((Option.map o apsnd o apsnd)
   517     (fn (args, rhs) => split_last (rename_terms (args @ [rhs]))) o dest_prim_def) prop
   518   end;
   519 
   520 fun get_defn thy defs s T = (case Symtab.lookup defs s of
   521     NONE => NONE
   522   | SOME ds =>
   523       let val i = find_index (is_instance T o fst) ds
   524       in if i >= 0 then
   525           SOME (nth ds i, if length ds = 1 then NONE else SOME i)
   526         else NONE
   527       end);
   528 
   529 
   530 (**** invoke suitable code generator for term / type ****)
   531 
   532 fun codegen_error (gr, _) dep s =
   533   error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
   534 
   535 fun invoke_codegen thy defs dep module brack t gr = (case get_first
   536    (fn (_, f) => f thy defs dep module brack t gr) (#codegens (CodegenData.get thy)) of
   537       NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
   538         Syntax.string_of_term_global thy t)
   539     | SOME x => x);
   540 
   541 fun invoke_tycodegen thy defs dep module brack T gr = (case get_first
   542    (fn (_, f) => f thy defs dep module brack T gr ) (#tycodegens (CodegenData.get thy)) of
   543       NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
   544         Syntax.string_of_typ_global thy T)
   545     | SOME x => x);
   546 
   547 
   548 (**** code generator for mixfix expressions ****)
   549 
   550 fun parens p = Pretty.block [str "(", p, str ")"];
   551 
   552 fun pretty_fn [] p = [p]
   553   | pretty_fn (x::xs) p = str ("fn " ^ x ^ " =>") ::
   554       Pretty.brk 1 :: pretty_fn xs p;
   555 
   556 fun pretty_mixfix _ _ [] [] _ = []
   557   | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
   558       p :: pretty_mixfix module module' ms ps qs
   559   | pretty_mixfix module module' (Ignore :: ms) ps qs =
   560       pretty_mixfix module module' ms ps qs
   561   | pretty_mixfix module module' (Module :: ms) ps qs =
   562       (if module <> module'
   563        then cons (str (module' ^ ".")) else I)
   564       (pretty_mixfix module module' ms ps qs)
   565   | pretty_mixfix module module' (Pretty p :: ms) ps qs =
   566       p :: pretty_mixfix module module' ms ps qs
   567   | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
   568       q :: pretty_mixfix module module' ms ps qs;
   569 
   570 fun replace_quotes [] [] = []
   571   | replace_quotes xs (Arg :: ms) =
   572       Arg :: replace_quotes xs ms
   573   | replace_quotes xs (Ignore :: ms) =
   574       Ignore :: replace_quotes xs ms
   575   | replace_quotes xs (Module :: ms) =
   576       Module :: replace_quotes xs ms
   577   | replace_quotes xs (Pretty p :: ms) =
   578       Pretty p :: replace_quotes xs ms
   579   | replace_quotes (x::xs) (Quote _ :: ms) =
   580       Quote x :: replace_quotes xs ms;
   581 
   582 
   583 (**** default code generators ****)
   584 
   585 fun eta_expand t ts i =
   586   let
   587     val k = length ts;
   588     val Ts = Library.drop (k, binder_types (fastype_of t));
   589     val j = i - k
   590   in
   591     List.foldr (fn (T, t) => Abs ("x", T, t))
   592       (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
   593   end;
   594 
   595 fun mk_app _ p [] = p
   596   | mk_app brack p ps = if brack then
   597        Pretty.block (str "(" ::
   598          separate (Pretty.brk 1) (p :: ps) @ [str ")"])
   599      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   600 
   601 fun new_names t xs = Name.variant_list
   602   (union (op =) (map (fst o fst o dest_Var) (OldTerm.term_vars t))
   603     (OldTerm.add_term_names (t, ML_Syntax.reserved_names))) (map mk_id xs);
   604 
   605 fun new_name t x = hd (new_names t [x]);
   606 
   607 fun if_library x y = if member (op =) (!mode) "library" then x else y;
   608 
   609 fun default_codegen thy defs dep module brack t gr =
   610   let
   611     val (u, ts) = strip_comb t;
   612     fun codegens brack = fold_map (invoke_codegen thy defs dep module brack)
   613   in (case u of
   614       Var ((s, i), T) =>
   615         let
   616           val (ps, gr') = codegens true ts gr;
   617           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   618         in SOME (mk_app brack (str (s ^
   619            (if i=0 then "" else string_of_int i))) ps, gr'')
   620         end
   621 
   622     | Free (s, T) =>
   623         let
   624           val (ps, gr') = codegens true ts gr;
   625           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   626         in SOME (mk_app brack (str s) ps, gr'') end
   627 
   628     | Const (s, T) =>
   629       (case get_assoc_code thy (s, T) of
   630          SOME (ms, aux) =>
   631            let val i = num_args_of ms
   632            in if length ts < i then
   633                default_codegen thy defs dep module brack (eta_expand u ts i) gr 
   634              else
   635                let
   636                  val (ts1, ts2) = args_of ms ts;
   637                  val (ps1, gr1) = codegens false ts1 gr;
   638                  val (ps2, gr2) = codegens true ts2 gr1;
   639                  val (ps3, gr3) = codegens false (quotes_of ms) gr2;
   640                  val (_, gr4) = invoke_tycodegen thy defs dep module false
   641                    (funpow (length ts) (hd o tl o snd o dest_Type) T) gr3;
   642                  val (module', suffix) = (case get_defn thy defs s T of
   643                      NONE => (if_library (thyname_of_const thy s) module, "")
   644                    | SOME ((U, (module', _)), NONE) =>
   645                        (if_library module' module, "")
   646                    | SOME ((U, (module', _)), SOME i) =>
   647                        (if_library module' module, " def" ^ string_of_int i));
   648                  val node_id = s ^ suffix;
   649                  fun p module' = mk_app brack (Pretty.block
   650                    (pretty_mixfix module module' ms ps1 ps3)) ps2
   651                in SOME (case try (get_node gr4) node_id of
   652                    NONE => (case get_aux_code aux of
   653                        [] => (p module, gr4)
   654                      | xs => (p module', add_edge (node_id, dep) (new_node
   655                          (node_id, (NONE, module', cat_lines xs ^ "\n")) gr4)))
   656                  | SOME (_, module'', _) =>
   657                      (p module'', add_edge (node_id, dep) gr4))
   658                end
   659            end
   660        | NONE => (case get_defn thy defs s T of
   661            NONE => NONE
   662          | SOME ((U, (thyname, thm)), k) => (case prep_prim_def thy thm
   663             of SOME (_, (_, (args, rhs))) => let
   664                val module' = if_library thyname module;
   665                val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   666                val node_id = s ^ suffix;
   667                val ((ps, def_id), gr') = gr |> codegens true ts
   668                  ||>> mk_const_id module' (s ^ suffix);
   669                val p = mk_app brack (str (mk_qual_id module def_id)) ps
   670              in SOME (case try (get_node gr') node_id of
   671                  NONE =>
   672                    let
   673                      val _ = message ("expanding definition of " ^ s);
   674                      val (Ts, _) = strip_type U;
   675                      val (args', rhs') =
   676                        if not (null args) orelse null Ts then (args, rhs) else
   677                          let val v = Free (new_name rhs "x", hd Ts)
   678                          in ([v], betapply (rhs, v)) end;
   679                      val (p', gr1) = invoke_codegen thy defs node_id module' false
   680                        rhs' (add_edge (node_id, dep)
   681                           (new_node (node_id, (NONE, "", "")) gr'));
   682                      val (xs, gr2) = codegens false args' gr1;
   683                      val (_, gr3) = invoke_tycodegen thy defs dep module false T gr2;
   684                      val (ty, gr4) = invoke_tycodegen thy defs node_id module' false U gr3;
   685                    in (p, map_node node_id (K (NONE, module', string_of
   686                        (Pretty.block (separate (Pretty.brk 1)
   687                          (if null args' then
   688                             [str ("val " ^ snd def_id ^ " :"), ty]
   689                           else str ("fun " ^ snd def_id) :: xs) @
   690                         [str " =", Pretty.brk 1, p', str ";"])) ^ "\n\n")) gr4)
   691                    end
   692                | SOME _ => (p, add_edge (node_id, dep) gr'))
   693              end
   694              | NONE => NONE)))
   695 
   696     | Abs _ =>
   697       let
   698         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   699         val t = strip_abs_body u
   700         val bs' = new_names t bs;
   701         val (ps, gr1) = codegens true ts gr;
   702         val (p, gr2) = invoke_codegen thy defs dep module false
   703           (subst_bounds (map Free (rev (bs' ~~ Ts)), t)) gr1;
   704       in
   705         SOME (mk_app brack (Pretty.block (str "(" :: pretty_fn bs' p @
   706           [str ")"])) ps, gr2)
   707       end
   708 
   709     | _ => NONE)
   710   end;
   711 
   712 fun default_tycodegen thy defs dep module brack (TVar ((s, i), _)) gr =
   713       SOME (str (s ^ (if i = 0 then "" else string_of_int i)), gr)
   714   | default_tycodegen thy defs dep module brack (TFree (s, _)) gr =
   715       SOME (str s, gr)
   716   | default_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
   717       (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   718          NONE => NONE
   719        | SOME (ms, aux) =>
   720            let
   721              val (ps, gr') = fold_map
   722                (invoke_tycodegen thy defs dep module false)
   723                (fst (args_of ms Ts)) gr;
   724              val (qs, gr'') = fold_map
   725                (invoke_tycodegen thy defs dep module false)
   726                (quotes_of ms) gr';
   727              val module' = if_library (thyname_of_type thy s) module;
   728              val node_id = s ^ " (type)";
   729              fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   730            in SOME (case try (get_node gr'') node_id of
   731                NONE => (case get_aux_code aux of
   732                    [] => (p module', gr'')
   733                  | xs => (p module', snd (mk_type_id module' s
   734                        (add_edge (node_id, dep) (new_node (node_id,
   735                          (NONE, module', cat_lines xs ^ "\n")) gr'')))))
   736              | SOME (_, module'', _) =>
   737                  (p module'', add_edge (node_id, dep) gr''))
   738            end);
   739 
   740 fun mk_tuple [p] = p
   741   | mk_tuple ps = Pretty.block (str "(" ::
   742       flat (separate [str ",", Pretty.brk 1] (map single ps)) @ [str ")"]);
   743 
   744 fun mk_let bindings body =
   745   Pretty.blk (0, [str "let", Pretty.brk 1,
   746     Pretty.blk (0, separate Pretty.fbrk (map (fn (pat, rhs) =>
   747       Pretty.block [str "val ", pat, str " =", Pretty.brk 1,
   748       rhs, str ";"]) bindings)),
   749     Pretty.brk 1, str "in", Pretty.brk 1, body,
   750     Pretty.brk 1, str "end"]);
   751 
   752 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   753 
   754 fun add_to_module name s = AList.map_entry (op =) (name : string) (suffix s);
   755 
   756 fun output_code gr module xs =
   757   let
   758     val code = map_filter (fn s =>
   759       let val c as (_, module', _) = Graph.get_node gr s
   760       in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   761         (rev (Graph.all_preds gr xs));
   762     fun string_of_cycle (a :: b :: cs) =
   763           let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   764             if a = a' then Option.map (pair x)
   765               (find_first ((fn (_, b', _) => b' = b) o Graph.get_node gr)
   766                 (Graph.imm_succs gr x))
   767             else NONE) code
   768           in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   769       | string_of_cycle _ = ""
   770   in
   771     if module = "" then
   772       let
   773         val modules = distinct (op =) (map (#2 o snd) code);
   774         val mod_gr = fold_rev Graph.add_edge_acyclic
   775           (maps (fn (s, (_, module, _)) => map (pair module)
   776             (filter_out (fn s => s = module) (map (#2 o Graph.get_node gr)
   777               (Graph.imm_succs gr s)))) code)
   778           (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
   779         val modules' =
   780           rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   781       in
   782         List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   783           (map (rpair "") modules') code
   784       end handle Graph.CYCLES (cs :: _) =>
   785         error ("Cyclic dependency of modules:\n" ^ commas cs ^
   786           "\n" ^ string_of_cycle cs)
   787     else [(module, implode (map (#3 o snd) code))]
   788   end;
   789 
   790 fun gen_generate_code prep_term thy modules module xs =
   791   let
   792     val _ = (module <> "" orelse
   793         member (op =) (!mode) "library" andalso forall (fn (s, _) => s = "") xs)
   794       orelse error "missing module name";
   795     val graphs = get_modules thy;
   796     val defs = mk_deftab thy;
   797     val gr = new_node ("<Top>", (NONE, module, ""))
   798       (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   799         (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   800            module = module') (gr, gr'),
   801          (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   802            (map (fn s => case Symtab.lookup graphs s of
   803                 NONE => error ("Undefined code module: " ^ s)
   804               | SOME gr => gr) modules))
   805       handle Graph.DUP k => error ("Duplicate code for " ^ k);
   806     fun expand (t as Abs _) = t
   807       | expand t = (case fastype_of t of
   808           Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   809     val (ps, gr') = fold_map (fn (s, t) => fn gr => apfst (pair s)
   810       (invoke_codegen thy defs "<Top>" module false t gr))
   811         (map (apsnd (expand o preprocess_term thy o prep_term thy)) xs) gr;
   812     val code = map_filter
   813       (fn ("", _) => NONE
   814         | (s', p) => SOME (string_of (Pretty.block
   815           [str ("val " ^ s' ^ " ="), Pretty.brk 1, p, str ";"]))) ps;
   816     val code' = space_implode "\n\n" code ^ "\n\n";
   817     val code'' =
   818       map_filter (fn (name, s) =>
   819           if member (op =) (!mode) "library" andalso name = module andalso null code
   820           then NONE
   821           else SOME (name, mk_struct name s))
   822         ((if null code then I
   823           else add_to_module module code')
   824            (output_code (fst gr') (if_library "" module) ["<Top>"]))
   825   in
   826     (code'', del_nodes ["<Top>"] gr')
   827   end;
   828 
   829 val generate_code_i = gen_generate_code Sign.cert_term;
   830 val generate_code =
   831   gen_generate_code (Syntax.read_term o ProofContext.allow_dummies o ProofContext.init);
   832 
   833 
   834 (**** Reflection ****)
   835 
   836 val strip_tname = implode o tl o explode;
   837 
   838 fun pretty_list xs = Pretty.block (str "[" ::
   839   flat (separate [str ",", Pretty.brk 1] (map single xs)) @
   840   [str "]"]);
   841 
   842 fun mk_type p (TVar ((s, i), _)) = str
   843       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   844   | mk_type p (TFree (s, _)) = str (strip_tname s ^ "T")
   845   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   846       [str "Type", Pretty.brk 1, str ("(\"" ^ s ^ "\","),
   847        Pretty.brk 1, pretty_list (map (mk_type false) Ts), str ")"]);
   848 
   849 fun mk_term_of gr module p (TVar ((s, i), _)) = str
   850       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   851   | mk_term_of gr module p (TFree (s, _)) = str (strip_tname s ^ "F")
   852   | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   853       (Pretty.block (separate (Pretty.brk 1)
   854         (str (mk_qual_id module
   855           (get_type_id' (fn s' => "term_of_" ^ s') gr s)) ::
   856         maps (fn T =>
   857           [mk_term_of gr module true T, mk_type true T]) Ts)));
   858 
   859 
   860 (**** Test data generators ****)
   861 
   862 fun mk_gen gr module p xs a (TVar ((s, i), _)) = str
   863       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   864   | mk_gen gr module p xs a (TFree (s, _)) = str (strip_tname s ^ "G")
   865   | mk_gen gr module p xs a (Type (tyc as (s, Ts))) = (if p then parens else I)
   866       (Pretty.block (separate (Pretty.brk 1)
   867         (str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') gr s) ^
   868           (if member (op =) xs s then "'" else "")) ::
   869          (case tyc of
   870             ("fun", [T, U]) =>
   871               [mk_term_of gr module true T, mk_type true T,
   872                mk_gen gr module true xs a U, mk_type true U]
   873           | _ => maps (fn T =>
   874               [mk_gen gr module true xs a T, mk_type true T]) Ts) @
   875          (if member (op =) xs s then [str a] else []))));
   876 
   877 val test_fn : (int -> term list option) Unsynchronized.ref =
   878   Unsynchronized.ref (fn _ => NONE);
   879 
   880 fun test_term ctxt t =
   881   let
   882     val thy = ProofContext.theory_of ctxt;
   883     val (code, gr) = setmp_CRITICAL mode ["term_of", "test"]
   884       (generate_code_i thy [] "Generated") [("testf", t)];
   885     val Ts = map snd (fst (strip_abs t));
   886     val args = map_index (fn (i, T) => ("arg" ^ string_of_int i, T)) Ts;
   887     val s = "structure TestTerm =\nstruct\n\n" ^
   888       cat_lines (map snd code) ^
   889       "\nopen Generated;\n\n" ^ string_of
   890         (Pretty.block [str "val () = Codegen.test_fn :=",
   891           Pretty.brk 1, str ("(fn i =>"), Pretty.brk 1,
   892           mk_let (map (fn (s, T) =>
   893               (mk_tuple [str s, str (s ^ "_t")],
   894                Pretty.block [mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   895                  str "i"])) args)
   896             (Pretty.block [str "if ",
   897               mk_app false (str "testf") (map (str o fst) args),
   898               Pretty.brk 1, str "then NONE",
   899               Pretty.brk 1, str "else ",
   900               Pretty.block [str "SOME ", Pretty.block (str "[" ::
   901                 Pretty.commas (map (fn (s, _) => str (s ^ "_t ()")) args) @
   902                   [str "]"])]]),
   903           str ");"]) ^
   904       "\n\nend;\n";
   905     val _ = ML_Context.eval_in (SOME ctxt) false Position.none s;
   906   in ! test_fn end;
   907 
   908 
   909 
   910 (**** Evaluator for terms ****)
   911 
   912 val eval_result = Unsynchronized.ref (fn () => Bound 0);
   913 
   914 fun eval_term thy t =
   915   let
   916     val ctxt = ProofContext.init thy;
   917     val e =
   918       let
   919         val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
   920           error "Term to be evaluated contains type variables";
   921         val _ = (null (Term.add_vars t []) andalso null (Term.add_frees t [])) orelse
   922           error "Term to be evaluated contains variables";
   923         val (code, gr) = setmp_CRITICAL mode ["term_of"]
   924           (generate_code_i thy [] "Generated")
   925           [("result", Abs ("x", TFree ("'a", []), t))];
   926         val s = "structure EvalTerm =\nstruct\n\n" ^
   927           cat_lines (map snd code) ^
   928           "\nopen Generated;\n\n" ^ string_of
   929             (Pretty.block [str "val () = Codegen.eval_result := (fn () =>",
   930               Pretty.brk 1,
   931               mk_app false (mk_term_of gr "Generated" false (fastype_of t))
   932                 [str "(result ())"],
   933               str ");"]) ^
   934           "\n\nend;\n";
   935         val _ = NAMED_CRITICAL "codegen" (fn () =>
   936           ML_Context.eval_in (SOME ctxt) false Position.none s);
   937       in !eval_result end;
   938   in e () end;
   939 
   940 val (_, evaluation_conv) = Context.>>> (Context.map_theory_result
   941   (Thm.add_oracle (Binding.name "evaluation", fn ct =>
   942     let
   943       val thy = Thm.theory_of_cterm ct;
   944       val t = Thm.term_of ct;
   945     in Thm.cterm_of thy (Logic.mk_equals (t, eval_term thy t)) end)));
   946 
   947 
   948 (**** Interface ****)
   949 
   950 fun parse_mixfix rd s =
   951   (case Scan.finite Symbol.stopper (Scan.repeat
   952      (   $$ "_" >> K Arg
   953       || $$ "?" >> K Ignore
   954       || $$ "\\<module>" >> K Module
   955       || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
   956       || $$ "{" |-- $$ "*" |-- Scan.repeat1
   957            (   $$ "'" |-- Scan.one Symbol.is_regular
   958             || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.is_regular)) --|
   959          $$ "*" --| $$ "}" >> (Quote o rd o implode)
   960       || Scan.repeat1
   961            (   $$ "'" |-- Scan.one Symbol.is_regular
   962             || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
   963                  (Scan.one Symbol.is_regular)) >> (Pretty o str o implode)))
   964        (Symbol.explode s) of
   965      (p, []) => p
   966    | _ => error ("Malformed annotation: " ^ quote s));
   967 
   968 
   969 structure P = OuterParse and K = OuterKeyword;
   970 
   971 val _ = List.app OuterKeyword.keyword ["attach", "file", "contains"];
   972 
   973 fun strip_whitespace s = implode (fst (take_suffix (fn c => c = "\n" orelse c = " ")
   974   (snd (take_prefix (fn c => c = "\n" orelse c = " ") (explode s))))) ^ "\n";
   975 
   976 val parse_attach = Scan.repeat (P.$$$ "attach" |--
   977   Scan.optional (P.$$$ "(" |-- P.xname --| P.$$$ ")") "" --
   978     (P.verbatim >> strip_whitespace));
   979 
   980 val _ =
   981   OuterSyntax.command "types_code"
   982   "associate types with target language types" K.thy_decl
   983     (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
   984      (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
   985        (fn ((name, mfx), aux) => (name, (parse_mixfix
   986          (Syntax.read_typ_global thy) mfx, aux)))) xs thy)));
   987 
   988 val _ =
   989   OuterSyntax.command "consts_code"
   990   "associate constants with target language code" K.thy_decl
   991     (Scan.repeat1
   992        (P.term --|
   993         P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
   994      (fn xs => Toplevel.theory (fn thy => fold (assoc_const o
   995        (fn ((const, mfx), aux) =>
   996          (const, (parse_mixfix (Syntax.read_term_global thy) mfx, aux)))) xs thy)));
   997 
   998 fun parse_code lib =
   999   Scan.optional (P.$$$ "(" |-- P.enum "," P.xname --| P.$$$ ")") (!mode) --
  1000   (if lib then Scan.optional P.name "" else P.name) --
  1001   Scan.option (P.$$$ "file" |-- P.name) --
  1002   (if lib then Scan.succeed []
  1003    else Scan.optional (P.$$$ "imports" |-- Scan.repeat1 P.name) []) --|
  1004   P.$$$ "contains" --
  1005   (   Scan.repeat1 (P.name --| P.$$$ "=" -- P.term)
  1006    || Scan.repeat1 (P.term >> pair "")) >>
  1007   (fn ((((mode', module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
  1008     let
  1009       val mode'' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode');
  1010       val (code, gr) = setmp_CRITICAL mode mode'' (generate_code thy modules module) xs;
  1011       val thy' = thy |> Context.theory_map (ML_Context.exec (fn () =>
  1012         (case opt_fname of
  1013           NONE => ML_Context.eval false Position.none (cat_lines (map snd code))
  1014         | SOME fname =>
  1015             if lib then app (fn (name, s) => File.write
  1016                 (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
  1017               (("ROOT", implode (map (fn (name, _) =>
  1018                   "use \"" ^ name ^ ".ML\";\n") code)) :: code)
  1019             else File.write (Path.explode fname) (snd (hd code)))));
  1020     in
  1021       if lib then thy'
  1022       else map_modules (Symtab.update (module, gr)) thy'
  1023     end));
  1024 
  1025 val setup = add_codegen "default" default_codegen
  1026   #> add_tycodegen "default" default_tycodegen
  1027   #> add_preprocessor unfold_preprocessor;
  1028 
  1029 val _ =
  1030   OuterSyntax.command "code_library"
  1031     "generates code for terms (one structure for each theory)" K.thy_decl
  1032     (parse_code true);
  1033 
  1034 val _ =
  1035   OuterSyntax.command "code_module"
  1036     "generates code for terms (single structure, incremental)" K.thy_decl
  1037     (parse_code false);
  1038 
  1039 end;