src/Pure/codegen.ML
author berghofe
Sun Oct 19 21:19:27 2008 +0200 (2008-10-19)
changeset 28640 188e9557c572
parent 28537 1e84256d1a8a
child 28674 08a77c495dc1
permissions -rw-r--r--
- removed test_params from CodegenData (now in Pure/Tools/quickcheck.ML)
- improved code unfold preprocessor: now uses one single simpset
containing all unfolding rules
- got rid of some legacy functions
     1 (*  Title:      Pure/codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 Generic code generator.
     6 *)
     7 
     8 signature CODEGEN =
     9 sig
    10   val quiet_mode : bool ref
    11   val message : string -> unit
    12   val mode : string list ref
    13   val margin : int ref
    14   val string_of : Pretty.T -> string
    15   val str : string -> Pretty.T
    16 
    17   datatype 'a mixfix =
    18       Arg
    19     | Ignore
    20     | Module
    21     | Pretty of Pretty.T
    22     | Quote of 'a;
    23 
    24   type deftab
    25   type node
    26   type codegr
    27   type 'a codegen
    28 
    29   val add_codegen: string -> term codegen -> theory -> theory
    30   val add_tycodegen: string -> typ codegen -> theory -> theory
    31   val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory
    32   val preprocess: theory -> thm list -> thm list
    33   val preprocess_term: theory -> term -> term
    34   val print_codegens: theory -> unit
    35   val generate_code: theory -> string list -> string -> (string * string) list ->
    36     (string * string) list * codegr
    37   val generate_code_i: theory -> string list -> string -> (string * term) list ->
    38     (string * string) list * codegr
    39   val assoc_const: string * (term mixfix list *
    40     (string * string) list) -> theory -> theory
    41   val assoc_const_i: (string * typ) * (term mixfix list *
    42     (string * string) list) -> theory -> theory
    43   val assoc_type: xstring * (typ mixfix list *
    44     (string * string) list) -> theory -> theory
    45   val get_assoc_code: theory -> string * typ ->
    46     (term mixfix list * (string * string) list) option
    47   val get_assoc_type: theory -> string ->
    48     (typ mixfix list * (string * string) list) option
    49   val codegen_error: codegr -> string -> string -> 'a
    50   val invoke_codegen: theory -> deftab -> string -> string -> bool ->
    51     term -> codegr -> Pretty.T * codegr
    52   val invoke_tycodegen: theory -> deftab -> string -> string -> bool ->
    53     typ -> codegr -> Pretty.T * codegr
    54   val mk_id: string -> string
    55   val mk_qual_id: string -> string * string -> string
    56   val mk_const_id: string -> string -> codegr -> (string * string) * codegr
    57   val get_const_id: codegr -> string -> string * string
    58   val mk_type_id: string -> string -> codegr -> (string * string) * codegr
    59   val get_type_id: codegr -> string -> string * string
    60   val thyname_of_type: theory -> string -> string
    61   val thyname_of_const: theory -> string -> string
    62   val rename_terms: term list -> term list
    63   val rename_term: term -> term
    64   val new_names: term -> string list -> string list
    65   val new_name: term -> string -> string
    66   val if_library: 'a -> 'a -> 'a
    67   val get_defn: theory -> deftab -> string -> typ ->
    68     ((typ * (string * (term list * term))) * int option) option
    69   val is_instance: typ -> typ -> bool
    70   val parens: Pretty.T -> Pretty.T
    71   val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
    72   val mk_tuple: Pretty.T list -> Pretty.T
    73   val mk_let: (Pretty.T * Pretty.T) list -> Pretty.T -> Pretty.T
    74   val eta_expand: term -> term list -> int -> term
    75   val strip_tname: string -> string
    76   val mk_type: bool -> typ -> Pretty.T
    77   val mk_term_of: codegr -> string -> bool -> typ -> Pretty.T
    78   val mk_gen: codegr -> string -> bool -> string list -> string -> typ -> Pretty.T
    79   val test_fn: (int -> (string * term) list option) ref
    80   val test_term: Proof.context -> term -> int -> term list option
    81   val eval_result: (unit -> term) ref
    82   val eval_term: theory -> term -> term
    83   val evaluation_conv: cterm -> thm
    84   val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    85   val quotes_of: 'a mixfix list -> 'a list
    86   val num_args_of: 'a mixfix list -> int
    87   val replace_quotes: 'b list -> 'a mixfix list -> 'b mixfix list
    88   val mk_deftab: theory -> deftab
    89   val add_unfold: thm -> theory -> theory
    90 
    91   val get_node: codegr -> string -> node
    92   val add_edge: string * string -> codegr -> codegr
    93   val add_edge_acyclic: string * string -> codegr -> codegr
    94   val del_nodes: string list -> codegr -> codegr
    95   val map_node: string -> (node -> node) -> codegr -> codegr
    96   val new_node: string * node -> codegr -> codegr
    97 
    98   val setup: theory -> theory
    99 end;
   100 
   101 structure Codegen : CODEGEN =
   102 struct
   103 
   104 val quiet_mode = ref true;
   105 fun message s = if !quiet_mode then () else writeln s;
   106 
   107 val mode = ref ([] : string list);
   108 
   109 val margin = ref 80;
   110 
   111 fun string_of p = (Pretty.string_of |>
   112   PrintMode.setmp [] |>
   113   Pretty.setmp_margin (!margin)) p;
   114 
   115 val str = PrintMode.setmp [] Pretty.str;
   116 
   117 (**** Mixfix syntax ****)
   118 
   119 datatype 'a mixfix =
   120     Arg
   121   | Ignore
   122   | Module
   123   | Pretty of Pretty.T
   124   | Quote of 'a;
   125 
   126 fun is_arg Arg = true
   127   | is_arg Ignore = true
   128   | is_arg _ = false;
   129 
   130 fun quotes_of [] = []
   131   | quotes_of (Quote q :: ms) = q :: quotes_of ms
   132   | quotes_of (_ :: ms) = quotes_of ms;
   133 
   134 fun args_of [] xs = ([], xs)
   135   | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
   136   | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
   137   | args_of (_ :: ms) xs = args_of ms xs;
   138 
   139 fun num_args_of x = length (List.filter is_arg x);
   140 
   141 
   142 (**** theory data ****)
   143 
   144 (* preprocessed definition table *)
   145 
   146 type deftab =
   147   (typ *              (* type of constant *)
   148     (string *         (* name of theory containing definition of constant *)
   149       (term list *    (* parameters *)
   150        term)))        (* right-hand side *)
   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 (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 fun add_unfold eqn =
   301   let
   302     val ctxt = ProofContext.init (Thm.theory_of_thm eqn);
   303     val eqn' = LocalDefs.meta_rewrite_rule ctxt eqn;
   304   in
   305     UnfoldData.map (fn ss => ss addsimps [eqn'])
   306   end;
   307 
   308 fun unfold_preprocessor thy =
   309   let val ss = Simplifier.theory_context thy (UnfoldData.get thy)
   310   in map (Thm.transfer thy #> Simplifier.full_simplify ss) end;
   311 
   312 
   313 (**** associate constants with target language code ****)
   314 
   315 fun gen_assoc_const prep_const (raw_const, syn) thy =
   316   let
   317     val {codegens, tycodegens, consts, types, preprocs, modules} =
   318       CodegenData.get thy;
   319     val (cname, T) = prep_const thy raw_const;
   320   in
   321     if num_args_of (fst syn) > length (binder_types T) then
   322       error ("More arguments than in corresponding type of " ^ cname)
   323     else case AList.lookup (op =) consts (cname, T) of
   324       NONE => CodegenData.put {codegens = codegens,
   325         tycodegens = tycodegens,
   326         consts = ((cname, T), syn) :: consts,
   327         types = types, preprocs = preprocs,
   328         modules = modules} thy
   329     | SOME _ => error ("Constant " ^ cname ^ " already associated with code")
   330   end;
   331 
   332 val assoc_const_i = gen_assoc_const (K I);
   333 val assoc_const = gen_assoc_const Code_Unit.read_bare_const;
   334 
   335 
   336 (**** associate types with target language types ****)
   337 
   338 fun assoc_type (s, syn) thy =
   339   let
   340     val {codegens, tycodegens, consts, types, preprocs, modules} =
   341       CodegenData.get thy;
   342     val tc = Sign.intern_type thy s;
   343   in
   344     case Symtab.lookup (snd (#types (Type.rep_tsig (Sign.tsig_of thy)))) tc of
   345       SOME ((Type.LogicalType i, _), _) =>
   346         if num_args_of (fst syn) > i then
   347           error ("More arguments than corresponding type constructor " ^ s)
   348         else (case AList.lookup (op =) types tc of
   349           NONE => CodegenData.put {codegens = codegens,
   350             tycodegens = tycodegens, consts = consts,
   351             types = (tc, syn) :: types,
   352             preprocs = preprocs, modules = modules} thy
   353         | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
   354     | _ => error ("Not a type constructor: " ^ s)
   355   end;
   356 
   357 fun get_assoc_type thy = AList.lookup (op =) ((#types o CodegenData.get) thy);
   358 
   359 
   360 (**** make valid ML identifiers ****)
   361 
   362 fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
   363   Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
   364 
   365 fun dest_sym s = (case split_last (snd (take_prefix (fn c => c = "\\") (explode s))) of
   366     ("<" :: "^" :: xs, ">") => (true, implode xs)
   367   | ("<" :: xs, ">") => (false, implode xs)
   368   | _ => sys_error "dest_sym");
   369 
   370 fun mk_id s = if s = "" then "" else
   371   let
   372     fun check_str [] = []
   373       | check_str xs = (case take_prefix is_ascii_letdig xs of
   374           ([], " " :: zs) => check_str zs
   375         | ([], z :: zs) =>
   376           if size z = 1 then string_of_int (ord z) :: check_str zs
   377           else (case dest_sym z of
   378               (true, "isub") => check_str zs
   379             | (true, "isup") => "" :: check_str zs
   380             | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
   381         | (ys, zs) => implode ys :: check_str zs);
   382     val s' = space_implode "_" (maps (check_str o Symbol.explode) (NameSpace.explode s))
   383   in
   384     if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
   385   end;
   386 
   387 fun mk_long_id (p as (tab, used)) module s =
   388   let
   389     fun find_name [] = sys_error "mk_long_id"
   390       | find_name (ys :: yss) =
   391           let
   392             val s' = NameSpace.implode ys
   393             val s'' = NameSpace.append module s'
   394           in case Symtab.lookup used s'' of
   395               NONE => ((module, s'),
   396                 (Symtab.update_new (s, (module, s')) tab,
   397                  Symtab.update_new (s'', ()) used))
   398             | SOME _ => find_name yss
   399           end
   400   in case Symtab.lookup tab s of
   401       NONE => find_name (Library.suffixes1 (NameSpace.explode s))
   402     | SOME name => (name, p)
   403   end;
   404 
   405 (* module:  module name for caller                                        *)
   406 (* module': module name for callee                                        *)
   407 (* if caller and callee reside in different modules, use qualified access *)
   408 
   409 fun mk_qual_id module (module', s) =
   410   if module = module' orelse module' = "" then s else module' ^ "." ^ s;
   411 
   412 fun mk_const_id module cname (gr, (tab1, tab2)) =
   413   let
   414     val ((module, s), tab1') = mk_long_id tab1 module cname
   415     val s' = mk_id s;
   416     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   417   in (((module, s'')), (gr, (tab1', tab2))) end;
   418 
   419 fun get_const_id (gr, (tab1, tab2)) cname =
   420   case Symtab.lookup (fst tab1) cname of
   421     NONE => error ("get_const_id: no such constant: " ^ quote cname)
   422   | SOME (module, s) =>
   423       let
   424         val s' = mk_id s;
   425         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   426       in (module, s'') end;
   427 
   428 fun mk_type_id module tyname (gr, (tab1, tab2)) =
   429   let
   430     val ((module, s), tab2') = mk_long_id tab2 module tyname
   431     val s' = mk_id s;
   432     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   433   in ((module, s''), (gr, (tab1, tab2'))) end;
   434 
   435 fun get_type_id (gr, (tab1, tab2)) tyname =
   436   case Symtab.lookup (fst tab2) tyname of
   437     NONE => error ("get_type_id: no such type: " ^ quote tyname)
   438   | SOME (module, s) =>
   439       let
   440         val s' = mk_id s;
   441         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   442       in (module, s'') end;
   443 
   444 fun get_type_id' f tab tyname = apsnd f (get_type_id tab tyname);
   445 
   446 fun get_node (gr, x) k = Graph.get_node gr k;
   447 fun add_edge e (gr, x) = (Graph.add_edge e gr, x);
   448 fun add_edge_acyclic e (gr, x) = (Graph.add_edge_acyclic e gr, x);
   449 fun del_nodes ks (gr, x) = (Graph.del_nodes ks gr, x);
   450 fun map_node k f (gr, x) = (Graph.map_node k f gr, x);
   451 fun new_node p (gr, x) = (Graph.new_node p gr, x);
   452 
   453 fun thyname_of thy f x = the (AList.lookup (op =) (f x) Markup.theory_nameN);
   454 
   455 fun thyname_of_type thy =
   456   thyname_of thy (Type.the_tags (Sign.tsig_of thy));
   457 
   458 fun thyname_of_const thy =
   459   thyname_of thy (Consts.the_tags (Sign.consts_of thy));
   460 
   461 fun rename_terms ts =
   462   let
   463     val names = List.foldr add_term_names
   464       (map (fst o fst) (rev (fold Term.add_vars ts []))) ts;
   465     val reserved = filter ML_Syntax.is_reserved names;
   466     val (illegal, alt_names) = split_list (map_filter (fn s =>
   467       let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
   468     val ps = (reserved @ illegal) ~~
   469       Name.variant_list names (map (suffix "'") reserved @ alt_names);
   470 
   471     fun rename_id s = AList.lookup (op =) ps s |> the_default s;
   472 
   473     fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
   474       | rename (Free (a, T)) = Free (rename_id a, T)
   475       | rename (Abs (s, T, t)) = Abs (s, T, rename t)
   476       | rename (t $ u) = rename t $ rename u
   477       | rename t = t;
   478   in
   479     map rename ts
   480   end;
   481 
   482 val rename_term = hd o rename_terms o single;
   483 
   484 
   485 (**** retrieve definition of constant ****)
   486 
   487 fun is_instance T1 T2 =
   488   Type.raw_instance (T1, if null (typ_tfrees T2) then T2 else Logic.varifyT T2);
   489 
   490 fun get_assoc_code thy (s, T) = Option.map snd (find_first (fn ((s', T'), _) =>
   491   s = s' andalso is_instance T T') (#consts (CodegenData.get thy)));
   492 
   493 fun get_aux_code xs = map_filter (fn (m, code) =>
   494   if m = "" orelse member (op =) (!mode) m then SOME code else NONE) xs;
   495 
   496 fun mk_deftab thy =
   497   let
   498     val axmss = map (fn thy' => (Context.theory_name thy', Theory.axiom_table thy'))
   499       (thy :: Theory.ancestors_of thy);
   500     fun prep_def def = (case preprocess thy [def] of
   501       [def'] => prop_of def' | _ => error "mk_deftab: bad preprocessor");
   502     fun dest t =
   503       let
   504         val (lhs, rhs) = Logic.dest_equals t;
   505         val (c, args) = strip_comb lhs;
   506         val (s, T) = dest_Const c
   507       in if forall is_Var args then SOME (s, (T, (args, rhs))) else NONE
   508       end handle TERM _ => NONE;
   509     fun add_def thyname (name, t) = (case dest t of
   510         NONE => I
   511       | SOME _ => (case dest (prep_def (Thm.get_axiom_i thy name)) of
   512           NONE => I
   513         | SOME (s, (T, (args, rhs))) => Symtab.map_default (s, [])
   514             (cons (T, (thyname, split_last (rename_terms (args @ [rhs])))))))
   515   in
   516     fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
   517   end;
   518 
   519 fun get_defn thy defs s T = (case Symtab.lookup defs s of
   520     NONE => NONE
   521   | SOME ds =>
   522       let val i = find_index (is_instance T o fst) ds
   523       in if i >= 0 then
   524           SOME (List.nth (ds, i), if length ds = 1 then NONE else SOME i)
   525         else NONE
   526       end);
   527 
   528 
   529 (**** invoke suitable code generator for term / type ****)
   530 
   531 fun codegen_error (gr, _) dep s =
   532   error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
   533 
   534 fun invoke_codegen thy defs dep module brack t gr = (case get_first
   535    (fn (_, f) => f thy defs dep module brack t gr) (#codegens (CodegenData.get thy)) of
   536       NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
   537         Syntax.string_of_term_global thy t)
   538     | SOME x => x);
   539 
   540 fun invoke_tycodegen thy defs dep module brack T gr = (case get_first
   541    (fn (_, f) => f thy defs dep module brack T gr ) (#tycodegens (CodegenData.get thy)) of
   542       NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
   543         Syntax.string_of_typ_global thy T)
   544     | SOME x => x);
   545 
   546 
   547 (**** code generator for mixfix expressions ****)
   548 
   549 fun parens p = Pretty.block [str "(", p, str ")"];
   550 
   551 fun pretty_fn [] p = [p]
   552   | pretty_fn (x::xs) p = str ("fn " ^ x ^ " =>") ::
   553       Pretty.brk 1 :: pretty_fn xs p;
   554 
   555 fun pretty_mixfix _ _ [] [] _ = []
   556   | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
   557       p :: pretty_mixfix module module' ms ps qs
   558   | pretty_mixfix module module' (Ignore :: ms) ps qs =
   559       pretty_mixfix module module' ms ps qs
   560   | pretty_mixfix module module' (Module :: ms) ps qs =
   561       (if module <> module'
   562        then cons (str (module' ^ ".")) else I)
   563       (pretty_mixfix module module' ms ps qs)
   564   | pretty_mixfix module module' (Pretty p :: ms) ps qs =
   565       p :: pretty_mixfix module module' ms ps qs
   566   | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
   567       q :: pretty_mixfix module module' ms ps qs;
   568 
   569 fun replace_quotes [] [] = []
   570   | replace_quotes xs (Arg :: ms) =
   571       Arg :: replace_quotes xs ms
   572   | replace_quotes xs (Ignore :: ms) =
   573       Ignore :: replace_quotes xs ms
   574   | replace_quotes xs (Module :: ms) =
   575       Module :: replace_quotes xs ms
   576   | replace_quotes xs (Pretty p :: ms) =
   577       Pretty p :: replace_quotes xs ms
   578   | replace_quotes (x::xs) (Quote _ :: ms) =
   579       Quote x :: replace_quotes xs ms;
   580 
   581 
   582 (**** default code generators ****)
   583 
   584 fun eta_expand t ts i =
   585   let
   586     val k = length ts;
   587     val Ts = Library.drop (k, binder_types (fastype_of t));
   588     val j = i - k
   589   in
   590     List.foldr (fn (T, t) => Abs ("x", T, t))
   591       (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
   592   end;
   593 
   594 fun mk_app _ p [] = p
   595   | mk_app brack p ps = if brack then
   596        Pretty.block (str "(" ::
   597          separate (Pretty.brk 1) (p :: ps) @ [str ")"])
   598      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   599 
   600 fun new_names t xs = Name.variant_list
   601   (map (fst o fst o dest_Var) (term_vars t) union
   602     add_term_names (t, ML_Syntax.reserved_names)) (map mk_id xs);
   603 
   604 fun new_name t x = hd (new_names t [x]);
   605 
   606 fun if_library x y = if member (op =) (!mode) "library" then x else y;
   607 
   608 fun default_codegen thy defs dep module brack t gr =
   609   let
   610     val (u, ts) = strip_comb t;
   611     fun codegens brack = fold_map (invoke_codegen thy defs dep module brack)
   612   in (case u of
   613       Var ((s, i), T) =>
   614         let
   615           val (ps, gr') = codegens true ts gr;
   616           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   617         in SOME (mk_app brack (str (s ^
   618            (if i=0 then "" else string_of_int i))) ps, gr'')
   619         end
   620 
   621     | Free (s, T) =>
   622         let
   623           val (ps, gr') = codegens true ts gr;
   624           val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
   625         in SOME (mk_app brack (str s) ps, gr'') end
   626 
   627     | Const (s, T) =>
   628       (case get_assoc_code thy (s, T) of
   629          SOME (ms, aux) =>
   630            let val i = num_args_of ms
   631            in if length ts < i then
   632                default_codegen thy defs dep module brack (eta_expand u ts i) gr 
   633              else
   634                let
   635                  val (ts1, ts2) = args_of ms ts;
   636                  val (ps1, gr1) = codegens false ts1 gr;
   637                  val (ps2, gr2) = codegens true ts2 gr1;
   638                  val (ps3, gr3) = codegens false (quotes_of ms) gr2;
   639                  val (_, gr4) = invoke_tycodegen thy defs dep module false
   640                    (funpow (length ts) (hd o tl o snd o dest_Type) T) gr3;
   641                  val (module', suffix) = (case get_defn thy defs s T of
   642                      NONE => (if_library (thyname_of_const thy s) module, "")
   643                    | SOME ((U, (module', _)), NONE) =>
   644                        (if_library module' module, "")
   645                    | SOME ((U, (module', _)), SOME i) =>
   646                        (if_library module' module, " def" ^ string_of_int i));
   647                  val node_id = s ^ suffix;
   648                  fun p module' = mk_app brack (Pretty.block
   649                    (pretty_mixfix module module' ms ps1 ps3)) ps2
   650                in SOME (case try (get_node gr4) node_id of
   651                    NONE => (case get_aux_code aux of
   652                        [] => (p module, gr4)
   653                      | xs => (p module', add_edge (node_id, dep) (new_node
   654                          (node_id, (NONE, module', cat_lines xs ^ "\n")) gr4)))
   655                  | SOME (_, module'', _) =>
   656                      (p module'', add_edge (node_id, dep) gr4))
   657                end
   658            end
   659        | NONE => (case get_defn thy defs s T of
   660            NONE => NONE
   661          | SOME ((U, (thyname, (args, rhs))), k) =>
   662              let
   663                val module' = if_library thyname module;
   664                val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   665                val node_id = s ^ suffix;
   666                val ((ps, def_id), gr') = gr |> codegens true ts
   667                  ||>> mk_const_id module' (s ^ suffix);
   668                val p = mk_app brack (str (mk_qual_id module def_id)) ps
   669              in SOME (case try (get_node gr') node_id of
   670                  NONE =>
   671                    let
   672                      val _ = message ("expanding definition of " ^ s);
   673                      val (Ts, _) = strip_type U;
   674                      val (args', rhs') =
   675                        if not (null args) orelse null Ts then (args, rhs) else
   676                          let val v = Free (new_name rhs "x", hd Ts)
   677                          in ([v], betapply (rhs, v)) end;
   678                      val (p', gr1) = invoke_codegen thy defs node_id module' false
   679                        rhs' (add_edge (node_id, dep)
   680                           (new_node (node_id, (NONE, "", "")) gr'));
   681                      val (xs, gr2) = codegens false args' gr1;
   682                      val (_, gr3) = invoke_tycodegen thy defs dep module false T gr2;
   683                      val (ty, gr4) = invoke_tycodegen thy defs node_id module' false U gr3;
   684                    in (p, map_node node_id (K (NONE, module', string_of
   685                        (Pretty.block (separate (Pretty.brk 1)
   686                          (if null args' then
   687                             [str ("val " ^ snd def_id ^ " :"), ty]
   688                           else str ("fun " ^ snd def_id) :: xs) @
   689                         [str " =", Pretty.brk 1, p', str ";"])) ^ "\n\n")) gr4)
   690                    end
   691                | SOME _ => (p, add_edge (node_id, dep) gr'))
   692              end))
   693 
   694     | Abs _ =>
   695       let
   696         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   697         val t = strip_abs_body u
   698         val bs' = new_names t bs;
   699         val (ps, gr1) = codegens true ts gr;
   700         val (p, gr2) = invoke_codegen thy defs dep module false
   701           (subst_bounds (map Free (rev (bs' ~~ Ts)), t)) gr1;
   702       in
   703         SOME (mk_app brack (Pretty.block (str "(" :: pretty_fn bs' p @
   704           [str ")"])) ps, gr2)
   705       end
   706 
   707     | _ => NONE)
   708   end;
   709 
   710 fun default_tycodegen thy defs dep module brack (TVar ((s, i), _)) gr =
   711       SOME (str (s ^ (if i = 0 then "" else string_of_int i)), gr)
   712   | default_tycodegen thy defs dep module brack (TFree (s, _)) gr =
   713       SOME (str s, gr)
   714   | default_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
   715       (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   716          NONE => NONE
   717        | SOME (ms, aux) =>
   718            let
   719              val (ps, gr') = fold_map
   720                (invoke_tycodegen thy defs dep module false)
   721                (fst (args_of ms Ts)) gr;
   722              val (qs, gr'') = fold_map
   723                (invoke_tycodegen thy defs dep module false)
   724                (quotes_of ms) gr';
   725              val module' = if_library (thyname_of_type thy s) module;
   726              val node_id = s ^ " (type)";
   727              fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   728            in SOME (case try (get_node gr'') node_id of
   729                NONE => (case get_aux_code aux of
   730                    [] => (p module', gr'')
   731                  | xs => (p module', snd (mk_type_id module' s
   732                        (add_edge (node_id, dep) (new_node (node_id,
   733                          (NONE, module', cat_lines xs ^ "\n")) gr'')))))
   734              | SOME (_, module'', _) =>
   735                  (p module'', add_edge (node_id, dep) gr''))
   736            end);
   737 
   738 fun mk_tuple [p] = p
   739   | mk_tuple ps = Pretty.block (str "(" ::
   740       List.concat (separate [str ",", Pretty.brk 1] (map single ps)) @
   741         [str ")"]);
   742 
   743 fun mk_let bindings body =
   744   Pretty.blk (0, [str "let", Pretty.brk 1,
   745     Pretty.blk (0, separate Pretty.fbrk (map (fn (pat, rhs) =>
   746       Pretty.block [str "val ", pat, str " =", Pretty.brk 1,
   747       rhs, str ";"]) bindings)),
   748     Pretty.brk 1, str "in", Pretty.brk 1, body,
   749     Pretty.brk 1, str "end"]);
   750 
   751 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   752 
   753 fun add_to_module name s = AList.map_entry (op =) (name : string) (suffix s);
   754 
   755 fun output_code gr module xs =
   756   let
   757     val code = map_filter (fn s =>
   758       let val c as (_, module', _) = Graph.get_node gr s
   759       in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   760         (rev (Graph.all_preds gr xs));
   761     fun string_of_cycle (a :: b :: cs) =
   762           let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   763             if a = a' then Option.map (pair x)
   764               (find_first ((fn (_, b', _) => b' = b) o Graph.get_node gr)
   765                 (Graph.imm_succs gr x))
   766             else NONE) code
   767           in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   768       | string_of_cycle _ = ""
   769   in
   770     if module = "" then
   771       let
   772         val modules = distinct (op =) (map (#2 o snd) code);
   773         val mod_gr = fold_rev Graph.add_edge_acyclic
   774           (maps (fn (s, (_, module, _)) => map (pair module)
   775             (filter_out (fn s => s = module) (map (#2 o Graph.get_node gr)
   776               (Graph.imm_succs gr s)))) code)
   777           (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
   778         val modules' =
   779           rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   780       in
   781         List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   782           (map (rpair "") modules') code
   783       end handle Graph.CYCLES (cs :: _) =>
   784         error ("Cyclic dependency of modules:\n" ^ commas cs ^
   785           "\n" ^ string_of_cycle cs)
   786     else [(module, implode (map (#3 o snd) code))]
   787   end;
   788 
   789 fun gen_generate_code prep_term thy modules module xs =
   790   let
   791     val _ = (module <> "" orelse
   792         member (op =) (!mode) "library" andalso forall (fn (s, _) => s = "") xs)
   793       orelse error "missing module name";
   794     val graphs = get_modules thy;
   795     val defs = mk_deftab thy;
   796     val gr = new_node ("<Top>", (NONE, module, ""))
   797       (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   798         (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   799            module = module') (gr, gr'),
   800          (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   801            (map (fn s => case Symtab.lookup graphs s of
   802                 NONE => error ("Undefined code module: " ^ s)
   803               | SOME gr => gr) modules))
   804       handle Graph.DUP k => error ("Duplicate code for " ^ k);
   805     fun expand (t as Abs _) = t
   806       | expand t = (case fastype_of t of
   807           Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   808     val (ps, gr') = fold_map (fn (s, t) => fn gr => apfst (pair s)
   809       (invoke_codegen thy defs "<Top>" module false t gr))
   810         (map (apsnd (expand o preprocess_term thy o prep_term thy)) xs) gr;
   811     val code = map_filter
   812       (fn ("", _) => NONE
   813         | (s', p) => SOME (string_of (Pretty.block
   814           [str ("val " ^ s' ^ " ="), Pretty.brk 1, p, str ";"]))) ps;
   815     val code' = space_implode "\n\n" code ^ "\n\n";
   816     val code'' =
   817       map_filter (fn (name, s) =>
   818           if member (op =) (!mode) "library" andalso name = module andalso null code
   819           then NONE
   820           else SOME (name, mk_struct name s))
   821         ((if null code then I
   822           else add_to_module module code')
   823            (output_code (fst gr') (if_library "" module) ["<Top>"]))
   824   in
   825     (code'', del_nodes ["<Top>"] gr')
   826   end;
   827 
   828 val generate_code_i = gen_generate_code Sign.cert_term;
   829 val generate_code = gen_generate_code OldGoals.read_term;
   830 
   831 
   832 (**** Reflection ****)
   833 
   834 val strip_tname = implode o tl o explode;
   835 
   836 fun pretty_list xs = Pretty.block (str "[" ::
   837   flat (separate [str ",", Pretty.brk 1] (map single xs)) @
   838   [str "]"]);
   839 
   840 fun mk_type p (TVar ((s, i), _)) = str
   841       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   842   | mk_type p (TFree (s, _)) = str (strip_tname s ^ "T")
   843   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   844       [str "Type", Pretty.brk 1, str ("(\"" ^ s ^ "\","),
   845        Pretty.brk 1, pretty_list (map (mk_type false) Ts), str ")"]);
   846 
   847 fun mk_term_of gr module p (TVar ((s, i), _)) = str
   848       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   849   | mk_term_of gr module p (TFree (s, _)) = str (strip_tname s ^ "F")
   850   | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   851       (Pretty.block (separate (Pretty.brk 1)
   852         (str (mk_qual_id module
   853           (get_type_id' (fn s' => "term_of_" ^ s') gr s)) ::
   854         maps (fn T =>
   855           [mk_term_of gr module true T, mk_type true T]) Ts)));
   856 
   857 
   858 (**** Test data generators ****)
   859 
   860 fun mk_gen gr module p xs a (TVar ((s, i), _)) = str
   861       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   862   | mk_gen gr module p xs a (TFree (s, _)) = str (strip_tname s ^ "G")
   863   | mk_gen gr module p xs a (Type (tyc as (s, Ts))) = (if p then parens else I)
   864       (Pretty.block (separate (Pretty.brk 1)
   865         (str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') gr s) ^
   866           (if member (op =) xs s then "'" else "")) ::
   867          (case tyc of
   868             ("fun", [T, U]) =>
   869               [mk_term_of gr module true T, mk_type true T,
   870                mk_gen gr module true xs a U, mk_type true U]
   871           | _ => maps (fn T =>
   872               [mk_gen gr module true xs a T, mk_type true T]) Ts) @
   873          (if member (op =) xs s then [str a] else []))));
   874 
   875 val test_fn : (int -> (string * term) list option) ref = ref (fn _ => NONE);
   876 
   877 fun test_term ctxt t =
   878   let
   879     val thy = ProofContext.theory_of ctxt;
   880     val (code, gr) = setmp mode ["term_of", "test"]
   881       (generate_code_i thy [] "Generated") [("testf", t)];
   882     val frees = Name.names Name.context "a" ((map snd o fst o strip_abs) t);
   883     val frees' = frees ~~
   884       map (fn i => "arg" ^ string_of_int i) (1 upto length frees);
   885     val s = "structure TestTerm =\nstruct\n\n" ^
   886       cat_lines (map snd code) ^
   887       "\nopen Generated;\n\n" ^ string_of
   888         (Pretty.block [str "val () = Codegen.test_fn :=",
   889           Pretty.brk 1, str ("(fn i =>"), Pretty.brk 1,
   890           mk_let (map (fn ((s, T), s') =>
   891               (mk_tuple [str s', str (s' ^ "_t")],
   892                Pretty.block [mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   893                  str "(i + 1)"])) frees')
   894             (Pretty.block [str "if ",
   895               mk_app false (str "testf") (map (str o snd) frees'),
   896               Pretty.brk 1, str "then NONE",
   897               Pretty.brk 1, str "else ",
   898               Pretty.block [str "SOME ", Pretty.block (str "[" ::
   899                 flat (separate [str ",", Pretty.brk 1]
   900                   (map (fn ((s, T), s') => [Pretty.block
   901                     [str ("(" ^ quote (Symbol.escape s) ^ ","), Pretty.brk 1,
   902                      str (s' ^ "_t ())")]]) frees')) @
   903                   [str "]"])]]),
   904           str ");"]) ^
   905       "\n\nend;\n";
   906     val _ = ML_Context.eval_in (SOME ctxt) false Position.none s;
   907   in ! test_fn #> (Option.map o map) snd end;
   908 
   909 
   910 
   911 (**** Evaluator for terms ****)
   912 
   913 val eval_result = 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_tvars t) andalso null (term_tfrees t)) orelse
   921           error "Term to be evaluated contains type variables";
   922         val _ = (null (term_vars t) andalso null (term_frees t)) orelse
   923           error "Term to be evaluated contains variables";
   924         val (code, gr) = setmp 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 ("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 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   #> Value.add_evaluator ("SML", eval_term o ProofContext.theory_of)
  1029   #> Quickcheck.add_generator ("SML", test_term)
  1030   #> Code.add_attribute ("unfold", Scan.succeed (Thm.declaration_attribute
  1031        (fn thm => Context.mapping (add_unfold thm #> Code.add_inline thm) I)))
  1032   #> add_preprocessor unfold_preprocessor;
  1033 
  1034 val _ =
  1035   OuterSyntax.command "code_library"
  1036     "generates code for terms (one structure for each theory)" K.thy_decl
  1037     (parse_code true);
  1038 
  1039 val _ =
  1040   OuterSyntax.command "code_module"
  1041     "generates code for terms (single structure, incremental)" K.thy_decl
  1042     (parse_code false);
  1043 
  1044 end;