src/Pure/codegen.ML
author wenzelm
Thu Oct 01 23:27:05 2009 +0200 (2009-10-01)
changeset 32843 c8f5a7c8353f
parent 32738 15bb09ca0378
child 32952 aeb1e44fbc19
permissions -rw-r--r--
moved cache_conv to src/Pure/conv.ML, use Thm.cterm_cache;
     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 (!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 = setmp quick_and_dirty true (SkipProof.make_thm thy)
   284       (Logic.mk_equals (x, t));
   285     fun err () = error "preprocess_term: bad preprocessor"
   286   in case map prop_of (preprocess thy [eq]) of
   287       [Const ("==", _) $ x' $ t'] => if x = x' then t' else err ()
   288     | _ => err ()
   289   end;
   290 
   291 structure UnfoldData = TheoryDataFun
   292 (
   293   type T = simpset;
   294   val empty = empty_ss;
   295   val copy = I;
   296   val extend = I;
   297   fun merge _ = merge_ss;
   298 );
   299 
   300 val map_unfold = UnfoldData.map;
   301 val add_unfold = map_unfold o MetaSimplifier.add_simp;
   302 val del_unfold = map_unfold o MetaSimplifier.del_simp;
   303 
   304 fun unfold_preprocessor thy =
   305   let val ss = Simplifier.theory_context thy (UnfoldData.get thy)
   306   in map (Thm.transfer thy #> Simplifier.full_simplify ss) end;
   307 
   308 
   309 (**** associate constants with target language code ****)
   310 
   311 fun gen_assoc_const prep_const (raw_const, syn) thy =
   312   let
   313     val {codegens, tycodegens, consts, types, preprocs, modules} =
   314       CodegenData.get thy;
   315     val (cname, T) = prep_const thy raw_const;
   316   in
   317     if num_args_of (fst syn) > length (binder_types T) then
   318       error ("More arguments than in corresponding type of " ^ cname)
   319     else case AList.lookup (op =) consts (cname, T) of
   320       NONE => CodegenData.put {codegens = codegens,
   321         tycodegens = tycodegens,
   322         consts = ((cname, T), syn) :: consts,
   323         types = types, preprocs = preprocs,
   324         modules = modules} thy
   325     | SOME _ => error ("Constant " ^ cname ^ " already associated with code")
   326   end;
   327 
   328 val assoc_const_i = gen_assoc_const (K I);
   329 val assoc_const = gen_assoc_const Code.read_bare_const;
   330 
   331 
   332 (**** associate types with target language types ****)
   333 
   334 fun assoc_type (s, syn) thy =
   335   let
   336     val {codegens, tycodegens, consts, types, preprocs, modules} =
   337       CodegenData.get thy;
   338     val tc = Sign.intern_type thy s;
   339   in
   340     case Symtab.lookup (snd (#types (Type.rep_tsig (Sign.tsig_of thy)))) tc of
   341       SOME ((Type.LogicalType i, _), _) =>
   342         if num_args_of (fst syn) > i then
   343           error ("More arguments than corresponding type constructor " ^ s)
   344         else (case AList.lookup (op =) types tc of
   345           NONE => CodegenData.put {codegens = codegens,
   346             tycodegens = tycodegens, consts = consts,
   347             types = (tc, syn) :: types,
   348             preprocs = preprocs, modules = modules} thy
   349         | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
   350     | _ => error ("Not a type constructor: " ^ s)
   351   end;
   352 
   353 fun get_assoc_type thy = AList.lookup (op =) ((#types o CodegenData.get) thy);
   354 
   355 
   356 (**** make valid ML identifiers ****)
   357 
   358 fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
   359   Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
   360 
   361 fun dest_sym s = (case split_last (snd (take_prefix (fn c => c = "\\") (explode s))) of
   362     ("<" :: "^" :: xs, ">") => (true, implode xs)
   363   | ("<" :: xs, ">") => (false, implode xs)
   364   | _ => sys_error "dest_sym");
   365 
   366 fun mk_id s = if s = "" then "" else
   367   let
   368     fun check_str [] = []
   369       | check_str xs = (case take_prefix is_ascii_letdig xs of
   370           ([], " " :: zs) => check_str zs
   371         | ([], z :: zs) =>
   372           if size z = 1 then string_of_int (ord z) :: check_str zs
   373           else (case dest_sym z of
   374               (true, "isub") => check_str zs
   375             | (true, "isup") => "" :: check_str zs
   376             | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
   377         | (ys, zs) => implode ys :: check_str zs);
   378     val s' = space_implode "_" (maps (check_str o Symbol.explode) (Long_Name.explode s))
   379   in
   380     if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
   381   end;
   382 
   383 fun mk_long_id (p as (tab, used)) module s =
   384   let
   385     fun find_name [] = sys_error "mk_long_id"
   386       | find_name (ys :: yss) =
   387           let
   388             val s' = Long_Name.implode ys
   389             val s'' = Long_Name.append module s'
   390           in case Symtab.lookup used s'' of
   391               NONE => ((module, s'),
   392                 (Symtab.update_new (s, (module, s')) tab,
   393                  Symtab.update_new (s'', ()) used))
   394             | SOME _ => find_name yss
   395           end
   396   in case Symtab.lookup tab s of
   397       NONE => find_name (Library.suffixes1 (Long_Name.explode s))
   398     | SOME name => (name, p)
   399   end;
   400 
   401 (* module:  module name for caller                                        *)
   402 (* module': module name for callee                                        *)
   403 (* if caller and callee reside in different modules, use qualified access *)
   404 
   405 fun mk_qual_id module (module', s) =
   406   if module = module' orelse module' = "" then s else module' ^ "." ^ s;
   407 
   408 fun mk_const_id module cname (gr, (tab1, tab2)) =
   409   let
   410     val ((module, s), tab1') = mk_long_id tab1 module cname
   411     val s' = mk_id s;
   412     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   413   in (((module, s'')), (gr, (tab1', tab2))) end;
   414 
   415 fun get_const_id (gr, (tab1, tab2)) cname =
   416   case Symtab.lookup (fst tab1) cname of
   417     NONE => error ("get_const_id: no such constant: " ^ quote cname)
   418   | SOME (module, s) =>
   419       let
   420         val s' = mk_id s;
   421         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   422       in (module, s'') end;
   423 
   424 fun mk_type_id module tyname (gr, (tab1, tab2)) =
   425   let
   426     val ((module, s), tab2') = mk_long_id tab2 module tyname
   427     val s' = mk_id s;
   428     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   429   in ((module, s''), (gr, (tab1, tab2'))) end;
   430 
   431 fun get_type_id (gr, (tab1, tab2)) tyname =
   432   case Symtab.lookup (fst tab2) tyname of
   433     NONE => error ("get_type_id: no such type: " ^ quote tyname)
   434   | SOME (module, s) =>
   435       let
   436         val s' = mk_id s;
   437         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   438       in (module, s'') end;
   439 
   440 fun get_type_id' f tab tyname = apsnd f (get_type_id tab tyname);
   441 
   442 fun get_node (gr, x) k = Graph.get_node gr k;
   443 fun add_edge e (gr, x) = (Graph.add_edge e gr, x);
   444 fun add_edge_acyclic e (gr, x) = (Graph.add_edge_acyclic e gr, x);
   445 fun del_nodes ks (gr, x) = (Graph.del_nodes ks gr, x);
   446 fun map_node k f (gr, x) = (Graph.map_node k f gr, x);
   447 fun new_node p (gr, x) = (Graph.new_node p gr, x);
   448 
   449 fun thyname_of thy f x = the (AList.lookup (op =) (f x) Markup.theory_nameN);
   450 
   451 fun thyname_of_type thy =
   452   thyname_of thy (Type.the_tags (Sign.tsig_of thy));
   453 
   454 fun thyname_of_const thy =
   455   thyname_of thy (Consts.the_tags (Sign.consts_of thy));
   456 
   457 fun rename_terms ts =
   458   let
   459     val names = List.foldr OldTerm.add_term_names
   460       (map (fst o fst) (rev (fold Term.add_vars ts []))) ts;
   461     val reserved = filter ML_Syntax.is_reserved names;
   462     val (illegal, alt_names) = split_list (map_filter (fn s =>
   463       let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
   464     val ps = (reserved @ illegal) ~~
   465       Name.variant_list names (map (suffix "'") reserved @ alt_names);
   466 
   467     fun rename_id s = AList.lookup (op =) ps s |> the_default s;
   468 
   469     fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
   470       | rename (Free (a, T)) = Free (rename_id a, T)
   471       | rename (Abs (s, T, t)) = Abs (s, T, rename t)
   472       | rename (t $ u) = rename t $ rename u
   473       | rename t = t;
   474   in
   475     map rename ts
   476   end;
   477 
   478 val rename_term = hd o rename_terms o single;
   479 
   480 
   481 (**** retrieve definition of constant ****)
   482 
   483 fun is_instance T1 T2 =
   484   Type.raw_instance (T1, if null (OldTerm.typ_tfrees T2) then T2 else Logic.varifyT T2);
   485 
   486 fun get_assoc_code thy (s, T) = Option.map snd (find_first (fn ((s', T'), _) =>
   487   s = s' andalso is_instance T T') (#consts (CodegenData.get thy)));
   488 
   489 fun get_aux_code xs = map_filter (fn (m, code) =>
   490   if m = "" orelse member (op =) (!mode) m then SOME code else NONE) xs;
   491 
   492 fun dest_prim_def t =
   493   let
   494     val (lhs, rhs) = Logic.dest_equals t;
   495     val (c, args) = strip_comb lhs;
   496     val (s, T) = dest_Const c
   497   in if forall is_Var args then SOME (s, (T, (args, rhs))) else NONE
   498   end handle TERM _ => NONE;
   499 
   500 fun mk_deftab thy =
   501   let
   502     val axmss = map (fn thy' => (Context.theory_name thy', Theory.axiom_table thy'))
   503       (thy :: Theory.ancestors_of thy);
   504     fun prep_def def = (case preprocess thy [def] of
   505       [def'] => prop_of def' | _ => error "mk_deftab: bad preprocessor");
   506     fun add_def thyname (name, t) = (case dest_prim_def t of
   507         NONE => I
   508       | SOME (s, (T, _)) => Symtab.map_default (s, [])
   509           (cons (T, (thyname, Thm.axiom thy name))));
   510   in
   511     fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
   512   end;
   513 
   514 fun prep_prim_def thy thm =
   515   let
   516     val prop = case preprocess thy [thm]
   517      of [thm'] => Thm.prop_of thm'
   518       | _ => error "mk_deftab: bad preprocessor"
   519   in ((Option.map o apsnd o apsnd)
   520     (fn (args, rhs) => split_last (rename_terms (args @ [rhs]))) o dest_prim_def) prop
   521   end;
   522 
   523 fun get_defn thy defs s T = (case Symtab.lookup defs s of
   524     NONE => NONE
   525   | SOME ds =>
   526       let val i = find_index (is_instance T o fst) ds
   527       in if i >= 0 then
   528           SOME (nth ds i, if length ds = 1 then NONE else SOME i)
   529         else NONE
   530       end);
   531 
   532 
   533 (**** invoke suitable code generator for term / type ****)
   534 
   535 fun codegen_error (gr, _) dep s =
   536   error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
   537 
   538 fun invoke_codegen thy defs dep module brack t gr = (case get_first
   539    (fn (_, f) => f thy defs dep module brack t gr) (#codegens (CodegenData.get thy)) of
   540       NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
   541         Syntax.string_of_term_global thy t)
   542     | SOME x => x);
   543 
   544 fun invoke_tycodegen thy defs dep module brack T gr = (case get_first
   545    (fn (_, f) => f thy defs dep module brack T gr ) (#tycodegens (CodegenData.get thy)) of
   546       NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
   547         Syntax.string_of_typ_global thy T)
   548     | SOME x => x);
   549 
   550 
   551 (**** code generator for mixfix expressions ****)
   552 
   553 fun parens p = Pretty.block [str "(", p, str ")"];
   554 
   555 fun pretty_fn [] p = [p]
   556   | pretty_fn (x::xs) p = str ("fn " ^ x ^ " =>") ::
   557       Pretty.brk 1 :: pretty_fn xs p;
   558 
   559 fun pretty_mixfix _ _ [] [] _ = []
   560   | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
   561       p :: pretty_mixfix module module' ms ps qs
   562   | pretty_mixfix module module' (Ignore :: ms) ps qs =
   563       pretty_mixfix module module' ms ps qs
   564   | pretty_mixfix module module' (Module :: ms) ps qs =
   565       (if module <> module'
   566        then cons (str (module' ^ ".")) else I)
   567       (pretty_mixfix module module' ms ps qs)
   568   | pretty_mixfix module module' (Pretty p :: ms) ps qs =
   569       p :: pretty_mixfix module module' ms ps qs
   570   | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
   571       q :: pretty_mixfix module module' ms ps qs;
   572 
   573 fun replace_quotes [] [] = []
   574   | replace_quotes xs (Arg :: ms) =
   575       Arg :: replace_quotes xs ms
   576   | replace_quotes xs (Ignore :: ms) =
   577       Ignore :: replace_quotes xs ms
   578   | replace_quotes xs (Module :: ms) =
   579       Module :: replace_quotes xs ms
   580   | replace_quotes xs (Pretty p :: ms) =
   581       Pretty p :: replace_quotes xs ms
   582   | replace_quotes (x::xs) (Quote _ :: ms) =
   583       Quote x :: replace_quotes xs ms;
   584 
   585 
   586 (**** default code generators ****)
   587 
   588 fun eta_expand t ts i =
   589   let
   590     val k = length ts;
   591     val Ts = Library.drop (k, binder_types (fastype_of t));
   592     val j = i - k
   593   in
   594     List.foldr (fn (T, t) => Abs ("x", T, t))
   595       (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
   596   end;
   597 
   598 fun mk_app _ p [] = p
   599   | mk_app brack p ps = if brack then
   600        Pretty.block (str "(" ::
   601          separate (Pretty.brk 1) (p :: ps) @ [str ")"])
   602      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   603 
   604 fun new_names t xs = Name.variant_list
   605   (map (fst o fst o dest_Var) (OldTerm.term_vars t) union
   606     OldTerm.add_term_names (t, ML_Syntax.reserved_names)) (map mk_id xs);
   607 
   608 fun new_name t x = hd (new_names t [x]);
   609 
   610 fun if_library x y = if member (op =) (!mode) "library" then x else y;
   611 
   612 fun default_codegen thy defs dep module brack t gr =
   613   let
   614     val (u, ts) = strip_comb t;
   615     fun codegens brack = fold_map (invoke_codegen thy defs dep module brack)
   616   in (case u of
   617       Var ((s, i), T) =>
   618         let
   619           val (ps, gr') = codegens true ts gr;
   620           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   621         in SOME (mk_app brack (str (s ^
   622            (if i=0 then "" else string_of_int i))) ps, gr'')
   623         end
   624 
   625     | Free (s, T) =>
   626         let
   627           val (ps, gr') = codegens true ts gr;
   628           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   629         in SOME (mk_app brack (str s) ps, gr'') end
   630 
   631     | Const (s, T) =>
   632       (case get_assoc_code thy (s, T) of
   633          SOME (ms, aux) =>
   634            let val i = num_args_of ms
   635            in if length ts < i then
   636                default_codegen thy defs dep module brack (eta_expand u ts i) gr 
   637              else
   638                let
   639                  val (ts1, ts2) = args_of ms ts;
   640                  val (ps1, gr1) = codegens false ts1 gr;
   641                  val (ps2, gr2) = codegens true ts2 gr1;
   642                  val (ps3, gr3) = codegens false (quotes_of ms) gr2;
   643                  val (_, gr4) = invoke_tycodegen thy defs dep module false
   644                    (funpow (length ts) (hd o tl o snd o dest_Type) T) gr3;
   645                  val (module', suffix) = (case get_defn thy defs s T of
   646                      NONE => (if_library (thyname_of_const thy s) module, "")
   647                    | SOME ((U, (module', _)), NONE) =>
   648                        (if_library module' module, "")
   649                    | SOME ((U, (module', _)), SOME i) =>
   650                        (if_library module' module, " def" ^ string_of_int i));
   651                  val node_id = s ^ suffix;
   652                  fun p module' = mk_app brack (Pretty.block
   653                    (pretty_mixfix module module' ms ps1 ps3)) ps2
   654                in SOME (case try (get_node gr4) node_id of
   655                    NONE => (case get_aux_code aux of
   656                        [] => (p module, gr4)
   657                      | xs => (p module', add_edge (node_id, dep) (new_node
   658                          (node_id, (NONE, module', cat_lines xs ^ "\n")) gr4)))
   659                  | SOME (_, module'', _) =>
   660                      (p module'', add_edge (node_id, dep) gr4))
   661                end
   662            end
   663        | NONE => (case get_defn thy defs s T of
   664            NONE => NONE
   665          | SOME ((U, (thyname, thm)), k) => (case prep_prim_def thy thm
   666             of SOME (_, (_, (args, rhs))) => let
   667                val module' = if_library thyname module;
   668                val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   669                val node_id = s ^ suffix;
   670                val ((ps, def_id), gr') = gr |> codegens true ts
   671                  ||>> mk_const_id module' (s ^ suffix);
   672                val p = mk_app brack (str (mk_qual_id module def_id)) ps
   673              in SOME (case try (get_node gr') node_id of
   674                  NONE =>
   675                    let
   676                      val _ = message ("expanding definition of " ^ s);
   677                      val (Ts, _) = strip_type U;
   678                      val (args', rhs') =
   679                        if not (null args) orelse null Ts then (args, rhs) else
   680                          let val v = Free (new_name rhs "x", hd Ts)
   681                          in ([v], betapply (rhs, v)) end;
   682                      val (p', gr1) = invoke_codegen thy defs node_id module' false
   683                        rhs' (add_edge (node_id, dep)
   684                           (new_node (node_id, (NONE, "", "")) gr'));
   685                      val (xs, gr2) = codegens false args' gr1;
   686                      val (_, gr3) = invoke_tycodegen thy defs dep module false T gr2;
   687                      val (ty, gr4) = invoke_tycodegen thy defs node_id module' false U gr3;
   688                    in (p, map_node node_id (K (NONE, module', string_of
   689                        (Pretty.block (separate (Pretty.brk 1)
   690                          (if null args' then
   691                             [str ("val " ^ snd def_id ^ " :"), ty]
   692                           else str ("fun " ^ snd def_id) :: xs) @
   693                         [str " =", Pretty.brk 1, p', str ";"])) ^ "\n\n")) gr4)
   694                    end
   695                | SOME _ => (p, add_edge (node_id, dep) gr'))
   696              end
   697              | NONE => NONE)))
   698 
   699     | Abs _ =>
   700       let
   701         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   702         val t = strip_abs_body u
   703         val bs' = new_names t bs;
   704         val (ps, gr1) = codegens true ts gr;
   705         val (p, gr2) = invoke_codegen thy defs dep module false
   706           (subst_bounds (map Free (rev (bs' ~~ Ts)), t)) gr1;
   707       in
   708         SOME (mk_app brack (Pretty.block (str "(" :: pretty_fn bs' p @
   709           [str ")"])) ps, gr2)
   710       end
   711 
   712     | _ => NONE)
   713   end;
   714 
   715 fun default_tycodegen thy defs dep module brack (TVar ((s, i), _)) gr =
   716       SOME (str (s ^ (if i = 0 then "" else string_of_int i)), gr)
   717   | default_tycodegen thy defs dep module brack (TFree (s, _)) gr =
   718       SOME (str s, gr)
   719   | default_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
   720       (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   721          NONE => NONE
   722        | SOME (ms, aux) =>
   723            let
   724              val (ps, gr') = fold_map
   725                (invoke_tycodegen thy defs dep module false)
   726                (fst (args_of ms Ts)) gr;
   727              val (qs, gr'') = fold_map
   728                (invoke_tycodegen thy defs dep module false)
   729                (quotes_of ms) gr';
   730              val module' = if_library (thyname_of_type thy s) module;
   731              val node_id = s ^ " (type)";
   732              fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   733            in SOME (case try (get_node gr'') node_id of
   734                NONE => (case get_aux_code aux of
   735                    [] => (p module', gr'')
   736                  | xs => (p module', snd (mk_type_id module' s
   737                        (add_edge (node_id, dep) (new_node (node_id,
   738                          (NONE, module', cat_lines xs ^ "\n")) gr'')))))
   739              | SOME (_, module'', _) =>
   740                  (p module'', add_edge (node_id, dep) gr''))
   741            end);
   742 
   743 fun mk_tuple [p] = p
   744   | mk_tuple ps = Pretty.block (str "(" ::
   745       List.concat (separate [str ",", Pretty.brk 1] (map single ps)) @
   746         [str ")"]);
   747 
   748 fun mk_let bindings body =
   749   Pretty.blk (0, [str "let", Pretty.brk 1,
   750     Pretty.blk (0, separate Pretty.fbrk (map (fn (pat, rhs) =>
   751       Pretty.block [str "val ", pat, str " =", Pretty.brk 1,
   752       rhs, str ";"]) bindings)),
   753     Pretty.brk 1, str "in", Pretty.brk 1, body,
   754     Pretty.brk 1, str "end"]);
   755 
   756 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   757 
   758 fun add_to_module name s = AList.map_entry (op =) (name : string) (suffix s);
   759 
   760 fun output_code gr module xs =
   761   let
   762     val code = map_filter (fn s =>
   763       let val c as (_, module', _) = Graph.get_node gr s
   764       in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   765         (rev (Graph.all_preds gr xs));
   766     fun string_of_cycle (a :: b :: cs) =
   767           let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   768             if a = a' then Option.map (pair x)
   769               (find_first ((fn (_, b', _) => b' = b) o Graph.get_node gr)
   770                 (Graph.imm_succs gr x))
   771             else NONE) code
   772           in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   773       | string_of_cycle _ = ""
   774   in
   775     if module = "" then
   776       let
   777         val modules = distinct (op =) (map (#2 o snd) code);
   778         val mod_gr = fold_rev Graph.add_edge_acyclic
   779           (maps (fn (s, (_, module, _)) => map (pair module)
   780             (filter_out (fn s => s = module) (map (#2 o Graph.get_node gr)
   781               (Graph.imm_succs gr s)))) code)
   782           (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
   783         val modules' =
   784           rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   785       in
   786         List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   787           (map (rpair "") modules') code
   788       end handle Graph.CYCLES (cs :: _) =>
   789         error ("Cyclic dependency of modules:\n" ^ commas cs ^
   790           "\n" ^ string_of_cycle cs)
   791     else [(module, implode (map (#3 o snd) code))]
   792   end;
   793 
   794 fun gen_generate_code prep_term thy modules module xs =
   795   let
   796     val _ = (module <> "" orelse
   797         member (op =) (!mode) "library" andalso forall (fn (s, _) => s = "") xs)
   798       orelse error "missing module name";
   799     val graphs = get_modules thy;
   800     val defs = mk_deftab thy;
   801     val gr = new_node ("<Top>", (NONE, module, ""))
   802       (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   803         (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   804            module = module') (gr, gr'),
   805          (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   806            (map (fn s => case Symtab.lookup graphs s of
   807                 NONE => error ("Undefined code module: " ^ s)
   808               | SOME gr => gr) modules))
   809       handle Graph.DUP k => error ("Duplicate code for " ^ k);
   810     fun expand (t as Abs _) = t
   811       | expand t = (case fastype_of t of
   812           Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   813     val (ps, gr') = fold_map (fn (s, t) => fn gr => apfst (pair s)
   814       (invoke_codegen thy defs "<Top>" module false t gr))
   815         (map (apsnd (expand o preprocess_term thy o prep_term thy)) xs) gr;
   816     val code = map_filter
   817       (fn ("", _) => NONE
   818         | (s', p) => SOME (string_of (Pretty.block
   819           [str ("val " ^ s' ^ " ="), Pretty.brk 1, p, str ";"]))) ps;
   820     val code' = space_implode "\n\n" code ^ "\n\n";
   821     val code'' =
   822       map_filter (fn (name, s) =>
   823           if member (op =) (!mode) "library" andalso name = module andalso null code
   824           then NONE
   825           else SOME (name, mk_struct name s))
   826         ((if null code then I
   827           else add_to_module module code')
   828            (output_code (fst gr') (if_library "" module) ["<Top>"]))
   829   in
   830     (code'', del_nodes ["<Top>"] gr')
   831   end;
   832 
   833 val generate_code_i = gen_generate_code Sign.cert_term;
   834 val generate_code =
   835   gen_generate_code (Syntax.read_term o ProofContext.allow_dummies o ProofContext.init);
   836 
   837 
   838 (**** Reflection ****)
   839 
   840 val strip_tname = implode o tl o explode;
   841 
   842 fun pretty_list xs = Pretty.block (str "[" ::
   843   flat (separate [str ",", Pretty.brk 1] (map single xs)) @
   844   [str "]"]);
   845 
   846 fun mk_type p (TVar ((s, i), _)) = str
   847       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   848   | mk_type p (TFree (s, _)) = str (strip_tname s ^ "T")
   849   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   850       [str "Type", Pretty.brk 1, str ("(\"" ^ s ^ "\","),
   851        Pretty.brk 1, pretty_list (map (mk_type false) Ts), str ")"]);
   852 
   853 fun mk_term_of gr module p (TVar ((s, i), _)) = str
   854       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   855   | mk_term_of gr module p (TFree (s, _)) = str (strip_tname s ^ "F")
   856   | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   857       (Pretty.block (separate (Pretty.brk 1)
   858         (str (mk_qual_id module
   859           (get_type_id' (fn s' => "term_of_" ^ s') gr s)) ::
   860         maps (fn T =>
   861           [mk_term_of gr module true T, mk_type true T]) Ts)));
   862 
   863 
   864 (**** Test data generators ****)
   865 
   866 fun mk_gen gr module p xs a (TVar ((s, i), _)) = str
   867       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   868   | mk_gen gr module p xs a (TFree (s, _)) = str (strip_tname s ^ "G")
   869   | mk_gen gr module p xs a (Type (tyc as (s, Ts))) = (if p then parens else I)
   870       (Pretty.block (separate (Pretty.brk 1)
   871         (str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') gr s) ^
   872           (if member (op =) xs s then "'" else "")) ::
   873          (case tyc of
   874             ("fun", [T, U]) =>
   875               [mk_term_of gr module true T, mk_type true T,
   876                mk_gen gr module true xs a U, mk_type true U]
   877           | _ => maps (fn T =>
   878               [mk_gen gr module true xs a T, mk_type true T]) Ts) @
   879          (if member (op =) xs s then [str a] else []))));
   880 
   881 val test_fn : (int -> term list option) Unsynchronized.ref =
   882   Unsynchronized.ref (fn _ => NONE);
   883 
   884 fun test_term ctxt t =
   885   let
   886     val thy = ProofContext.theory_of ctxt;
   887     val (code, gr) = setmp mode ["term_of", "test"]
   888       (generate_code_i thy [] "Generated") [("testf", t)];
   889     val Ts = map snd (fst (strip_abs t));
   890     val args = map_index (fn (i, T) => ("arg" ^ string_of_int i, T)) Ts;
   891     val s = "structure TestTerm =\nstruct\n\n" ^
   892       cat_lines (map snd code) ^
   893       "\nopen Generated;\n\n" ^ string_of
   894         (Pretty.block [str "val () = Codegen.test_fn :=",
   895           Pretty.brk 1, str ("(fn i =>"), Pretty.brk 1,
   896           mk_let (map (fn (s, T) =>
   897               (mk_tuple [str s, str (s ^ "_t")],
   898                Pretty.block [mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   899                  str "i"])) args)
   900             (Pretty.block [str "if ",
   901               mk_app false (str "testf") (map (str o fst) args),
   902               Pretty.brk 1, str "then NONE",
   903               Pretty.brk 1, str "else ",
   904               Pretty.block [str "SOME ", Pretty.block (str "[" ::
   905                 Pretty.commas (map (fn (s, _) => str (s ^ "_t ()")) args) @
   906                   [str "]"])]]),
   907           str ");"]) ^
   908       "\n\nend;\n";
   909     val _ = ML_Context.eval_in (SOME ctxt) false Position.none s;
   910   in ! test_fn end;
   911 
   912 
   913 
   914 (**** Evaluator for terms ****)
   915 
   916 val eval_result = Unsynchronized.ref (fn () => Bound 0);
   917 
   918 fun eval_term thy t =
   919   let
   920     val ctxt = ProofContext.init thy;
   921     val e =
   922       let
   923         val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
   924           error "Term to be evaluated contains type variables";
   925         val _ = (null (Term.add_vars t []) andalso null (Term.add_frees t [])) orelse
   926           error "Term to be evaluated contains variables";
   927         val (code, gr) = setmp mode ["term_of"]
   928           (generate_code_i thy [] "Generated")
   929           [("result", Abs ("x", TFree ("'a", []), t))];
   930         val s = "structure EvalTerm =\nstruct\n\n" ^
   931           cat_lines (map snd code) ^
   932           "\nopen Generated;\n\n" ^ string_of
   933             (Pretty.block [str "val () = Codegen.eval_result := (fn () =>",
   934               Pretty.brk 1,
   935               mk_app false (mk_term_of gr "Generated" false (fastype_of t))
   936                 [str "(result ())"],
   937               str ");"]) ^
   938           "\n\nend;\n";
   939         val _ = NAMED_CRITICAL "codegen" (fn () =>
   940           ML_Context.eval_in (SOME ctxt) false Position.none s);
   941       in !eval_result end;
   942   in e () end;
   943 
   944 val (_, evaluation_conv) = Context.>>> (Context.map_theory_result
   945   (Thm.add_oracle (Binding.name "evaluation", fn ct =>
   946     let
   947       val thy = Thm.theory_of_cterm ct;
   948       val t = Thm.term_of ct;
   949     in Thm.cterm_of thy (Logic.mk_equals (t, eval_term thy t)) end)));
   950 
   951 
   952 (**** Interface ****)
   953 
   954 fun parse_mixfix rd s =
   955   (case Scan.finite Symbol.stopper (Scan.repeat
   956      (   $$ "_" >> K Arg
   957       || $$ "?" >> K Ignore
   958       || $$ "\\<module>" >> K Module
   959       || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
   960       || $$ "{" |-- $$ "*" |-- Scan.repeat1
   961            (   $$ "'" |-- Scan.one Symbol.is_regular
   962             || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.is_regular)) --|
   963          $$ "*" --| $$ "}" >> (Quote o rd o implode)
   964       || Scan.repeat1
   965            (   $$ "'" |-- Scan.one Symbol.is_regular
   966             || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
   967                  (Scan.one Symbol.is_regular)) >> (Pretty o str o implode)))
   968        (Symbol.explode s) of
   969      (p, []) => p
   970    | _ => error ("Malformed annotation: " ^ quote s));
   971 
   972 
   973 structure P = OuterParse and K = OuterKeyword;
   974 
   975 val _ = List.app OuterKeyword.keyword ["attach", "file", "contains"];
   976 
   977 fun strip_whitespace s = implode (fst (take_suffix (fn c => c = "\n" orelse c = " ")
   978   (snd (take_prefix (fn c => c = "\n" orelse c = " ") (explode s))))) ^ "\n";
   979 
   980 val parse_attach = Scan.repeat (P.$$$ "attach" |--
   981   Scan.optional (P.$$$ "(" |-- P.xname --| P.$$$ ")") "" --
   982     (P.verbatim >> strip_whitespace));
   983 
   984 val _ =
   985   OuterSyntax.command "types_code"
   986   "associate types with target language types" K.thy_decl
   987     (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
   988      (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
   989        (fn ((name, mfx), aux) => (name, (parse_mixfix
   990          (Syntax.read_typ_global thy) mfx, aux)))) xs thy)));
   991 
   992 val _ =
   993   OuterSyntax.command "consts_code"
   994   "associate constants with target language code" K.thy_decl
   995     (Scan.repeat1
   996        (P.term --|
   997         P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
   998      (fn xs => Toplevel.theory (fn thy => fold (assoc_const o
   999        (fn ((const, mfx), aux) =>
  1000          (const, (parse_mixfix (Syntax.read_term_global thy) mfx, aux)))) xs thy)));
  1001 
  1002 fun parse_code lib =
  1003   Scan.optional (P.$$$ "(" |-- P.enum "," P.xname --| P.$$$ ")") (!mode) --
  1004   (if lib then Scan.optional P.name "" else P.name) --
  1005   Scan.option (P.$$$ "file" |-- P.name) --
  1006   (if lib then Scan.succeed []
  1007    else Scan.optional (P.$$$ "imports" |-- Scan.repeat1 P.name) []) --|
  1008   P.$$$ "contains" --
  1009   (   Scan.repeat1 (P.name --| P.$$$ "=" -- P.term)
  1010    || Scan.repeat1 (P.term >> pair "")) >>
  1011   (fn ((((mode', module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
  1012     let
  1013       val mode'' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode');
  1014       val (code, gr) = setmp mode mode'' (generate_code thy modules module) xs;
  1015       val thy' = thy |> Context.theory_map (ML_Context.exec (fn () =>
  1016         (case opt_fname of
  1017           NONE => ML_Context.eval false Position.none (cat_lines (map snd code))
  1018         | SOME fname =>
  1019             if lib then app (fn (name, s) => File.write
  1020                 (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
  1021               (("ROOT", implode (map (fn (name, _) =>
  1022                   "use \"" ^ name ^ ".ML\";\n") code)) :: code)
  1023             else File.write (Path.explode fname) (snd (hd code)))));
  1024     in
  1025       if lib then thy'
  1026       else map_modules (Symtab.update (module, gr)) thy'
  1027     end));
  1028 
  1029 val setup = add_codegen "default" default_codegen
  1030   #> add_tycodegen "default" default_tycodegen
  1031   #> add_preprocessor unfold_preprocessor;
  1032 
  1033 val _ =
  1034   OuterSyntax.command "code_library"
  1035     "generates code for terms (one structure for each theory)" K.thy_decl
  1036     (parse_code true);
  1037 
  1038 val _ =
  1039   OuterSyntax.command "code_module"
  1040     "generates code for terms (single structure, incremental)" K.thy_decl
  1041     (parse_code false);
  1042 
  1043 end;