src/Pure/codegen.ML
author wenzelm
Sat Oct 24 19:20:03 2009 +0200 (2009-10-24)
changeset 33092 c859019d3ac5
parent 33042 ddf1f03a9ad9
child 33172 61ee96bc9895
permissions -rw-r--r--
eliminated separate stamp -- NameSpace.define/merge etc. ensure uniqueness already;
     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
   344           (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 add_def thyname (name, t) = (case dest_prim_def t of
   505         NONE => I
   506       | SOME (s, (T, _)) => Symtab.map_default (s, [])
   507           (cons (T, (thyname, Thm.axiom thy name))));
   508   in
   509     fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
   510   end;
   511 
   512 fun prep_prim_def thy thm =
   513   let
   514     val prop = case preprocess thy [thm]
   515      of [thm'] => Thm.prop_of thm'
   516       | _ => error "mk_deftab: bad preprocessor"
   517   in ((Option.map o apsnd o apsnd)
   518     (fn (args, rhs) => split_last (rename_terms (args @ [rhs]))) o dest_prim_def) prop
   519   end;
   520 
   521 fun get_defn thy defs s T = (case Symtab.lookup defs s of
   522     NONE => NONE
   523   | SOME ds =>
   524       let val i = find_index (is_instance T o fst) ds
   525       in if i >= 0 then
   526           SOME (nth ds i, if length ds = 1 then NONE else SOME i)
   527         else NONE
   528       end);
   529 
   530 
   531 (**** invoke suitable code generator for term / type ****)
   532 
   533 fun codegen_error (gr, _) dep s =
   534   error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
   535 
   536 fun invoke_codegen thy defs dep module brack t gr = (case get_first
   537    (fn (_, f) => f thy defs dep module brack t gr) (#codegens (CodegenData.get thy)) of
   538       NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
   539         Syntax.string_of_term_global thy t)
   540     | SOME x => x);
   541 
   542 fun invoke_tycodegen thy defs dep module brack T gr = (case get_first
   543    (fn (_, f) => f thy defs dep module brack T gr ) (#tycodegens (CodegenData.get thy)) of
   544       NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
   545         Syntax.string_of_typ_global thy T)
   546     | SOME x => x);
   547 
   548 
   549 (**** code generator for mixfix expressions ****)
   550 
   551 fun parens p = Pretty.block [str "(", p, str ")"];
   552 
   553 fun pretty_fn [] p = [p]
   554   | pretty_fn (x::xs) p = str ("fn " ^ x ^ " =>") ::
   555       Pretty.brk 1 :: pretty_fn xs p;
   556 
   557 fun pretty_mixfix _ _ [] [] _ = []
   558   | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
   559       p :: pretty_mixfix module module' ms ps qs
   560   | pretty_mixfix module module' (Ignore :: ms) ps qs =
   561       pretty_mixfix module module' ms ps qs
   562   | pretty_mixfix module module' (Module :: ms) ps qs =
   563       (if module <> module'
   564        then cons (str (module' ^ ".")) else I)
   565       (pretty_mixfix module module' ms ps qs)
   566   | pretty_mixfix module module' (Pretty p :: ms) ps qs =
   567       p :: pretty_mixfix module module' ms ps qs
   568   | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
   569       q :: pretty_mixfix module module' ms ps qs;
   570 
   571 fun replace_quotes [] [] = []
   572   | replace_quotes xs (Arg :: ms) =
   573       Arg :: replace_quotes xs ms
   574   | replace_quotes xs (Ignore :: ms) =
   575       Ignore :: replace_quotes xs ms
   576   | replace_quotes xs (Module :: ms) =
   577       Module :: replace_quotes xs ms
   578   | replace_quotes xs (Pretty p :: ms) =
   579       Pretty p :: replace_quotes xs ms
   580   | replace_quotes (x::xs) (Quote _ :: ms) =
   581       Quote x :: replace_quotes xs ms;
   582 
   583 
   584 (**** default code generators ****)
   585 
   586 fun eta_expand t ts i =
   587   let
   588     val k = length ts;
   589     val Ts = Library.drop (k, binder_types (fastype_of t));
   590     val j = i - k
   591   in
   592     List.foldr (fn (T, t) => Abs ("x", T, t))
   593       (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
   594   end;
   595 
   596 fun mk_app _ p [] = p
   597   | mk_app brack p ps = if brack then
   598        Pretty.block (str "(" ::
   599          separate (Pretty.brk 1) (p :: ps) @ [str ")"])
   600      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   601 
   602 fun new_names t xs = Name.variant_list
   603   (union (op =) (map (fst o fst o dest_Var) (OldTerm.term_vars t))
   604     (OldTerm.add_term_names (t, ML_Syntax.reserved_names))) (map mk_id xs);
   605 
   606 fun new_name t x = hd (new_names t [x]);
   607 
   608 fun if_library x y = if member (op =) (!mode) "library" then x else y;
   609 
   610 fun default_codegen thy defs dep module brack t gr =
   611   let
   612     val (u, ts) = strip_comb t;
   613     fun codegens brack = fold_map (invoke_codegen thy defs dep module brack)
   614   in (case u of
   615       Var ((s, i), T) =>
   616         let
   617           val (ps, gr') = codegens true ts gr;
   618           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   619         in SOME (mk_app brack (str (s ^
   620            (if i=0 then "" else string_of_int i))) ps, gr'')
   621         end
   622 
   623     | Free (s, T) =>
   624         let
   625           val (ps, gr') = codegens true ts gr;
   626           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   627         in SOME (mk_app brack (str s) ps, gr'') end
   628 
   629     | Const (s, T) =>
   630       (case get_assoc_code thy (s, T) of
   631          SOME (ms, aux) =>
   632            let val i = num_args_of ms
   633            in if length ts < i then
   634                default_codegen thy defs dep module brack (eta_expand u ts i) gr 
   635              else
   636                let
   637                  val (ts1, ts2) = args_of ms ts;
   638                  val (ps1, gr1) = codegens false ts1 gr;
   639                  val (ps2, gr2) = codegens true ts2 gr1;
   640                  val (ps3, gr3) = codegens false (quotes_of ms) gr2;
   641                  val (_, gr4) = invoke_tycodegen thy defs dep module false
   642                    (funpow (length ts) (hd o tl o snd o dest_Type) T) gr3;
   643                  val (module', suffix) = (case get_defn thy defs s T of
   644                      NONE => (if_library (thyname_of_const thy s) module, "")
   645                    | SOME ((U, (module', _)), NONE) =>
   646                        (if_library module' module, "")
   647                    | SOME ((U, (module', _)), SOME i) =>
   648                        (if_library module' module, " def" ^ string_of_int i));
   649                  val node_id = s ^ suffix;
   650                  fun p module' = mk_app brack (Pretty.block
   651                    (pretty_mixfix module module' ms ps1 ps3)) ps2
   652                in SOME (case try (get_node gr4) node_id of
   653                    NONE => (case get_aux_code aux of
   654                        [] => (p module, gr4)
   655                      | xs => (p module', add_edge (node_id, dep) (new_node
   656                          (node_id, (NONE, module', cat_lines xs ^ "\n")) gr4)))
   657                  | SOME (_, module'', _) =>
   658                      (p module'', add_edge (node_id, dep) gr4))
   659                end
   660            end
   661        | NONE => (case get_defn thy defs s T of
   662            NONE => NONE
   663          | SOME ((U, (thyname, thm)), k) => (case prep_prim_def thy thm
   664             of SOME (_, (_, (args, rhs))) => let
   665                val module' = if_library thyname module;
   666                val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   667                val node_id = s ^ suffix;
   668                val ((ps, def_id), gr') = gr |> codegens true ts
   669                  ||>> mk_const_id module' (s ^ suffix);
   670                val p = mk_app brack (str (mk_qual_id module def_id)) ps
   671              in SOME (case try (get_node gr') node_id of
   672                  NONE =>
   673                    let
   674                      val _ = message ("expanding definition of " ^ s);
   675                      val (Ts, _) = strip_type U;
   676                      val (args', rhs') =
   677                        if not (null args) orelse null Ts then (args, rhs) else
   678                          let val v = Free (new_name rhs "x", hd Ts)
   679                          in ([v], betapply (rhs, v)) end;
   680                      val (p', gr1) = invoke_codegen thy defs node_id module' false
   681                        rhs' (add_edge (node_id, dep)
   682                           (new_node (node_id, (NONE, "", "")) gr'));
   683                      val (xs, gr2) = codegens false args' gr1;
   684                      val (_, gr3) = invoke_tycodegen thy defs dep module false T gr2;
   685                      val (ty, gr4) = invoke_tycodegen thy defs node_id module' false U gr3;
   686                    in (p, map_node node_id (K (NONE, module', string_of
   687                        (Pretty.block (separate (Pretty.brk 1)
   688                          (if null args' then
   689                             [str ("val " ^ snd def_id ^ " :"), ty]
   690                           else str ("fun " ^ snd def_id) :: xs) @
   691                         [str " =", Pretty.brk 1, p', str ";"])) ^ "\n\n")) gr4)
   692                    end
   693                | SOME _ => (p, add_edge (node_id, dep) gr'))
   694              end
   695              | NONE => NONE)))
   696 
   697     | Abs _ =>
   698       let
   699         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   700         val t = strip_abs_body u
   701         val bs' = new_names t bs;
   702         val (ps, gr1) = codegens true ts gr;
   703         val (p, gr2) = invoke_codegen thy defs dep module false
   704           (subst_bounds (map Free (rev (bs' ~~ Ts)), t)) gr1;
   705       in
   706         SOME (mk_app brack (Pretty.block (str "(" :: pretty_fn bs' p @
   707           [str ")"])) ps, gr2)
   708       end
   709 
   710     | _ => NONE)
   711   end;
   712 
   713 fun default_tycodegen thy defs dep module brack (TVar ((s, i), _)) gr =
   714       SOME (str (s ^ (if i = 0 then "" else string_of_int i)), gr)
   715   | default_tycodegen thy defs dep module brack (TFree (s, _)) gr =
   716       SOME (str s, gr)
   717   | default_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
   718       (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   719          NONE => NONE
   720        | SOME (ms, aux) =>
   721            let
   722              val (ps, gr') = fold_map
   723                (invoke_tycodegen thy defs dep module false)
   724                (fst (args_of ms Ts)) gr;
   725              val (qs, gr'') = fold_map
   726                (invoke_tycodegen thy defs dep module false)
   727                (quotes_of ms) gr';
   728              val module' = if_library (thyname_of_type thy s) module;
   729              val node_id = s ^ " (type)";
   730              fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   731            in SOME (case try (get_node gr'') node_id of
   732                NONE => (case get_aux_code aux of
   733                    [] => (p module', gr'')
   734                  | xs => (p module', snd (mk_type_id module' s
   735                        (add_edge (node_id, dep) (new_node (node_id,
   736                          (NONE, module', cat_lines xs ^ "\n")) gr'')))))
   737              | SOME (_, module'', _) =>
   738                  (p module'', add_edge (node_id, dep) gr''))
   739            end);
   740 
   741 fun mk_tuple [p] = p
   742   | mk_tuple ps = Pretty.block (str "(" ::
   743       flat (separate [str ",", Pretty.brk 1] (map single ps)) @ [str ")"]);
   744 
   745 fun mk_let bindings body =
   746   Pretty.blk (0, [str "let", Pretty.brk 1,
   747     Pretty.blk (0, separate Pretty.fbrk (map (fn (pat, rhs) =>
   748       Pretty.block [str "val ", pat, str " =", Pretty.brk 1,
   749       rhs, str ";"]) bindings)),
   750     Pretty.brk 1, str "in", Pretty.brk 1, body,
   751     Pretty.brk 1, str "end"]);
   752 
   753 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   754 
   755 fun add_to_module name s = AList.map_entry (op =) (name : string) (suffix s);
   756 
   757 fun output_code gr module xs =
   758   let
   759     val code = map_filter (fn s =>
   760       let val c as (_, module', _) = Graph.get_node gr s
   761       in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   762         (rev (Graph.all_preds gr xs));
   763     fun string_of_cycle (a :: b :: cs) =
   764           let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   765             if a = a' then Option.map (pair x)
   766               (find_first ((fn (_, b', _) => b' = b) o Graph.get_node gr)
   767                 (Graph.imm_succs gr x))
   768             else NONE) code
   769           in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   770       | string_of_cycle _ = ""
   771   in
   772     if module = "" then
   773       let
   774         val modules = distinct (op =) (map (#2 o snd) code);
   775         val mod_gr = fold_rev Graph.add_edge_acyclic
   776           (maps (fn (s, (_, module, _)) => map (pair module)
   777             (filter_out (fn s => s = module) (map (#2 o Graph.get_node gr)
   778               (Graph.imm_succs gr s)))) code)
   779           (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
   780         val modules' =
   781           rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   782       in
   783         List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   784           (map (rpair "") modules') code
   785       end handle Graph.CYCLES (cs :: _) =>
   786         error ("Cyclic dependency of modules:\n" ^ commas cs ^
   787           "\n" ^ string_of_cycle cs)
   788     else [(module, implode (map (#3 o snd) code))]
   789   end;
   790 
   791 fun gen_generate_code prep_term thy modules module xs =
   792   let
   793     val _ = (module <> "" orelse
   794         member (op =) (!mode) "library" andalso forall (fn (s, _) => s = "") xs)
   795       orelse error "missing module name";
   796     val graphs = get_modules thy;
   797     val defs = mk_deftab thy;
   798     val gr = new_node ("<Top>", (NONE, module, ""))
   799       (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   800         (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   801            module = module') (gr, gr'),
   802          (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   803            (map (fn s => case Symtab.lookup graphs s of
   804                 NONE => error ("Undefined code module: " ^ s)
   805               | SOME gr => gr) modules))
   806       handle Graph.DUP k => error ("Duplicate code for " ^ k);
   807     fun expand (t as Abs _) = t
   808       | expand t = (case fastype_of t of
   809           Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   810     val (ps, gr') = fold_map (fn (s, t) => fn gr => apfst (pair s)
   811       (invoke_codegen thy defs "<Top>" module false t gr))
   812         (map (apsnd (expand o preprocess_term thy o prep_term thy)) xs) gr;
   813     val code = map_filter
   814       (fn ("", _) => NONE
   815         | (s', p) => SOME (string_of (Pretty.block
   816           [str ("val " ^ s' ^ " ="), Pretty.brk 1, p, str ";"]))) ps;
   817     val code' = space_implode "\n\n" code ^ "\n\n";
   818     val code'' =
   819       map_filter (fn (name, s) =>
   820           if member (op =) (!mode) "library" andalso name = module andalso null code
   821           then NONE
   822           else SOME (name, mk_struct name s))
   823         ((if null code then I
   824           else add_to_module module code')
   825            (output_code (fst gr') (if_library "" module) ["<Top>"]))
   826   in
   827     (code'', del_nodes ["<Top>"] gr')
   828   end;
   829 
   830 val generate_code_i = gen_generate_code Sign.cert_term;
   831 val generate_code =
   832   gen_generate_code (Syntax.read_term o ProofContext.allow_dummies o ProofContext.init);
   833 
   834 
   835 (**** Reflection ****)
   836 
   837 val strip_tname = implode o tl o explode;
   838 
   839 fun pretty_list xs = Pretty.block (str "[" ::
   840   flat (separate [str ",", Pretty.brk 1] (map single xs)) @
   841   [str "]"]);
   842 
   843 fun mk_type p (TVar ((s, i), _)) = str
   844       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   845   | mk_type p (TFree (s, _)) = str (strip_tname s ^ "T")
   846   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   847       [str "Type", Pretty.brk 1, str ("(\"" ^ s ^ "\","),
   848        Pretty.brk 1, pretty_list (map (mk_type false) Ts), str ")"]);
   849 
   850 fun mk_term_of gr module p (TVar ((s, i), _)) = str
   851       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   852   | mk_term_of gr module p (TFree (s, _)) = str (strip_tname s ^ "F")
   853   | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   854       (Pretty.block (separate (Pretty.brk 1)
   855         (str (mk_qual_id module
   856           (get_type_id' (fn s' => "term_of_" ^ s') gr s)) ::
   857         maps (fn T =>
   858           [mk_term_of gr module true T, mk_type true T]) Ts)));
   859 
   860 
   861 (**** Test data generators ****)
   862 
   863 fun mk_gen gr module p xs a (TVar ((s, i), _)) = str
   864       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   865   | mk_gen gr module p xs a (TFree (s, _)) = str (strip_tname s ^ "G")
   866   | mk_gen gr module p xs a (Type (tyc as (s, Ts))) = (if p then parens else I)
   867       (Pretty.block (separate (Pretty.brk 1)
   868         (str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') gr s) ^
   869           (if member (op =) xs s then "'" else "")) ::
   870          (case tyc of
   871             ("fun", [T, U]) =>
   872               [mk_term_of gr module true T, mk_type true T,
   873                mk_gen gr module true xs a U, mk_type true U]
   874           | _ => maps (fn T =>
   875               [mk_gen gr module true xs a T, mk_type true T]) Ts) @
   876          (if member (op =) xs s then [str a] else []))));
   877 
   878 val test_fn : (int -> term list option) Unsynchronized.ref =
   879   Unsynchronized.ref (fn _ => NONE);
   880 
   881 fun test_term ctxt t =
   882   let
   883     val thy = ProofContext.theory_of ctxt;
   884     val (code, gr) = setmp_CRITICAL mode ["term_of", "test"]
   885       (generate_code_i thy [] "Generated") [("testf", t)];
   886     val Ts = map snd (fst (strip_abs t));
   887     val args = map_index (fn (i, T) => ("arg" ^ string_of_int i, T)) Ts;
   888     val s = "structure TestTerm =\nstruct\n\n" ^
   889       cat_lines (map snd code) ^
   890       "\nopen Generated;\n\n" ^ string_of
   891         (Pretty.block [str "val () = Codegen.test_fn :=",
   892           Pretty.brk 1, str ("(fn i =>"), Pretty.brk 1,
   893           mk_let (map (fn (s, T) =>
   894               (mk_tuple [str s, str (s ^ "_t")],
   895                Pretty.block [mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   896                  str "i"])) args)
   897             (Pretty.block [str "if ",
   898               mk_app false (str "testf") (map (str o fst) args),
   899               Pretty.brk 1, str "then NONE",
   900               Pretty.brk 1, str "else ",
   901               Pretty.block [str "SOME ", Pretty.block (str "[" ::
   902                 Pretty.commas (map (fn (s, _) => str (s ^ "_t ()")) args) @
   903                   [str "]"])]]),
   904           str ");"]) ^
   905       "\n\nend;\n";
   906     val _ = ML_Context.eval_in (SOME ctxt) false Position.none s;
   907   in ! test_fn end;
   908 
   909 
   910 
   911 (**** Evaluator for terms ****)
   912 
   913 val eval_result = Unsynchronized.ref (fn () => Bound 0);
   914 
   915 fun eval_term thy t =
   916   let
   917     val ctxt = ProofContext.init thy;
   918     val e =
   919       let
   920         val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
   921           error "Term to be evaluated contains type variables";
   922         val _ = (null (Term.add_vars t []) andalso null (Term.add_frees t [])) orelse
   923           error "Term to be evaluated contains variables";
   924         val (code, gr) = setmp_CRITICAL mode ["term_of"]
   925           (generate_code_i thy [] "Generated")
   926           [("result", Abs ("x", TFree ("'a", []), t))];
   927         val s = "structure EvalTerm =\nstruct\n\n" ^
   928           cat_lines (map snd code) ^
   929           "\nopen Generated;\n\n" ^ string_of
   930             (Pretty.block [str "val () = Codegen.eval_result := (fn () =>",
   931               Pretty.brk 1,
   932               mk_app false (mk_term_of gr "Generated" false (fastype_of t))
   933                 [str "(result ())"],
   934               str ");"]) ^
   935           "\n\nend;\n";
   936         val _ = NAMED_CRITICAL "codegen" (fn () =>
   937           ML_Context.eval_in (SOME ctxt) false Position.none s);
   938       in !eval_result end;
   939   in e () end;
   940 
   941 val (_, evaluation_conv) = Context.>>> (Context.map_theory_result
   942   (Thm.add_oracle (Binding.name "evaluation", fn ct =>
   943     let
   944       val thy = Thm.theory_of_cterm ct;
   945       val t = Thm.term_of ct;
   946     in Thm.cterm_of thy (Logic.mk_equals (t, eval_term thy t)) end)));
   947 
   948 
   949 (**** Interface ****)
   950 
   951 fun parse_mixfix rd s =
   952   (case Scan.finite Symbol.stopper (Scan.repeat
   953      (   $$ "_" >> K Arg
   954       || $$ "?" >> K Ignore
   955       || $$ "\\<module>" >> K Module
   956       || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
   957       || $$ "{" |-- $$ "*" |-- Scan.repeat1
   958            (   $$ "'" |-- Scan.one Symbol.is_regular
   959             || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.is_regular)) --|
   960          $$ "*" --| $$ "}" >> (Quote o rd o implode)
   961       || Scan.repeat1
   962            (   $$ "'" |-- Scan.one Symbol.is_regular
   963             || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
   964                  (Scan.one Symbol.is_regular)) >> (Pretty o str o implode)))
   965        (Symbol.explode s) of
   966      (p, []) => p
   967    | _ => error ("Malformed annotation: " ^ quote s));
   968 
   969 
   970 structure P = OuterParse and K = OuterKeyword;
   971 
   972 val _ = List.app OuterKeyword.keyword ["attach", "file", "contains"];
   973 
   974 fun strip_whitespace s = implode (fst (take_suffix (fn c => c = "\n" orelse c = " ")
   975   (snd (take_prefix (fn c => c = "\n" orelse c = " ") (explode s))))) ^ "\n";
   976 
   977 val parse_attach = Scan.repeat (P.$$$ "attach" |--
   978   Scan.optional (P.$$$ "(" |-- P.xname --| P.$$$ ")") "" --
   979     (P.verbatim >> strip_whitespace));
   980 
   981 val _ =
   982   OuterSyntax.command "types_code"
   983   "associate types with target language types" K.thy_decl
   984     (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
   985      (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
   986        (fn ((name, mfx), aux) => (name, (parse_mixfix
   987          (Syntax.read_typ_global thy) mfx, aux)))) xs thy)));
   988 
   989 val _ =
   990   OuterSyntax.command "consts_code"
   991   "associate constants with target language code" K.thy_decl
   992     (Scan.repeat1
   993        (P.term --|
   994         P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
   995      (fn xs => Toplevel.theory (fn thy => fold (assoc_const o
   996        (fn ((const, mfx), aux) =>
   997          (const, (parse_mixfix (Syntax.read_term_global thy) mfx, aux)))) xs thy)));
   998 
   999 fun parse_code lib =
  1000   Scan.optional (P.$$$ "(" |-- P.enum "," P.xname --| P.$$$ ")") (!mode) --
  1001   (if lib then Scan.optional P.name "" else P.name) --
  1002   Scan.option (P.$$$ "file" |-- P.name) --
  1003   (if lib then Scan.succeed []
  1004    else Scan.optional (P.$$$ "imports" |-- Scan.repeat1 P.name) []) --|
  1005   P.$$$ "contains" --
  1006   (   Scan.repeat1 (P.name --| P.$$$ "=" -- P.term)
  1007    || Scan.repeat1 (P.term >> pair "")) >>
  1008   (fn ((((mode', module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
  1009     let
  1010       val mode'' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode');
  1011       val (code, gr) = setmp_CRITICAL mode mode'' (generate_code thy modules module) xs;
  1012       val thy' = thy |> Context.theory_map (ML_Context.exec (fn () =>
  1013         (case opt_fname of
  1014           NONE => ML_Context.eval false Position.none (cat_lines (map snd code))
  1015         | SOME fname =>
  1016             if lib then app (fn (name, s) => File.write
  1017                 (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
  1018               (("ROOT", implode (map (fn (name, _) =>
  1019                   "use \"" ^ name ^ ".ML\";\n") code)) :: code)
  1020             else File.write (Path.explode fname) (snd (hd code)))));
  1021     in
  1022       if lib then thy'
  1023       else map_modules (Symtab.update (module, gr)) thy'
  1024     end));
  1025 
  1026 val setup = add_codegen "default" default_codegen
  1027   #> add_tycodegen "default" default_tycodegen
  1028   #> add_preprocessor unfold_preprocessor;
  1029 
  1030 val _ =
  1031   OuterSyntax.command "code_library"
  1032     "generates code for terms (one structure for each theory)" K.thy_decl
  1033     (parse_code true);
  1034 
  1035 val _ =
  1036   OuterSyntax.command "code_module"
  1037     "generates code for terms (single structure, incremental)" K.thy_decl
  1038     (parse_code false);
  1039 
  1040 end;