src/Pure/codegen.ML
changeset 44143 d282b3c5df7c
parent 44142 8e27e0177518
parent 44134 fa98623f1006
child 44144 74b3751ea271
     1.1 --- a/src/Pure/codegen.ML	Wed Aug 10 18:02:16 2011 -0700
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,1049 +0,0 @@
     1.4 -(*  Title:      Pure/codegen.ML
     1.5 -    Author:     Stefan Berghofer, TU Muenchen
     1.6 -
     1.7 -Generic code generator.
     1.8 -*)
     1.9 -
    1.10 -signature CODEGEN =
    1.11 -sig
    1.12 -  val quiet_mode : bool Unsynchronized.ref
    1.13 -  val message : string -> unit
    1.14 -  val margin : int Unsynchronized.ref
    1.15 -  val string_of : Pretty.T -> string
    1.16 -  val str : string -> Pretty.T
    1.17 -
    1.18 -  datatype 'a mixfix =
    1.19 -      Arg
    1.20 -    | Ignore
    1.21 -    | Module
    1.22 -    | Pretty of Pretty.T
    1.23 -    | Quote of 'a;
    1.24 -
    1.25 -  type deftab
    1.26 -  type node
    1.27 -  type codegr
    1.28 -  type 'a codegen
    1.29 -
    1.30 -  val add_codegen: string -> term codegen -> theory -> theory
    1.31 -  val add_tycodegen: string -> typ codegen -> theory -> theory
    1.32 -  val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory
    1.33 -  val preprocess: theory -> thm list -> thm list
    1.34 -  val preprocess_term: theory -> term -> term
    1.35 -  val print_codegens: theory -> unit
    1.36 -  val generate_code: theory -> string list -> string list -> string -> (string * string) list ->
    1.37 -    (string * string) list * codegr
    1.38 -  val generate_code_i: theory -> string list -> string list -> string -> (string * term) list ->
    1.39 -    (string * string) list * codegr
    1.40 -  val assoc_const: string * (term mixfix list *
    1.41 -    (string * string) list) -> theory -> theory
    1.42 -  val assoc_const_i: (string * typ) * (term mixfix list *
    1.43 -    (string * string) list) -> theory -> theory
    1.44 -  val assoc_type: xstring * (typ mixfix list *
    1.45 -    (string * string) list) -> theory -> theory
    1.46 -  val get_assoc_code: theory -> string * typ ->
    1.47 -    (term mixfix list * (string * string) list) option
    1.48 -  val get_assoc_type: theory -> string ->
    1.49 -    (typ mixfix list * (string * string) list) option
    1.50 -  val codegen_error: codegr -> string -> string -> 'a
    1.51 -  val invoke_codegen: theory -> string list -> deftab -> string -> string -> bool ->
    1.52 -    term -> codegr -> Pretty.T * codegr
    1.53 -  val invoke_tycodegen: theory -> string list -> deftab -> string -> string -> bool ->
    1.54 -    typ -> codegr -> Pretty.T * codegr
    1.55 -  val mk_id: string -> string
    1.56 -  val mk_qual_id: string -> string * string -> string
    1.57 -  val mk_const_id: string -> string -> codegr -> (string * string) * codegr
    1.58 -  val get_const_id: codegr -> string -> string * string
    1.59 -  val mk_type_id: string -> string -> codegr -> (string * string) * codegr
    1.60 -  val get_type_id: codegr -> string -> string * string
    1.61 -  val thyname_of_type: theory -> string -> string
    1.62 -  val thyname_of_const: theory -> string -> string
    1.63 -  val rename_terms: term list -> term list
    1.64 -  val rename_term: term -> term
    1.65 -  val new_names: term -> string list -> string list
    1.66 -  val new_name: term -> string -> string
    1.67 -  val if_library: string list -> 'a -> 'a -> 'a
    1.68 -  val get_defn: theory -> deftab -> string -> typ ->
    1.69 -    ((typ * (string * thm)) * int option) option
    1.70 -  val is_instance: typ -> typ -> bool
    1.71 -  val parens: Pretty.T -> Pretty.T
    1.72 -  val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
    1.73 -  val mk_tuple: Pretty.T list -> Pretty.T
    1.74 -  val mk_let: (Pretty.T * Pretty.T) list -> Pretty.T -> Pretty.T
    1.75 -  val eta_expand: term -> term list -> int -> term
    1.76 -  val strip_tname: string -> string
    1.77 -  val mk_type: bool -> typ -> Pretty.T
    1.78 -  val mk_term_of: codegr -> string -> bool -> typ -> Pretty.T
    1.79 -  val mk_gen: codegr -> string -> bool -> string list -> string -> typ -> Pretty.T
    1.80 -  val poke_test_fn: (int -> term list option) -> unit
    1.81 -  val poke_eval_fn: (unit -> term) -> unit
    1.82 -  val test_term: Proof.context -> term -> int -> term list option
    1.83 -  val eval_term: Proof.context -> term -> term
    1.84 -  val evaluation_conv: Proof.context -> conv
    1.85 -  val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    1.86 -  val quotes_of: 'a mixfix list -> 'a list
    1.87 -  val num_args_of: 'a mixfix list -> int
    1.88 -  val replace_quotes: 'b list -> 'a mixfix list -> 'b mixfix list
    1.89 -  val mk_deftab: theory -> deftab
    1.90 -  val map_unfold: (simpset -> simpset) -> theory -> theory
    1.91 -  val add_unfold: thm -> theory -> theory
    1.92 -  val del_unfold: thm -> theory -> theory
    1.93 -
    1.94 -  val get_node: codegr -> string -> node
    1.95 -  val add_edge: string * string -> codegr -> codegr
    1.96 -  val add_edge_acyclic: string * string -> codegr -> codegr
    1.97 -  val del_nodes: string list -> codegr -> codegr
    1.98 -  val map_node: string -> (node -> node) -> codegr -> codegr
    1.99 -  val new_node: string * node -> codegr -> codegr
   1.100 -
   1.101 -  val setup: theory -> theory
   1.102 -end;
   1.103 -
   1.104 -structure Codegen : CODEGEN =
   1.105 -struct
   1.106 -
   1.107 -val quiet_mode = Unsynchronized.ref true;
   1.108 -fun message s = if !quiet_mode then () else writeln s;
   1.109 -
   1.110 -val margin = Unsynchronized.ref 80;
   1.111 -
   1.112 -fun string_of p = Print_Mode.setmp [] (Pretty.string_of_margin (!margin)) p;
   1.113 -
   1.114 -val str = Print_Mode.setmp [] Pretty.str;
   1.115 -
   1.116 -(**** Mixfix syntax ****)
   1.117 -
   1.118 -datatype 'a mixfix =
   1.119 -    Arg
   1.120 -  | Ignore
   1.121 -  | Module
   1.122 -  | Pretty of Pretty.T
   1.123 -  | Quote of 'a;
   1.124 -
   1.125 -fun is_arg Arg = true
   1.126 -  | is_arg Ignore = true
   1.127 -  | is_arg _ = false;
   1.128 -
   1.129 -fun quotes_of [] = []
   1.130 -  | quotes_of (Quote q :: ms) = q :: quotes_of ms
   1.131 -  | quotes_of (_ :: ms) = quotes_of ms;
   1.132 -
   1.133 -fun args_of [] xs = ([], xs)
   1.134 -  | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
   1.135 -  | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
   1.136 -  | args_of (_ :: ms) xs = args_of ms xs;
   1.137 -
   1.138 -fun num_args_of x = length (filter is_arg x);
   1.139 -
   1.140 -
   1.141 -(**** theory data ****)
   1.142 -
   1.143 -(* preprocessed definition table *)
   1.144 -
   1.145 -type deftab =
   1.146 -  (typ *              (* type of constant *)
   1.147 -    (string *         (* name of theory containing definition of constant *)
   1.148 -      thm))           (* definition theorem *)
   1.149 -  list Symtab.table;
   1.150 -
   1.151 -(* code dependency graph *)
   1.152 -
   1.153 -type nametab = (string * string) Symtab.table * unit Symtab.table;
   1.154 -
   1.155 -fun merge_nametabs ((tab, used) : nametab, (tab', used')) =
   1.156 -  (Symtab.merge op = (tab, tab'), Symtab.merge op = (used, used'));
   1.157 -
   1.158 -type node =
   1.159 -  (exn option *    (* slot for arbitrary data *)
   1.160 -   string *        (* name of structure containing piece of code *)
   1.161 -   string);        (* piece of code *)
   1.162 -
   1.163 -type codegr =
   1.164 -  node Graph.T *
   1.165 -  (nametab *       (* table for assigned constant names *)
   1.166 -   nametab);       (* table for assigned type names *)
   1.167 -
   1.168 -val emptygr : codegr = (Graph.empty,
   1.169 -  ((Symtab.empty, Symtab.empty), (Symtab.empty, Symtab.empty)));
   1.170 -
   1.171 -(* type of code generators *)
   1.172 -
   1.173 -type 'a codegen =
   1.174 -  theory ->      (* theory in which generate_code was called *)
   1.175 -  string list -> (* mode *)
   1.176 -  deftab ->      (* definition table (for efficiency) *)
   1.177 -  string ->      (* node name of caller (for recording dependencies) *)
   1.178 -  string ->      (* module name of caller (for modular code generation) *)
   1.179 -  bool ->        (* whether to parenthesize generated expression *)
   1.180 -  'a ->          (* item to generate code from *)
   1.181 -  codegr ->      (* code dependency graph *)
   1.182 -  (Pretty.T * codegr) option;
   1.183 -
   1.184 -
   1.185 -(* theory data *)
   1.186 -
   1.187 -structure CodegenData = Theory_Data
   1.188 -(
   1.189 -  type T =
   1.190 -    {codegens : (string * term codegen) list,
   1.191 -     tycodegens : (string * typ codegen) list,
   1.192 -     consts : ((string * typ) * (term mixfix list * (string * string) list)) list,
   1.193 -     types : (string * (typ mixfix list * (string * string) list)) list,
   1.194 -     preprocs: (stamp * (theory -> thm list -> thm list)) list,
   1.195 -     modules: codegr Symtab.table};
   1.196 -
   1.197 -  val empty =
   1.198 -    {codegens = [], tycodegens = [], consts = [], types = [],
   1.199 -     preprocs = [], modules = Symtab.empty};
   1.200 -  val extend = I;
   1.201 -
   1.202 -  fun merge
   1.203 -    ({codegens = codegens1, tycodegens = tycodegens1,
   1.204 -      consts = consts1, types = types1,
   1.205 -      preprocs = preprocs1, modules = modules1} : T,
   1.206 -     {codegens = codegens2, tycodegens = tycodegens2,
   1.207 -      consts = consts2, types = types2,
   1.208 -      preprocs = preprocs2, modules = modules2}) : T =
   1.209 -    {codegens = AList.merge (op =) (K true) (codegens1, codegens2),
   1.210 -     tycodegens = AList.merge (op =) (K true) (tycodegens1, tycodegens2),
   1.211 -     consts = AList.merge (op =) (K true) (consts1, consts2),
   1.212 -     types = AList.merge (op =) (K true) (types1, types2),
   1.213 -     preprocs = AList.merge (op =) (K true) (preprocs1, preprocs2),
   1.214 -     modules = Symtab.merge (K true) (modules1, modules2)};
   1.215 -);
   1.216 -
   1.217 -fun print_codegens thy =
   1.218 -  let val {codegens, tycodegens, ...} = CodegenData.get thy in
   1.219 -    Pretty.writeln (Pretty.chunks
   1.220 -      [Pretty.strs ("term code generators:" :: map fst codegens),
   1.221 -       Pretty.strs ("type code generators:" :: map fst tycodegens)])
   1.222 -  end;
   1.223 -
   1.224 -
   1.225 -
   1.226 -(**** access modules ****)
   1.227 -
   1.228 -fun get_modules thy = #modules (CodegenData.get thy);
   1.229 -
   1.230 -fun map_modules f thy =
   1.231 -  let val {codegens, tycodegens, consts, types, preprocs, modules} =
   1.232 -    CodegenData.get thy;
   1.233 -  in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
   1.234 -    consts = consts, types = types, preprocs = preprocs,
   1.235 -    modules = f modules} thy
   1.236 -  end;
   1.237 -
   1.238 -
   1.239 -(**** add new code generators to theory ****)
   1.240 -
   1.241 -fun add_codegen name f thy =
   1.242 -  let val {codegens, tycodegens, consts, types, preprocs, modules} =
   1.243 -    CodegenData.get thy
   1.244 -  in (case AList.lookup (op =) codegens name of
   1.245 -      NONE => CodegenData.put {codegens = (name, f) :: codegens,
   1.246 -        tycodegens = tycodegens, consts = consts, types = types,
   1.247 -        preprocs = preprocs, modules = modules} thy
   1.248 -    | SOME _ => error ("Code generator " ^ name ^ " already declared"))
   1.249 -  end;
   1.250 -
   1.251 -fun add_tycodegen name f thy =
   1.252 -  let val {codegens, tycodegens, consts, types, preprocs, modules} =
   1.253 -    CodegenData.get thy
   1.254 -  in (case AList.lookup (op =) tycodegens name of
   1.255 -      NONE => CodegenData.put {tycodegens = (name, f) :: tycodegens,
   1.256 -        codegens = codegens, consts = consts, types = types,
   1.257 -        preprocs = preprocs, modules = modules} thy
   1.258 -    | SOME _ => error ("Code generator " ^ name ^ " already declared"))
   1.259 -  end;
   1.260 -
   1.261 -
   1.262 -(**** preprocessors ****)
   1.263 -
   1.264 -fun add_preprocessor p thy =
   1.265 -  let val {codegens, tycodegens, consts, types, preprocs, modules} =
   1.266 -    CodegenData.get thy
   1.267 -  in CodegenData.put {tycodegens = tycodegens,
   1.268 -    codegens = codegens, consts = consts, types = types,
   1.269 -    preprocs = (stamp (), p) :: preprocs,
   1.270 -    modules = modules} thy
   1.271 -  end;
   1.272 -
   1.273 -fun preprocess thy =
   1.274 -  let val {preprocs, ...} = CodegenData.get thy
   1.275 -  in fold (fn (_, f) => f thy) preprocs end;
   1.276 -
   1.277 -fun preprocess_term thy t =
   1.278 -  let
   1.279 -    val x = Free (singleton (Name.variant_list (OldTerm.add_term_names (t, []))) "x", fastype_of t);
   1.280 -    (* fake definition *)
   1.281 -    val eq = Skip_Proof.make_thm thy (Logic.mk_equals (x, t));
   1.282 -    fun err () = error "preprocess_term: bad preprocessor"
   1.283 -  in case map prop_of (preprocess thy [eq]) of
   1.284 -      [Const ("==", _) $ x' $ t'] => if x = x' then t' else err ()
   1.285 -    | _ => err ()
   1.286 -  end;
   1.287 -
   1.288 -structure UnfoldData = Theory_Data
   1.289 -(
   1.290 -  type T = simpset;
   1.291 -  val empty = empty_ss;
   1.292 -  val extend = I;
   1.293 -  val merge = merge_ss;
   1.294 -);
   1.295 -
   1.296 -val map_unfold = UnfoldData.map;
   1.297 -val add_unfold = map_unfold o Simplifier.add_simp;
   1.298 -val del_unfold = map_unfold o Simplifier.del_simp;
   1.299 -
   1.300 -fun unfold_preprocessor thy =
   1.301 -  let val ss = Simplifier.global_context thy (UnfoldData.get thy)
   1.302 -  in map (Thm.transfer thy #> Simplifier.full_simplify ss) end;
   1.303 -
   1.304 -
   1.305 -(**** associate constants with target language code ****)
   1.306 -
   1.307 -fun gen_assoc_const prep_const (raw_const, syn) thy =
   1.308 -  let
   1.309 -    val {codegens, tycodegens, consts, types, preprocs, modules} =
   1.310 -      CodegenData.get thy;
   1.311 -    val (cname, T) = prep_const thy raw_const;
   1.312 -  in
   1.313 -    if num_args_of (fst syn) > length (binder_types T) then
   1.314 -      error ("More arguments than in corresponding type of " ^ cname)
   1.315 -    else case AList.lookup (op =) consts (cname, T) of
   1.316 -      NONE => CodegenData.put {codegens = codegens,
   1.317 -        tycodegens = tycodegens,
   1.318 -        consts = ((cname, T), syn) :: consts,
   1.319 -        types = types, preprocs = preprocs,
   1.320 -        modules = modules} thy
   1.321 -    | SOME _ => error ("Constant " ^ cname ^ " already associated with code")
   1.322 -  end;
   1.323 -
   1.324 -val assoc_const_i = gen_assoc_const (K I);
   1.325 -val assoc_const = gen_assoc_const Code.read_bare_const;
   1.326 -
   1.327 -
   1.328 -(**** associate types with target language types ****)
   1.329 -
   1.330 -fun assoc_type (s, syn) thy =
   1.331 -  let
   1.332 -    val {codegens, tycodegens, consts, types, preprocs, modules} =
   1.333 -      CodegenData.get thy;
   1.334 -    val tc = Sign.intern_type thy s;
   1.335 -  in
   1.336 -    case Symtab.lookup (snd (#types (Type.rep_tsig (Sign.tsig_of thy)))) tc of
   1.337 -      SOME (Type.LogicalType i) =>
   1.338 -        if num_args_of (fst syn) > i then
   1.339 -          error ("More arguments than corresponding type constructor " ^ s)
   1.340 -        else
   1.341 -          (case AList.lookup (op =) types tc of
   1.342 -            NONE => CodegenData.put {codegens = codegens,
   1.343 -              tycodegens = tycodegens, consts = consts,
   1.344 -              types = (tc, syn) :: types,
   1.345 -              preprocs = preprocs, modules = modules} thy
   1.346 -          | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
   1.347 -    | _ => error ("Not a type constructor: " ^ s)
   1.348 -  end;
   1.349 -
   1.350 -fun get_assoc_type thy = AList.lookup (op =) ((#types o CodegenData.get) thy);
   1.351 -
   1.352 -
   1.353 -(**** make valid ML identifiers ****)
   1.354 -
   1.355 -fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
   1.356 -  Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
   1.357 -
   1.358 -fun dest_sym s =
   1.359 -  (case split_last (snd (take_prefix (fn c => c = "\\") (raw_explode s))) of
   1.360 -    ("<" :: "^" :: xs, ">") => (true, implode xs)
   1.361 -  | ("<" :: xs, ">") => (false, implode xs)
   1.362 -  | _ => raise Fail "dest_sym");
   1.363 -
   1.364 -fun mk_id s = if s = "" then "" else
   1.365 -  let
   1.366 -    fun check_str [] = []
   1.367 -      | check_str xs = (case take_prefix is_ascii_letdig xs of
   1.368 -          ([], " " :: zs) => check_str zs
   1.369 -        | ([], z :: zs) =>
   1.370 -          if size z = 1 then string_of_int (ord z) :: check_str zs
   1.371 -          else (case dest_sym z of
   1.372 -              (true, "isub") => check_str zs
   1.373 -            | (true, "isup") => "" :: check_str zs
   1.374 -            | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
   1.375 -        | (ys, zs) => implode ys :: check_str zs);
   1.376 -    val s' = space_implode "_" (maps (check_str o Symbol.explode) (Long_Name.explode s))
   1.377 -  in
   1.378 -    if Symbol.is_ascii_letter (hd (raw_explode s')) then s' else "id_" ^ s'
   1.379 -  end;
   1.380 -
   1.381 -fun mk_long_id (p as (tab, used)) module s =
   1.382 -  let
   1.383 -    fun find_name [] = raise Fail "mk_long_id"
   1.384 -      | find_name (ys :: yss) =
   1.385 -          let
   1.386 -            val s' = Long_Name.implode ys
   1.387 -            val s'' = Long_Name.append module s'
   1.388 -          in case Symtab.lookup used s'' of
   1.389 -              NONE => ((module, s'),
   1.390 -                (Symtab.update_new (s, (module, s')) tab,
   1.391 -                 Symtab.update_new (s'', ()) used))
   1.392 -            | SOME _ => find_name yss
   1.393 -          end
   1.394 -  in case Symtab.lookup tab s of
   1.395 -      NONE => find_name (Library.suffixes1 (Long_Name.explode s))
   1.396 -    | SOME name => (name, p)
   1.397 -  end;
   1.398 -
   1.399 -(* module:  module name for caller                                        *)
   1.400 -(* module': module name for callee                                        *)
   1.401 -(* if caller and callee reside in different modules, use qualified access *)
   1.402 -
   1.403 -fun mk_qual_id module (module', s) =
   1.404 -  if module = module' orelse module' = "" then s else module' ^ "." ^ s;
   1.405 -
   1.406 -fun mk_const_id module cname (gr, (tab1, tab2)) =
   1.407 -  let
   1.408 -    val ((module, s), tab1') = mk_long_id tab1 module cname
   1.409 -    val s' = mk_id s;
   1.410 -    val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   1.411 -  in (((module, s'')), (gr, (tab1', tab2))) end;
   1.412 -
   1.413 -fun get_const_id (gr, (tab1, tab2)) cname =
   1.414 -  case Symtab.lookup (fst tab1) cname of
   1.415 -    NONE => error ("get_const_id: no such constant: " ^ quote cname)
   1.416 -  | SOME (module, s) =>
   1.417 -      let
   1.418 -        val s' = mk_id s;
   1.419 -        val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   1.420 -      in (module, s'') end;
   1.421 -
   1.422 -fun mk_type_id module tyname (gr, (tab1, tab2)) =
   1.423 -  let
   1.424 -    val ((module, s), tab2') = mk_long_id tab2 module tyname
   1.425 -    val s' = mk_id s;
   1.426 -    val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   1.427 -  in ((module, s''), (gr, (tab1, tab2'))) end;
   1.428 -
   1.429 -fun get_type_id (gr, (tab1, tab2)) tyname =
   1.430 -  case Symtab.lookup (fst tab2) tyname of
   1.431 -    NONE => error ("get_type_id: no such type: " ^ quote tyname)
   1.432 -  | SOME (module, s) =>
   1.433 -      let
   1.434 -        val s' = mk_id s;
   1.435 -        val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   1.436 -      in (module, s'') end;
   1.437 -
   1.438 -fun get_type_id' f tab tyname = apsnd f (get_type_id tab tyname);
   1.439 -
   1.440 -fun get_node (gr, x) k = Graph.get_node gr k;
   1.441 -fun add_edge e (gr, x) = (Graph.add_edge e gr, x);
   1.442 -fun add_edge_acyclic e (gr, x) = (Graph.add_edge_acyclic e gr, x);
   1.443 -fun del_nodes ks (gr, x) = (Graph.del_nodes ks gr, x);
   1.444 -fun map_node k f (gr, x) = (Graph.map_node k f gr, x);
   1.445 -fun new_node p (gr, x) = (Graph.new_node p gr, x);
   1.446 -
   1.447 -fun thyname_of_type thy = #theory_name o Name_Space.the_entry (Sign.type_space thy);
   1.448 -fun thyname_of_const thy = #theory_name o Name_Space.the_entry (Sign.const_space thy);
   1.449 -
   1.450 -fun rename_terms ts =
   1.451 -  let
   1.452 -    val names = List.foldr OldTerm.add_term_names
   1.453 -      (map (fst o fst) (rev (fold Term.add_vars ts []))) ts;
   1.454 -    val reserved = filter ML_Syntax.is_reserved names;
   1.455 -    val (illegal, alt_names) = split_list (map_filter (fn s =>
   1.456 -      let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
   1.457 -    val ps = (reserved @ illegal) ~~
   1.458 -      Name.variant_list names (map (suffix "'") reserved @ alt_names);
   1.459 -
   1.460 -    fun rename_id s = AList.lookup (op =) ps s |> the_default s;
   1.461 -
   1.462 -    fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
   1.463 -      | rename (Free (a, T)) = Free (rename_id a, T)
   1.464 -      | rename (Abs (s, T, t)) = Abs (s, T, rename t)
   1.465 -      | rename (t $ u) = rename t $ rename u
   1.466 -      | rename t = t;
   1.467 -  in
   1.468 -    map rename ts
   1.469 -  end;
   1.470 -
   1.471 -val rename_term = hd o rename_terms o single;
   1.472 -
   1.473 -
   1.474 -(**** retrieve definition of constant ****)
   1.475 -
   1.476 -fun is_instance T1 T2 =
   1.477 -  Type.raw_instance (T1, if null (OldTerm.typ_tfrees T2) then T2 else Logic.varifyT_global T2);
   1.478 -
   1.479 -fun get_assoc_code thy (s, T) = Option.map snd (find_first (fn ((s', T'), _) =>
   1.480 -  s = s' andalso is_instance T T') (#consts (CodegenData.get thy)));
   1.481 -
   1.482 -fun get_aux_code mode xs = map_filter (fn (m, code) =>
   1.483 -  if m = "" orelse member (op =) mode m then SOME code else NONE) xs;
   1.484 -
   1.485 -fun dest_prim_def t =
   1.486 -  let
   1.487 -    val (lhs, rhs) = Logic.dest_equals t;
   1.488 -    val (c, args) = strip_comb lhs;
   1.489 -    val (s, T) = dest_Const c
   1.490 -  in if forall is_Var args then SOME (s, (T, (args, rhs))) else NONE
   1.491 -  end handle TERM _ => NONE;
   1.492 -
   1.493 -fun mk_deftab thy =
   1.494 -  let
   1.495 -    val axmss =
   1.496 -      map (fn thy' => (Context.theory_name thy', Theory.axiom_table thy'))
   1.497 -        (Theory.nodes_of thy);
   1.498 -    fun add_def thyname (name, t) =
   1.499 -      (case dest_prim_def t of
   1.500 -        NONE => I
   1.501 -      | SOME (s, (T, _)) => Symtab.map_default (s, [])
   1.502 -          (cons (T, (thyname, Thm.axiom thy name))));
   1.503 -  in
   1.504 -    fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
   1.505 -  end;
   1.506 -
   1.507 -fun prep_prim_def thy thm =
   1.508 -  let
   1.509 -    val prop = case preprocess thy [thm]
   1.510 -     of [thm'] => Thm.prop_of thm'
   1.511 -      | _ => error "mk_deftab: bad preprocessor"
   1.512 -  in ((Option.map o apsnd o apsnd)
   1.513 -    (fn (args, rhs) => split_last (rename_terms (args @ [rhs]))) o dest_prim_def) prop
   1.514 -  end;
   1.515 -
   1.516 -fun get_defn thy defs s T = (case Symtab.lookup defs s of
   1.517 -    NONE => NONE
   1.518 -  | SOME ds =>
   1.519 -      let val i = find_index (is_instance T o fst) ds
   1.520 -      in if i >= 0 then
   1.521 -          SOME (nth ds i, if length ds = 1 then NONE else SOME i)
   1.522 -        else NONE
   1.523 -      end);
   1.524 -
   1.525 -
   1.526 -(**** invoke suitable code generator for term / type ****)
   1.527 -
   1.528 -fun codegen_error (gr, _) dep s =
   1.529 -  error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
   1.530 -
   1.531 -fun invoke_codegen thy mode defs dep module brack t gr = (case get_first
   1.532 -   (fn (_, f) => f thy mode defs dep module brack t gr) (#codegens (CodegenData.get thy)) of
   1.533 -      NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
   1.534 -        Syntax.string_of_term_global thy t)
   1.535 -    | SOME x => x);
   1.536 -
   1.537 -fun invoke_tycodegen thy mode defs dep module brack T gr = (case get_first
   1.538 -   (fn (_, f) => f thy mode defs dep module brack T gr ) (#tycodegens (CodegenData.get thy)) of
   1.539 -      NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
   1.540 -        Syntax.string_of_typ_global thy T)
   1.541 -    | SOME x => x);
   1.542 -
   1.543 -
   1.544 -(**** code generator for mixfix expressions ****)
   1.545 -
   1.546 -fun parens p = Pretty.block [str "(", p, str ")"];
   1.547 -
   1.548 -fun pretty_fn [] p = [p]
   1.549 -  | pretty_fn (x::xs) p = str ("fn " ^ x ^ " =>") ::
   1.550 -      Pretty.brk 1 :: pretty_fn xs p;
   1.551 -
   1.552 -fun pretty_mixfix _ _ [] [] _ = []
   1.553 -  | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
   1.554 -      p :: pretty_mixfix module module' ms ps qs
   1.555 -  | pretty_mixfix module module' (Ignore :: ms) ps qs =
   1.556 -      pretty_mixfix module module' ms ps qs
   1.557 -  | pretty_mixfix module module' (Module :: ms) ps qs =
   1.558 -      (if module <> module'
   1.559 -       then cons (str (module' ^ ".")) else I)
   1.560 -      (pretty_mixfix module module' ms ps qs)
   1.561 -  | pretty_mixfix module module' (Pretty p :: ms) ps qs =
   1.562 -      p :: pretty_mixfix module module' ms ps qs
   1.563 -  | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
   1.564 -      q :: pretty_mixfix module module' ms ps qs;
   1.565 -
   1.566 -fun replace_quotes [] [] = []
   1.567 -  | replace_quotes xs (Arg :: ms) =
   1.568 -      Arg :: replace_quotes xs ms
   1.569 -  | replace_quotes xs (Ignore :: ms) =
   1.570 -      Ignore :: replace_quotes xs ms
   1.571 -  | replace_quotes xs (Module :: ms) =
   1.572 -      Module :: replace_quotes xs ms
   1.573 -  | replace_quotes xs (Pretty p :: ms) =
   1.574 -      Pretty p :: replace_quotes xs ms
   1.575 -  | replace_quotes (x::xs) (Quote _ :: ms) =
   1.576 -      Quote x :: replace_quotes xs ms;
   1.577 -
   1.578 -
   1.579 -(**** default code generators ****)
   1.580 -
   1.581 -fun eta_expand t ts i =
   1.582 -  let
   1.583 -    val k = length ts;
   1.584 -    val Ts = drop k (binder_types (fastype_of t));
   1.585 -    val j = i - k
   1.586 -  in
   1.587 -    List.foldr (fn (T, t) => Abs ("x", T, t))
   1.588 -      (list_comb (t, ts @ map Bound (j-1 downto 0))) (take j Ts)
   1.589 -  end;
   1.590 -
   1.591 -fun mk_app _ p [] = p
   1.592 -  | mk_app brack p ps = if brack then
   1.593 -       Pretty.block (str "(" ::
   1.594 -         separate (Pretty.brk 1) (p :: ps) @ [str ")"])
   1.595 -     else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   1.596 -
   1.597 -fun new_names t xs = Name.variant_list
   1.598 -  (union (op =) (map (fst o fst o dest_Var) (OldTerm.term_vars t))
   1.599 -    (OldTerm.add_term_names (t, ML_Syntax.reserved_names))) (map mk_id xs);
   1.600 -
   1.601 -fun new_name t x = hd (new_names t [x]);
   1.602 -
   1.603 -fun if_library mode x y = if member (op =) mode "library" then x else y;
   1.604 -
   1.605 -fun default_codegen thy mode defs dep module brack t gr =
   1.606 -  let
   1.607 -    val (u, ts) = strip_comb t;
   1.608 -    fun codegens brack = fold_map (invoke_codegen thy mode defs dep module brack)
   1.609 -  in (case u of
   1.610 -      Var ((s, i), T) =>
   1.611 -        let
   1.612 -          val (ps, gr') = codegens true ts gr;
   1.613 -          val (_, gr'') = invoke_tycodegen thy mode defs dep module false T gr'
   1.614 -        in SOME (mk_app brack (str (s ^
   1.615 -           (if i=0 then "" else string_of_int i))) ps, gr'')
   1.616 -        end
   1.617 -
   1.618 -    | Free (s, T) =>
   1.619 -        let
   1.620 -          val (ps, gr') = codegens true ts gr;
   1.621 -          val (_, gr'') = invoke_tycodegen thy mode defs dep module false T gr'
   1.622 -        in SOME (mk_app brack (str s) ps, gr'') end
   1.623 -
   1.624 -    | Const (s, T) =>
   1.625 -      (case get_assoc_code thy (s, T) of
   1.626 -         SOME (ms, aux) =>
   1.627 -           let val i = num_args_of ms
   1.628 -           in if length ts < i then
   1.629 -               default_codegen thy mode defs dep module brack (eta_expand u ts i) gr 
   1.630 -             else
   1.631 -               let
   1.632 -                 val (ts1, ts2) = args_of ms ts;
   1.633 -                 val (ps1, gr1) = codegens false ts1 gr;
   1.634 -                 val (ps2, gr2) = codegens true ts2 gr1;
   1.635 -                 val (ps3, gr3) = codegens false (quotes_of ms) gr2;
   1.636 -                 val (_, gr4) = invoke_tycodegen thy mode defs dep module false
   1.637 -                   (funpow (length ts) (hd o tl o snd o dest_Type) T) gr3;
   1.638 -                 val (module', suffix) = (case get_defn thy defs s T of
   1.639 -                     NONE => (if_library mode (thyname_of_const thy s) module, "")
   1.640 -                   | SOME ((U, (module', _)), NONE) =>
   1.641 -                       (if_library mode module' module, "")
   1.642 -                   | SOME ((U, (module', _)), SOME i) =>
   1.643 -                       (if_library mode module' module, " def" ^ string_of_int i));
   1.644 -                 val node_id = s ^ suffix;
   1.645 -                 fun p module' = mk_app brack (Pretty.block
   1.646 -                   (pretty_mixfix module module' ms ps1 ps3)) ps2
   1.647 -               in SOME (case try (get_node gr4) node_id of
   1.648 -                   NONE => (case get_aux_code mode aux of
   1.649 -                       [] => (p module, gr4)
   1.650 -                     | xs => (p module', add_edge (node_id, dep) (new_node
   1.651 -                         (node_id, (NONE, module', cat_lines xs ^ "\n")) gr4)))
   1.652 -                 | SOME (_, module'', _) =>
   1.653 -                     (p module'', add_edge (node_id, dep) gr4))
   1.654 -               end
   1.655 -           end
   1.656 -       | NONE => (case get_defn thy defs s T of
   1.657 -           NONE => NONE
   1.658 -         | SOME ((U, (thyname, thm)), k) => (case prep_prim_def thy thm
   1.659 -            of SOME (_, (_, (args, rhs))) => let
   1.660 -               val module' = if_library mode thyname module;
   1.661 -               val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   1.662 -               val node_id = s ^ suffix;
   1.663 -               val ((ps, def_id), gr') = gr |> codegens true ts
   1.664 -                 ||>> mk_const_id module' (s ^ suffix);
   1.665 -               val p = mk_app brack (str (mk_qual_id module def_id)) ps
   1.666 -             in SOME (case try (get_node gr') node_id of
   1.667 -                 NONE =>
   1.668 -                   let
   1.669 -                     val _ = message ("expanding definition of " ^ s);
   1.670 -                     val Ts = binder_types U;
   1.671 -                     val (args', rhs') =
   1.672 -                       if not (null args) orelse null Ts then (args, rhs) else
   1.673 -                         let val v = Free (new_name rhs "x", hd Ts)
   1.674 -                         in ([v], betapply (rhs, v)) end;
   1.675 -                     val (p', gr1) = invoke_codegen thy mode defs node_id module' false
   1.676 -                       rhs' (add_edge (node_id, dep)
   1.677 -                          (new_node (node_id, (NONE, "", "")) gr'));
   1.678 -                     val (xs, gr2) = codegens false args' gr1;
   1.679 -                     val (_, gr3) = invoke_tycodegen thy mode defs dep module false T gr2;
   1.680 -                     val (ty, gr4) = invoke_tycodegen thy mode defs node_id module' false U gr3;
   1.681 -                   in (p, map_node node_id (K (NONE, module', string_of
   1.682 -                       (Pretty.block (separate (Pretty.brk 1)
   1.683 -                         (if null args' then
   1.684 -                            [str ("val " ^ snd def_id ^ " :"), ty]
   1.685 -                          else str ("fun " ^ snd def_id) :: xs) @
   1.686 -                        [str " =", Pretty.brk 1, p', str ";"])) ^ "\n\n")) gr4)
   1.687 -                   end
   1.688 -               | SOME _ => (p, add_edge (node_id, dep) gr'))
   1.689 -             end
   1.690 -             | NONE => NONE)))
   1.691 -
   1.692 -    | Abs _ =>
   1.693 -      let
   1.694 -        val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   1.695 -        val t = strip_abs_body u
   1.696 -        val bs' = new_names t bs;
   1.697 -        val (ps, gr1) = codegens true ts gr;
   1.698 -        val (p, gr2) = invoke_codegen thy mode defs dep module false
   1.699 -          (subst_bounds (map Free (rev (bs' ~~ Ts)), t)) gr1;
   1.700 -      in
   1.701 -        SOME (mk_app brack (Pretty.block (str "(" :: pretty_fn bs' p @
   1.702 -          [str ")"])) ps, gr2)
   1.703 -      end
   1.704 -
   1.705 -    | _ => NONE)
   1.706 -  end;
   1.707 -
   1.708 -fun default_tycodegen thy mode defs dep module brack (TVar ((s, i), _)) gr =
   1.709 -      SOME (str (s ^ (if i = 0 then "" else string_of_int i)), gr)
   1.710 -  | default_tycodegen thy mode defs dep module brack (TFree (s, _)) gr =
   1.711 -      SOME (str s, gr)
   1.712 -  | default_tycodegen thy mode defs dep module brack (Type (s, Ts)) gr =
   1.713 -      (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   1.714 -         NONE => NONE
   1.715 -       | SOME (ms, aux) =>
   1.716 -           let
   1.717 -             val (ps, gr') = fold_map
   1.718 -               (invoke_tycodegen thy mode defs dep module false)
   1.719 -               (fst (args_of ms Ts)) gr;
   1.720 -             val (qs, gr'') = fold_map
   1.721 -               (invoke_tycodegen thy mode defs dep module false)
   1.722 -               (quotes_of ms) gr';
   1.723 -             val module' = if_library mode (thyname_of_type thy s) module;
   1.724 -             val node_id = s ^ " (type)";
   1.725 -             fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   1.726 -           in SOME (case try (get_node gr'') node_id of
   1.727 -               NONE => (case get_aux_code mode aux of
   1.728 -                   [] => (p module', gr'')
   1.729 -                 | xs => (p module', snd (mk_type_id module' s
   1.730 -                       (add_edge (node_id, dep) (new_node (node_id,
   1.731 -                         (NONE, module', cat_lines xs ^ "\n")) gr'')))))
   1.732 -             | SOME (_, module'', _) =>
   1.733 -                 (p module'', add_edge (node_id, dep) gr''))
   1.734 -           end);
   1.735 -
   1.736 -fun mk_tuple [p] = p
   1.737 -  | mk_tuple ps = Pretty.block (str "(" ::
   1.738 -      flat (separate [str ",", Pretty.brk 1] (map single ps)) @ [str ")"]);
   1.739 -
   1.740 -fun mk_let bindings body =
   1.741 -  Pretty.blk (0, [str "let", Pretty.brk 1,
   1.742 -    Pretty.blk (0, separate Pretty.fbrk (map (fn (pat, rhs) =>
   1.743 -      Pretty.block [str "val ", pat, str " =", Pretty.brk 1,
   1.744 -      rhs, str ";"]) bindings)),
   1.745 -    Pretty.brk 1, str "in", Pretty.brk 1, body,
   1.746 -    Pretty.brk 1, str "end"]);
   1.747 -
   1.748 -fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   1.749 -
   1.750 -fun add_to_module name s = AList.map_entry (op =) (name : string) (suffix s);
   1.751 -
   1.752 -fun output_code gr module xs =
   1.753 -  let
   1.754 -    val code = map_filter (fn s =>
   1.755 -      let val c as (_, module', _) = Graph.get_node gr s
   1.756 -      in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   1.757 -        (rev (Graph.all_preds gr xs));
   1.758 -    fun string_of_cycle (a :: b :: cs) =
   1.759 -          let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   1.760 -            if a = a' then Option.map (pair x)
   1.761 -              (find_first ((fn (_, b', _) => b' = b) o Graph.get_node gr)
   1.762 -                (Graph.imm_succs gr x))
   1.763 -            else NONE) code
   1.764 -          in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   1.765 -      | string_of_cycle _ = ""
   1.766 -  in
   1.767 -    if module = "" then
   1.768 -      let
   1.769 -        val modules = distinct (op =) (map (#2 o snd) code);
   1.770 -        val mod_gr = fold_rev Graph.add_edge_acyclic
   1.771 -          (maps (fn (s, (_, module, _)) => map (pair module)
   1.772 -            (filter_out (fn s => s = module) (map (#2 o Graph.get_node gr)
   1.773 -              (Graph.imm_succs gr s)))) code)
   1.774 -          (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
   1.775 -        val modules' =
   1.776 -          rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   1.777 -      in
   1.778 -        List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   1.779 -          (map (rpair "") modules') code
   1.780 -      end handle Graph.CYCLES (cs :: _) =>
   1.781 -        error ("Cyclic dependency of modules:\n" ^ commas cs ^
   1.782 -          "\n" ^ string_of_cycle cs)
   1.783 -    else [(module, implode (map (#3 o snd) code))]
   1.784 -  end;
   1.785 -
   1.786 -fun gen_generate_code prep_term thy mode modules module xs =
   1.787 -  let
   1.788 -    val _ = (module <> "" orelse
   1.789 -        member (op =) mode "library" andalso forall (fn (s, _) => s = "") xs)
   1.790 -      orelse error "missing module name";
   1.791 -    val graphs = get_modules thy;
   1.792 -    val defs = mk_deftab thy;
   1.793 -    val gr = new_node ("<Top>", (NONE, module, ""))
   1.794 -      (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   1.795 -        (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   1.796 -           module = module') (gr, gr'),
   1.797 -         (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   1.798 -           (map (fn s => case Symtab.lookup graphs s of
   1.799 -                NONE => error ("Undefined code module: " ^ s)
   1.800 -              | SOME gr => gr) modules))
   1.801 -      handle Graph.DUP k => error ("Duplicate code for " ^ k);
   1.802 -    fun expand (t as Abs _) = t
   1.803 -      | expand t = (case fastype_of t of
   1.804 -          Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   1.805 -    val (ps, gr') = fold_map (fn (s, t) => fn gr => apfst (pair s)
   1.806 -      (invoke_codegen thy mode defs "<Top>" module false t gr))
   1.807 -        (map (apsnd (expand o preprocess_term thy o prep_term thy)) xs) gr;
   1.808 -    val code = map_filter
   1.809 -      (fn ("", _) => NONE
   1.810 -        | (s', p) => SOME (string_of (Pretty.block
   1.811 -          [str ("val " ^ s' ^ " ="), Pretty.brk 1, p, str ";"]))) ps;
   1.812 -    val code' = space_implode "\n\n" code ^ "\n\n";
   1.813 -    val code'' =
   1.814 -      map_filter (fn (name, s) =>
   1.815 -          if member (op =) mode "library" andalso name = module andalso null code
   1.816 -          then NONE
   1.817 -          else SOME (name, mk_struct name s))
   1.818 -        ((if null code then I
   1.819 -          else add_to_module module code')
   1.820 -           (output_code (fst gr') (if_library mode "" module) ["<Top>"]))
   1.821 -  in
   1.822 -    (code'', del_nodes ["<Top>"] gr')
   1.823 -  end;
   1.824 -
   1.825 -val generate_code_i = gen_generate_code Sign.cert_term;
   1.826 -val generate_code =
   1.827 -  gen_generate_code (Syntax.read_term o Proof_Context.allow_dummies o Proof_Context.init_global);
   1.828 -
   1.829 -
   1.830 -(**** Reflection ****)
   1.831 -
   1.832 -val strip_tname = implode o tl o raw_explode;
   1.833 -
   1.834 -fun pretty_list xs = Pretty.block (str "[" ::
   1.835 -  flat (separate [str ",", Pretty.brk 1] (map single xs)) @
   1.836 -  [str "]"]);
   1.837 -
   1.838 -fun mk_type p (TVar ((s, i), _)) = str
   1.839 -      (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   1.840 -  | mk_type p (TFree (s, _)) = str (strip_tname s ^ "T")
   1.841 -  | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   1.842 -      [str "Type", Pretty.brk 1, str ("(\"" ^ s ^ "\","),
   1.843 -       Pretty.brk 1, pretty_list (map (mk_type false) Ts), str ")"]);
   1.844 -
   1.845 -fun mk_term_of gr module p (TVar ((s, i), _)) = str
   1.846 -      (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   1.847 -  | mk_term_of gr module p (TFree (s, _)) = str (strip_tname s ^ "F")
   1.848 -  | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   1.849 -      (Pretty.block (separate (Pretty.brk 1)
   1.850 -        (str (mk_qual_id module
   1.851 -          (get_type_id' (fn s' => "term_of_" ^ s') gr s)) ::
   1.852 -        maps (fn T =>
   1.853 -          [mk_term_of gr module true T, mk_type true T]) Ts)));
   1.854 -
   1.855 -
   1.856 -(**** Implicit results ****)
   1.857 -
   1.858 -structure Result = Proof_Data
   1.859 -(
   1.860 -  type T = (int -> term list option) * (unit -> term);
   1.861 -  fun init _ = (fn _ => NONE, fn () => Bound 0);
   1.862 -);
   1.863 -
   1.864 -val get_test_fn = #1 o Result.get;
   1.865 -val get_eval_fn = #2 o Result.get;
   1.866 -
   1.867 -fun poke_test_fn f = Context.>> (Context.map_proof (Result.map (fn (_, g) => (f, g))));
   1.868 -fun poke_eval_fn g = Context.>> (Context.map_proof (Result.map (fn (f, _) => (f, g))));
   1.869 -
   1.870 -
   1.871 -(**** Test data generators ****)
   1.872 -
   1.873 -fun mk_gen gr module p xs a (TVar ((s, i), _)) = str
   1.874 -      (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   1.875 -  | mk_gen gr module p xs a (TFree (s, _)) = str (strip_tname s ^ "G")
   1.876 -  | mk_gen gr module p xs a (Type (tyc as (s, Ts))) = (if p then parens else I)
   1.877 -      (Pretty.block (separate (Pretty.brk 1)
   1.878 -        (str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') gr s) ^
   1.879 -          (if member (op =) xs s then "'" else "")) ::
   1.880 -         (case tyc of
   1.881 -            ("fun", [T, U]) =>
   1.882 -              [mk_term_of gr module true T, mk_type true T,
   1.883 -               mk_gen gr module true xs a U, mk_type true U]
   1.884 -          | _ => maps (fn T =>
   1.885 -              [mk_gen gr module true xs a T, mk_type true T]) Ts) @
   1.886 -         (if member (op =) xs s then [str a] else []))));
   1.887 -
   1.888 -fun test_term ctxt t =
   1.889 -  let
   1.890 -    val thy = Proof_Context.theory_of ctxt;
   1.891 -    val (code, gr) = generate_code_i thy ["term_of", "test"] [] "Generated" [("testf", t)];
   1.892 -    val Ts = map snd (fst (strip_abs t));
   1.893 -    val args = map_index (fn (i, T) => ("arg" ^ string_of_int i, T)) Ts;
   1.894 -    val s = "structure Test_Term =\nstruct\n\n" ^
   1.895 -      cat_lines (map snd code) ^
   1.896 -      "\nopen Generated;\n\n" ^ string_of
   1.897 -        (Pretty.block [str "val () = Codegen.poke_test_fn",
   1.898 -          Pretty.brk 1, str ("(fn i =>"), Pretty.brk 1,
   1.899 -          mk_let (map (fn (s, T) =>
   1.900 -              (mk_tuple [str s, str (s ^ "_t")],
   1.901 -               Pretty.block [mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   1.902 -                 str "i"])) args)
   1.903 -            (Pretty.block [str "if ",
   1.904 -              mk_app false (str "testf") (map (str o fst) args),
   1.905 -              Pretty.brk 1, str "then NONE",
   1.906 -              Pretty.brk 1, str "else ",
   1.907 -              Pretty.block [str "SOME ",
   1.908 -                Pretty.enum "," "[" "]" (map (fn (s, _) => str (s ^ "_t ()")) args)]]),
   1.909 -          str ");"]) ^
   1.910 -      "\n\nend;\n";
   1.911 -  in
   1.912 -    ctxt
   1.913 -    |> Context.proof_map (ML_Context.exec (fn () => ML_Context.eval_text false Position.none s))
   1.914 -    |> get_test_fn
   1.915 -  end;
   1.916 -
   1.917 -
   1.918 -(**** Evaluator for terms ****)
   1.919 -
   1.920 -fun eval_term ctxt t =
   1.921 -  let
   1.922 -    val _ =
   1.923 -      legacy_feature
   1.924 -        "Old evaluation mechanism -- use evaluator \"code\" or method \"eval\" instead";
   1.925 -    val thy = Proof_Context.theory_of ctxt;
   1.926 -    val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
   1.927 -      error "Term to be evaluated contains type variables";
   1.928 -    val _ = (null (Term.add_vars t []) andalso null (Term.add_frees t [])) orelse
   1.929 -      error "Term to be evaluated contains variables";
   1.930 -    val (code, gr) =
   1.931 -      generate_code_i thy ["term_of"] [] "Generated"
   1.932 -        [("result", Abs ("x", TFree ("'a", []), t))];
   1.933 -    val s = "structure Eval_Term =\nstruct\n\n" ^
   1.934 -      cat_lines (map snd code) ^
   1.935 -      "\nopen Generated;\n\n" ^ string_of
   1.936 -        (Pretty.block [str "val () = Codegen.poke_eval_fn (fn () =>",
   1.937 -          Pretty.brk 1,
   1.938 -          mk_app false (mk_term_of gr "Generated" false (fastype_of t))
   1.939 -            [str "(result ())"],
   1.940 -          str ");"]) ^
   1.941 -      "\n\nend;\n";
   1.942 -    val eval_fn =
   1.943 -      ctxt
   1.944 -      |> Context.proof_map (ML_Context.exec (fn () => ML_Context.eval_text false Position.none s))
   1.945 -      |> get_eval_fn;
   1.946 -  in eval_fn () end;
   1.947 -
   1.948 -val (_, evaluation_oracle) = Context.>>> (Context.map_theory_result
   1.949 -  (Thm.add_oracle (Binding.name "evaluation", fn (ctxt, ct) =>
   1.950 -    let
   1.951 -      val thy = Proof_Context.theory_of ctxt;
   1.952 -      val t = Thm.term_of ct;
   1.953 -    in
   1.954 -      if Theory.subthy (Thm.theory_of_cterm ct, thy) then
   1.955 -        Thm.cterm_of thy (Logic.mk_equals (t, eval_term ctxt t))
   1.956 -      else raise CTERM ("evaluation_oracle: bad theory", [ct])
   1.957 -    end)));
   1.958 -
   1.959 -fun evaluation_conv ctxt ct = evaluation_oracle (ctxt, ct);
   1.960 -
   1.961 -
   1.962 -(**** Interface ****)
   1.963 -
   1.964 -fun parse_mixfix rd s =
   1.965 -  (case Scan.finite Symbol.stopper (Scan.repeat
   1.966 -     (   $$ "_" >> K Arg
   1.967 -      || $$ "?" >> K Ignore
   1.968 -      || $$ "\\<module>" >> K Module
   1.969 -      || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
   1.970 -      || $$ "{" |-- $$ "*" |-- Scan.repeat1
   1.971 -           (   $$ "'" |-- Scan.one Symbol.is_regular
   1.972 -            || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.is_regular)) --|
   1.973 -         $$ "*" --| $$ "}" >> (Quote o rd o implode)
   1.974 -      || Scan.repeat1
   1.975 -           (   $$ "'" |-- Scan.one Symbol.is_regular
   1.976 -            || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
   1.977 -                 (Scan.one Symbol.is_regular)) >> (Pretty o str o implode)))
   1.978 -       (Symbol.explode s) of
   1.979 -     (p, []) => p
   1.980 -   | _ => error ("Malformed annotation: " ^ quote s));
   1.981 -
   1.982 -
   1.983 -val _ = List.app Keyword.keyword ["attach", "file", "contains"];
   1.984 -
   1.985 -fun strip_whitespace s = implode (fst (take_suffix (fn c => c = "\n" orelse c = " ")
   1.986 -  (snd (take_prefix (fn c => c = "\n" orelse c = " ") (raw_explode s))))) ^ "\n";
   1.987 -
   1.988 -val parse_attach = Scan.repeat (Parse.$$$ "attach" |--
   1.989 -  Scan.optional (Parse.$$$ "(" |-- Parse.xname --| Parse.$$$ ")") "" --
   1.990 -    (Parse.verbatim >> strip_whitespace));
   1.991 -
   1.992 -val _ =
   1.993 -  Outer_Syntax.command "types_code"
   1.994 -  "associate types with target language types" Keyword.thy_decl
   1.995 -    (Scan.repeat1 (Parse.xname --| Parse.$$$ "(" -- Parse.string --| Parse.$$$ ")" -- parse_attach) >>
   1.996 -     (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
   1.997 -       (fn ((name, mfx), aux) => (name, (parse_mixfix
   1.998 -         (Syntax.read_typ_global thy) mfx, aux)))) xs thy)));
   1.999 -
  1.1000 -val _ =
  1.1001 -  Outer_Syntax.command "consts_code"
  1.1002 -  "associate constants with target language code" Keyword.thy_decl
  1.1003 -    (Scan.repeat1
  1.1004 -       (Parse.term --|
  1.1005 -        Parse.$$$ "(" -- Parse.string --| Parse.$$$ ")" -- parse_attach) >>
  1.1006 -     (fn xs => Toplevel.theory (fn thy => fold (assoc_const o
  1.1007 -       (fn ((const, mfx), aux) =>
  1.1008 -         (const, (parse_mixfix (Syntax.read_term_global thy) mfx, aux)))) xs thy)));
  1.1009 -
  1.1010 -fun parse_code lib =
  1.1011 -  Scan.optional (Parse.$$$ "(" |-- Parse.enum "," Parse.xname --| Parse.$$$ ")") [] --
  1.1012 -  (if lib then Scan.optional Parse.name "" else Parse.name) --
  1.1013 -  Scan.option (Parse.$$$ "file" |-- Parse.name) --
  1.1014 -  (if lib then Scan.succeed []
  1.1015 -   else Scan.optional (Parse.$$$ "imports" |-- Scan.repeat1 Parse.name) []) --|
  1.1016 -  Parse.$$$ "contains" --
  1.1017 -  (   Scan.repeat1 (Parse.name --| Parse.$$$ "=" -- Parse.term)
  1.1018 -   || Scan.repeat1 (Parse.term >> pair "")) >>
  1.1019 -  (fn ((((mode, module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
  1.1020 -    let
  1.1021 -      val _ = legacy_feature "Old code generation command -- use 'export_code' instead";
  1.1022 -      val mode' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode);
  1.1023 -      val (code, gr) = generate_code thy mode' modules module xs;
  1.1024 -      val thy' = thy |> Context.theory_map (ML_Context.exec (fn () =>
  1.1025 -        (case opt_fname of
  1.1026 -          NONE => ML_Context.eval_text false Position.none (cat_lines (map snd code))
  1.1027 -        | SOME fname =>
  1.1028 -            if lib then app (fn (name, s) => File.write
  1.1029 -                (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
  1.1030 -              (("ROOT", implode (map (fn (name, _) =>
  1.1031 -                  "use \"" ^ name ^ ".ML\";\n") code)) :: code)
  1.1032 -            else File.write (Path.explode fname) (snd (hd code)))));
  1.1033 -    in
  1.1034 -      if lib then thy'
  1.1035 -      else map_modules (Symtab.update (module, gr)) thy'
  1.1036 -    end));
  1.1037 -
  1.1038 -val setup = add_codegen "default" default_codegen
  1.1039 -  #> add_tycodegen "default" default_tycodegen
  1.1040 -  #> add_preprocessor unfold_preprocessor;
  1.1041 -
  1.1042 -val _ =
  1.1043 -  Outer_Syntax.command "code_library"
  1.1044 -    "generate code for terms (one structure for each theory)" Keyword.thy_decl
  1.1045 -    (parse_code true);
  1.1046 -
  1.1047 -val _ =
  1.1048 -  Outer_Syntax.command "code_module"
  1.1049 -    "generate code for terms (single structure, incremental)" Keyword.thy_decl
  1.1050 -    (parse_code false);
  1.1051 -
  1.1052 -end;