src/Pure/codegen.ML
author haftmann
Thu May 10 10:22:17 2007 +0200 (2007-05-10)
changeset 22921 475ff421a6a3
parent 22846 fb79144af9a3
child 23178 07ba6b58b3d2
permissions -rw-r--r--
consts in consts_code Isar commands are now referred to by usual term syntax
     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 
    15   datatype 'a mixfix =
    16       Arg
    17     | Ignore
    18     | Module
    19     | Pretty of Pretty.T
    20     | Quote of 'a;
    21 
    22   type deftab
    23   type node
    24   type codegr
    25   type 'a codegen
    26 
    27   val add_codegen: string -> term codegen -> theory -> theory
    28   val add_tycodegen: string -> typ codegen -> theory -> theory
    29   val add_attribute: string -> (Args.T list -> attribute * Args.T list) -> theory -> theory
    30   val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory
    31   val preprocess: theory -> thm list -> thm list
    32   val preprocess_term: theory -> term -> term
    33   val print_codegens: theory -> unit
    34   val generate_code: theory -> string list -> string -> (string * string) list ->
    35     (string * string) list * codegr
    36   val generate_code_i: theory -> string list -> string -> (string * term) list ->
    37     (string * string) list * codegr
    38   val assoc_const: string * (term mixfix list *
    39     (string * string) list) -> theory -> theory
    40   val assoc_const_i: (string * typ) * (term mixfix list *
    41     (string * string) list) -> theory -> theory
    42   val assoc_type: xstring * (typ mixfix list *
    43     (string * string) list) -> theory -> theory
    44   val get_assoc_code: theory -> string * typ ->
    45     (term mixfix list * (string * string) list) option
    46   val get_assoc_type: theory -> string ->
    47     (typ mixfix list * (string * string) list) option
    48   val codegen_error: codegr -> string -> string -> 'a
    49   val invoke_codegen: theory -> deftab -> string -> string -> bool ->
    50     codegr * term -> codegr * Pretty.T
    51   val invoke_tycodegen: theory -> deftab -> string -> string -> bool ->
    52     codegr * typ -> codegr * Pretty.T
    53   val mk_id: string -> string
    54   val mk_qual_id: string -> string * string -> string
    55   val mk_const_id: string -> string -> codegr -> codegr * (string * string)
    56   val get_const_id: string -> codegr -> string * string
    57   val mk_type_id: string -> string -> codegr -> codegr * (string * string)
    58   val get_type_id: string -> codegr -> string * string
    59   val thyname_of_type: string -> theory -> string
    60   val thyname_of_const: string -> theory -> string
    61   val rename_terms: term list -> term list
    62   val rename_term: term -> term
    63   val new_names: term -> string list -> string list
    64   val new_name: term -> string -> string
    65   val if_library: 'a -> 'a -> 'a
    66   val get_defn: theory -> deftab -> string -> typ ->
    67     ((typ * (string * (term list * term))) * int option) option
    68   val is_instance: theory -> typ -> typ -> bool
    69   val parens: Pretty.T -> Pretty.T
    70   val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
    71   val eta_expand: term -> term list -> int -> term
    72   val strip_tname: string -> string
    73   val mk_type: bool -> typ -> Pretty.T
    74   val mk_term_of: codegr -> string -> bool -> typ -> Pretty.T
    75   val mk_gen: codegr -> string -> bool -> string list -> string -> typ -> Pretty.T
    76   val test_fn: (int -> (string * term) list option) ref
    77   val test_term: theory -> int -> int -> term -> (string * term) list option
    78   val eval_result: term ref
    79   val eval_term: theory -> term -> term
    80   val evaluation_conv: cterm -> thm
    81   val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    82   val quotes_of: 'a mixfix list -> 'a list
    83   val num_args_of: 'a mixfix list -> int
    84   val replace_quotes: 'b list -> 'a mixfix list -> 'b mixfix list
    85   val fillin_mixfix: ('a -> Pretty.T) -> 'a mixfix list -> 'a list -> Pretty.T
    86   val mk_deftab: theory -> deftab
    87   val add_unfold: thm -> theory -> theory
    88 
    89   val get_node: codegr -> string -> node
    90   val add_edge: string * string -> codegr -> codegr
    91   val add_edge_acyclic: string * string -> codegr -> codegr
    92   val del_nodes: string list -> codegr -> codegr
    93   val map_node: string -> (node -> node) -> codegr -> codegr
    94   val new_node: string * node -> codegr -> codegr
    95 end;
    96 
    97 structure Codegen : CODEGEN =
    98 struct
    99 
   100 val quiet_mode = ref true;
   101 fun message s = if !quiet_mode then () else writeln s;
   102 
   103 val mode = ref ([] : string list);
   104 
   105 val margin = ref 80;
   106 
   107 (**** Mixfix syntax ****)
   108 
   109 datatype 'a mixfix =
   110     Arg
   111   | Ignore
   112   | Module
   113   | Pretty of Pretty.T
   114   | Quote of 'a;
   115 
   116 fun is_arg Arg = true
   117   | is_arg Ignore = true
   118   | is_arg _ = false;
   119 
   120 fun quotes_of [] = []
   121   | quotes_of (Quote q :: ms) = q :: quotes_of ms
   122   | quotes_of (_ :: ms) = quotes_of ms;
   123 
   124 fun args_of [] xs = ([], xs)
   125   | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
   126   | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
   127   | args_of (_ :: ms) xs = args_of ms xs;
   128 
   129 fun num_args_of x = length (List.filter is_arg x);
   130 
   131 
   132 (**** theory data ****)
   133 
   134 (* preprocessed definition table *)
   135 
   136 type deftab =
   137   (typ *              (* type of constant *)
   138     (string *         (* name of theory containing definition of constant *)
   139       (term list *    (* parameters *)
   140        term)))        (* right-hand side *)
   141   list Symtab.table;
   142 
   143 (* code dependency graph *)
   144 
   145 type nametab = (string * string) Symtab.table * unit Symtab.table;
   146 
   147 fun merge_nametabs ((tab, used), (tab', used')) =
   148   (Symtab.merge op = (tab, tab'), Symtab.merge op = (used, used'));
   149 
   150 type node =
   151   (exn option *    (* slot for arbitrary data *)
   152    string *        (* name of structure containing piece of code *)
   153    string);        (* piece of code *)
   154 
   155 type codegr =
   156   node Graph.T *
   157   (nametab *       (* table for assigned constant names *)
   158    nametab);       (* table for assigned type names *)
   159 
   160 val emptygr : codegr = (Graph.empty,
   161   ((Symtab.empty, Symtab.empty), (Symtab.empty, Symtab.empty)));
   162 
   163 (* type of code generators *)
   164 
   165 type 'a codegen =
   166   theory ->    (* theory in which generate_code was called *)
   167   deftab ->    (* definition table (for efficiency) *)
   168   codegr ->    (* code dependency graph *)
   169   string ->    (* node name of caller (for recording dependencies) *)
   170   string ->    (* module name of caller (for modular code generation) *)
   171   bool ->      (* whether to parenthesize generated expression *)
   172   'a ->        (* item to generate code from *)
   173   (codegr * Pretty.T) option;
   174 
   175 (* parameters for random testing *)
   176 
   177 type test_params =
   178   {size: int, iterations: int, default_type: typ option};
   179 
   180 fun merge_test_params
   181   {size = size1, iterations = iterations1, default_type = default_type1}
   182   {size = size2, iterations = iterations2, default_type = default_type2} =
   183   {size = Int.max (size1, size2),
   184    iterations = Int.max (iterations1, iterations2),
   185    default_type = case default_type1 of
   186        NONE => default_type2
   187      | _ => default_type1};
   188 
   189 val default_test_params : test_params =
   190   {size = 10, iterations = 100, default_type = NONE};
   191 
   192 fun set_size size ({iterations, default_type, ...} : test_params) =
   193   {size = size, iterations = iterations, default_type = default_type};
   194 
   195 fun set_iterations iterations ({size, default_type, ...} : test_params) =
   196   {size = size, iterations = iterations, default_type = default_type};
   197 
   198 fun set_default_type s thy ({size, iterations, ...} : test_params) =
   199   {size = size, iterations = iterations,
   200    default_type = SOME (Sign.read_typ thy s)};
   201 
   202 
   203 (* theory data *)
   204 
   205 structure CodeData = CodegenData;
   206 
   207 structure CodegenData = TheoryDataFun
   208 (
   209   type T =
   210     {codegens : (string * term codegen) list,
   211      tycodegens : (string * typ codegen) list,
   212      consts : ((string * typ) * (term mixfix list * (string * string) list)) list,
   213      types : (string * (typ mixfix list * (string * string) list)) list,
   214      attrs: (string * (Args.T list -> attribute * Args.T list)) list,
   215      preprocs: (stamp * (theory -> thm list -> thm list)) list,
   216      modules: codegr Symtab.table,
   217      test_params: test_params};
   218 
   219   val empty =
   220     {codegens = [], tycodegens = [], consts = [], types = [], attrs = [],
   221      preprocs = [], modules = Symtab.empty, test_params = default_test_params};
   222   val copy = I;
   223   val extend = I;
   224 
   225   fun merge _
   226     ({codegens = codegens1, tycodegens = tycodegens1,
   227       consts = consts1, types = types1, attrs = attrs1,
   228       preprocs = preprocs1, modules = modules1, test_params = test_params1},
   229      {codegens = codegens2, tycodegens = tycodegens2,
   230       consts = consts2, types = types2, attrs = attrs2,
   231       preprocs = preprocs2, modules = modules2, test_params = test_params2}) =
   232     {codegens = AList.merge (op =) (K true) (codegens1, codegens2),
   233      tycodegens = AList.merge (op =) (K true) (tycodegens1, tycodegens2),
   234      consts = AList.merge (op =) (K true) (consts1, consts2),
   235      types = AList.merge (op =) (K true) (types1, types2),
   236      attrs = AList.merge (op =) (K true) (attrs1, attrs2),
   237      preprocs = AList.merge (op =) (K true) (preprocs1, preprocs2),
   238      modules = Symtab.merge (K true) (modules1, modules2),
   239      test_params = merge_test_params test_params1 test_params2};
   240 );
   241 
   242 fun print_codegens thy =
   243   let val {codegens, tycodegens, ...} = CodegenData.get thy in
   244     Pretty.writeln (Pretty.chunks
   245       [Pretty.strs ("term code generators:" :: map fst codegens),
   246        Pretty.strs ("type code generators:" :: map fst tycodegens)])
   247   end;
   248 
   249 
   250 
   251 (**** access parameters for random testing ****)
   252 
   253 fun get_test_params thy = #test_params (CodegenData.get thy);
   254 
   255 fun map_test_params f thy =
   256   let val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   257     CodegenData.get thy;
   258   in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
   259     consts = consts, types = types, attrs = attrs, preprocs = preprocs,
   260     modules = modules, test_params = f test_params} thy
   261   end;
   262 
   263 
   264 (**** access modules ****)
   265 
   266 fun get_modules thy = #modules (CodegenData.get thy);
   267 
   268 fun map_modules f thy =
   269   let val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   270     CodegenData.get thy;
   271   in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
   272     consts = consts, types = types, attrs = attrs, preprocs = preprocs,
   273     modules = f modules, test_params = test_params} thy
   274   end;
   275 
   276 
   277 (**** add new code generators to theory ****)
   278 
   279 fun add_codegen name f thy =
   280   let val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   281     CodegenData.get thy
   282   in (case AList.lookup (op =) codegens name of
   283       NONE => CodegenData.put {codegens = (name, f) :: codegens,
   284         tycodegens = tycodegens, consts = consts, types = types,
   285         attrs = attrs, preprocs = preprocs, modules = modules,
   286         test_params = test_params} thy
   287     | SOME _ => error ("Code generator " ^ name ^ " already declared"))
   288   end;
   289 
   290 fun add_tycodegen name f thy =
   291   let val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   292     CodegenData.get thy
   293   in (case AList.lookup (op =) tycodegens name of
   294       NONE => CodegenData.put {tycodegens = (name, f) :: tycodegens,
   295         codegens = codegens, consts = consts, types = types,
   296         attrs = attrs, preprocs = preprocs, modules = modules,
   297         test_params = test_params} thy
   298     | SOME _ => error ("Code generator " ^ name ^ " already declared"))
   299   end;
   300 
   301 
   302 (**** preprocessors ****)
   303 
   304 fun add_preprocessor p thy =
   305   let val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   306     CodegenData.get thy
   307   in CodegenData.put {tycodegens = tycodegens,
   308     codegens = codegens, consts = consts, types = types,
   309     attrs = attrs, preprocs = (stamp (), p) :: preprocs,
   310     modules = modules, test_params = test_params} thy
   311   end;
   312 
   313 fun preprocess thy =
   314   let val {preprocs, ...} = CodegenData.get thy
   315   in fold (fn (_, f) => f thy) preprocs end;
   316 
   317 fun preprocess_term thy t =
   318   let
   319     val x = Free (Name.variant (add_term_names (t, [])) "x", fastype_of t);
   320     (* fake definition *)
   321     val eq = setmp quick_and_dirty true (SkipProof.make_thm thy)
   322       (Logic.mk_equals (x, t));
   323     fun err () = error "preprocess_term: bad preprocessor"
   324   in case map prop_of (preprocess thy [eq]) of
   325       [Const ("==", _) $ x' $ t'] => if x = x' then t' else err ()
   326     | _ => err ()
   327   end;
   328 
   329 fun add_unfold eqn =
   330   let
   331     val thy = Thm.theory_of_thm eqn;
   332     val ctxt = ProofContext.init thy;
   333     val eqn' = LocalDefs.meta_rewrite_rule ctxt eqn;
   334     val names = term_consts (fst (Logic.dest_equals (prop_of eqn')));
   335     fun prep thy = map (fn th =>
   336       let val prop = prop_of th
   337       in
   338         if forall (fn name => exists_Const (equal name o fst) prop) names
   339         then rewrite_rule [eqn'] (Thm.transfer thy th)
   340         else th
   341       end)
   342   in add_preprocessor prep end;
   343 
   344 
   345 (**** code attribute ****)
   346 
   347 fun add_attribute name att thy =
   348   let val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   349     CodegenData.get thy
   350   in (case AList.lookup (op =) attrs name of
   351       NONE => CodegenData.put {tycodegens = tycodegens,
   352         codegens = codegens, consts = consts, types = types,
   353         attrs = if name = "" then attrs @ [(name, att)] else (name, att) :: attrs,
   354         preprocs = preprocs, modules = modules,
   355         test_params = test_params} thy
   356     | SOME _ => error ("Code attribute " ^ name ^ " already declared"))
   357   end;
   358 
   359 fun mk_parser (a, p) = (if a = "" then Scan.succeed "" else Args.$$$ a) |-- p;
   360 
   361 val code_attr =
   362   Attrib.syntax (Scan.peek (fn context => foldr op || Scan.fail (map mk_parser
   363     (#attrs (CodegenData.get (Context.theory_of context))))));
   364 
   365 val _ = Context.add_setup
   366   (Attrib.add_attributes [("code", code_attr, "declare theorems for code generation")]);
   367 
   368 local
   369   fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   370   fun add_simple_attribute (name, f) =
   371     add_attribute name (Scan.succeed (mk_attribute f));
   372   fun add_del_attribute (name, (add, del)) =
   373     add_attribute name (Args.del |-- Scan.succeed (mk_attribute del)
   374       || Scan.succeed (mk_attribute add))
   375 in
   376   val _ = Context.add_setup (add_simple_attribute ("unfold",
   377     fn thm => add_unfold thm #> CodeData.add_inline thm));
   378   val _ = map (Context.add_setup o add_del_attribute) [
   379     ("func", (CodeData.add_func true, CodeData.del_func)),
   380     ("inline", (CodeData.add_inline, CodeData.del_inline))
   381   ];
   382 end; (*local*)
   383 
   384 
   385 (**** associate constants with target language code ****)
   386 
   387 fun gen_assoc_const prep_const (raw_const, syn) thy =
   388   let
   389     val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   390       CodegenData.get thy;
   391     val (cname, T) = prep_const thy raw_const;
   392   in
   393     if num_args_of (fst syn) > length (binder_types T) then
   394       error ("More arguments than in corresponding type of " ^ cname)
   395     else case AList.lookup (op =) consts (cname, T) of
   396       NONE => CodegenData.put {codegens = codegens,
   397         tycodegens = tycodegens,
   398         consts = ((cname, T), syn) :: consts,
   399         types = types, attrs = attrs, preprocs = preprocs,
   400         modules = modules, test_params = test_params} thy
   401     | SOME _ => error ("Constant " ^ cname ^ " already associated with code")
   402   end;
   403 
   404 val assoc_const_i = gen_assoc_const (K I);
   405 val assoc_const = gen_assoc_const CodegenConsts.read_bare_const;
   406 
   407 
   408 (**** associate types with target language types ****)
   409 
   410 fun assoc_type (s, syn) thy =
   411   let
   412     val {codegens, tycodegens, consts, types, attrs, preprocs, modules, test_params} =
   413       CodegenData.get thy;
   414     val tc = Sign.intern_type thy s;
   415   in
   416     case Symtab.lookup (snd (#types (Type.rep_tsig (Sign.tsig_of thy)))) tc of
   417       SOME (Type.LogicalType i, _) =>
   418         if num_args_of (fst syn) > i then
   419           error ("More arguments than corresponding type constructor " ^ s)
   420         else (case AList.lookup (op =) types tc of
   421           NONE => CodegenData.put {codegens = codegens,
   422             tycodegens = tycodegens, consts = consts,
   423             types = (tc, syn) :: types, attrs = attrs,
   424             preprocs = preprocs, modules = modules, test_params = test_params} thy
   425         | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
   426     | _ => error ("Not a type constructor: " ^ s)
   427   end;
   428 
   429 fun get_assoc_type thy = AList.lookup (op =) ((#types o CodegenData.get) thy);
   430 
   431 
   432 (**** make valid ML identifiers ****)
   433 
   434 fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
   435   Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
   436 
   437 fun dest_sym s = (case split_last (snd (take_prefix (equal "\\") (explode s))) of
   438     ("<" :: "^" :: xs, ">") => (true, implode xs)
   439   | ("<" :: xs, ">") => (false, implode xs)
   440   | _ => sys_error "dest_sym");
   441 
   442 fun mk_id s = if s = "" then "" else
   443   let
   444     fun check_str [] = []
   445       | check_str xs = (case take_prefix is_ascii_letdig xs of
   446           ([], " " :: zs) => check_str zs
   447         | ([], z :: zs) =>
   448           if size z = 1 then string_of_int (ord z) :: check_str zs
   449           else (case dest_sym z of
   450               (true, "isub") => check_str zs
   451             | (true, "isup") => "" :: check_str zs
   452             | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
   453         | (ys, zs) => implode ys :: check_str zs);
   454     val s' = space_implode "_" (maps (check_str o Symbol.explode) (NameSpace.explode s))
   455   in
   456     if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
   457   end;
   458 
   459 fun mk_long_id (p as (tab, used)) module s =
   460   let
   461     fun find_name [] = sys_error "mk_long_id"
   462       | find_name (ys :: yss) =
   463           let
   464             val s' = NameSpace.implode ys
   465             val s'' = NameSpace.append module s'
   466           in case Symtab.lookup used s'' of
   467               NONE => ((module, s'),
   468                 (Symtab.update_new (s, (module, s')) tab,
   469                  Symtab.update_new (s'', ()) used))
   470             | SOME _ => find_name yss
   471           end
   472   in case Symtab.lookup tab s of
   473       NONE => find_name (Library.suffixes1 (NameSpace.explode s))
   474     | SOME name => (name, p)
   475   end;
   476 
   477 (* module:  module name for caller                                        *)
   478 (* module': module name for callee                                        *)
   479 (* if caller and callee reside in different modules, use qualified access *)
   480 
   481 fun mk_qual_id module (module', s) =
   482   if module = module' orelse module' = "" then s else module' ^ "." ^ s;
   483 
   484 fun mk_const_id module cname (gr, (tab1, tab2)) =
   485   let
   486     val ((module, s), tab1') = mk_long_id tab1 module cname
   487     val s' = mk_id s;
   488     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   489   in ((gr, (tab1', tab2)), (module, s'')) end;
   490 
   491 fun get_const_id cname (gr, (tab1, tab2)) =
   492   case Symtab.lookup (fst tab1) cname of
   493     NONE => error ("get_const_id: no such constant: " ^ quote cname)
   494   | SOME (module, s) =>
   495       let
   496         val s' = mk_id s;
   497         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
   498       in (module, s'') end;
   499 
   500 fun mk_type_id module tyname (gr, (tab1, tab2)) =
   501   let
   502     val ((module, s), tab2') = mk_long_id tab2 module tyname
   503     val s' = mk_id s;
   504     val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   505   in ((gr, (tab1, tab2')), (module, s'')) end;
   506 
   507 fun get_type_id tyname (gr, (tab1, tab2)) =
   508   case Symtab.lookup (fst tab2) tyname of
   509     NONE => error ("get_type_id: no such type: " ^ quote tyname)
   510   | SOME (module, s) =>
   511       let
   512         val s' = mk_id s;
   513         val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
   514       in (module, s'') end;
   515 
   516 fun get_type_id' f tyname tab = apsnd f (get_type_id tyname tab);
   517 
   518 fun get_node (gr, x) k = Graph.get_node gr k;
   519 fun add_edge e (gr, x) = (Graph.add_edge e gr, x);
   520 fun add_edge_acyclic e (gr, x) = (Graph.add_edge_acyclic e gr, x);
   521 fun del_nodes ks (gr, x) = (Graph.del_nodes ks gr, x);
   522 fun map_node k f (gr, x) = (Graph.map_node k f gr, x);
   523 fun new_node p (gr, x) = (Graph.new_node p gr, x);
   524 
   525 fun theory_of_type s thy =
   526   if Sign.declared_tyname thy s
   527   then SOME (the_default thy (get_first (theory_of_type s) (Theory.parents_of thy)))
   528   else NONE;
   529 
   530 fun theory_of_const s thy =
   531   if Sign.declared_const thy s
   532   then SOME (the_default thy (get_first (theory_of_const s) (Theory.parents_of thy)))
   533   else NONE;
   534 
   535 fun thyname_of_type s thy = (case theory_of_type s thy of
   536     NONE => error ("thyname_of_type: no such type: " ^ quote s)
   537   | SOME thy' => Context.theory_name thy');
   538 
   539 fun thyname_of_const s thy = (case theory_of_const s thy of
   540     NONE => error ("thyname_of_const: no such constant: " ^ quote s)
   541   | SOME thy' => Context.theory_name thy');
   542 
   543 fun rename_terms ts =
   544   let
   545     val names = foldr add_term_names
   546       (map (fst o fst) (rev (fold Term.add_vars ts []))) ts;
   547     val reserved = filter ML_Syntax.is_reserved names;
   548     val (illegal, alt_names) = split_list (map_filter (fn s =>
   549       let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
   550     val ps = (reserved @ illegal) ~~
   551       Name.variant_list names (map (suffix "'") reserved @ alt_names);
   552 
   553     fun rename_id s = AList.lookup (op =) ps s |> the_default s;
   554 
   555     fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
   556       | rename (Free (a, T)) = Free (rename_id a, T)
   557       | rename (Abs (s, T, t)) = Abs (s, T, rename t)
   558       | rename (t $ u) = rename t $ rename u
   559       | rename t = t;
   560   in
   561     map rename ts
   562   end;
   563 
   564 val rename_term = hd o rename_terms o single;
   565 
   566 
   567 (**** retrieve definition of constant ****)
   568 
   569 fun is_instance thy T1 T2 =
   570   Sign.typ_instance thy (T1, Logic.legacy_varifyT T2);
   571 
   572 fun get_assoc_code thy (s, T) = Option.map snd (find_first (fn ((s', T'), _) =>
   573   s = s' andalso is_instance thy T T') (#consts (CodegenData.get thy)));
   574 
   575 fun get_aux_code xs = map_filter (fn (m, code) =>
   576   if m = "" orelse member (op =) (!mode) m then SOME code else NONE) xs;
   577 
   578 fun mk_deftab thy =
   579   let
   580     val axmss = map (fn thy' => (Context.theory_name thy', Theory.axiom_table thy'))
   581       (thy :: Theory.ancestors_of thy);
   582     fun prep_def def = (case preprocess thy [def] of
   583       [def'] => prop_of def' | _ => error "mk_deftab: bad preprocessor");
   584     fun dest t =
   585       let
   586         val (lhs, rhs) = Logic.dest_equals t;
   587         val (c, args) = strip_comb lhs;
   588         val (s, T) = dest_Const c
   589       in if forall is_Var args then SOME (s, (T, (args, rhs))) else NONE
   590       end handle TERM _ => NONE;
   591     fun add_def thyname (name, t) = (case dest t of
   592         NONE => I
   593       | SOME _ => (case dest (prep_def (Thm.get_axiom thy name)) of
   594           NONE => I
   595         | SOME (s, (T, (args, rhs))) => Symtab.map_default (s, [])
   596             (cons (T, (thyname, split_last (rename_terms (args @ [rhs])))))))
   597   in
   598     fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
   599   end;
   600 
   601 fun get_defn thy defs s T = (case Symtab.lookup defs s of
   602     NONE => NONE
   603   | SOME ds =>
   604       let val i = find_index (is_instance thy T o fst) ds
   605       in if i >= 0 then
   606           SOME (List.nth (ds, i), if length ds = 1 then NONE else SOME i)
   607         else NONE
   608       end);
   609 
   610 
   611 (**** invoke suitable code generator for term / type ****)
   612 
   613 fun codegen_error (gr, _) dep s =
   614   error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
   615 
   616 fun invoke_codegen thy defs dep module brack (gr, t) = (case get_first
   617    (fn (_, f) => f thy defs gr dep module brack t) (#codegens (CodegenData.get thy)) of
   618       NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
   619         Sign.string_of_term thy t)
   620     | SOME x => x);
   621 
   622 fun invoke_tycodegen thy defs dep module brack (gr, T) = (case get_first
   623    (fn (_, f) => f thy defs gr dep module brack T) (#tycodegens (CodegenData.get thy)) of
   624       NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
   625         Sign.string_of_typ thy T)
   626     | SOME x => x);
   627 
   628 
   629 (**** code generator for mixfix expressions ****)
   630 
   631 fun parens p = Pretty.block [Pretty.str "(", p, Pretty.str ")"];
   632 
   633 fun pretty_fn [] p = [p]
   634   | pretty_fn (x::xs) p = Pretty.str ("fn " ^ x ^ " =>") ::
   635       Pretty.brk 1 :: pretty_fn xs p;
   636 
   637 fun pretty_mixfix _ _ [] [] _ = []
   638   | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
   639       p :: pretty_mixfix module module' ms ps qs
   640   | pretty_mixfix module module' (Ignore :: ms) ps qs =
   641       pretty_mixfix module module' ms ps qs
   642   | pretty_mixfix module module' (Module :: ms) ps qs =
   643       (if module <> module'
   644        then cons (Pretty.str (module' ^ ".")) else I)
   645       (pretty_mixfix module module' ms ps qs)
   646   | pretty_mixfix module module' (Pretty p :: ms) ps qs =
   647       p :: pretty_mixfix module module' ms ps qs
   648   | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
   649       q :: pretty_mixfix module module' ms ps qs;
   650 
   651 fun replace_quotes [] [] = []
   652   | replace_quotes xs (Arg :: ms) =
   653       Arg :: replace_quotes xs ms
   654   | replace_quotes xs (Ignore :: ms) =
   655       Ignore :: replace_quotes xs ms
   656   | replace_quotes xs (Module :: ms) =
   657       Module :: replace_quotes xs ms
   658   | replace_quotes xs (Pretty p :: ms) =
   659       Pretty p :: replace_quotes xs ms
   660   | replace_quotes (x::xs) (Quote _ :: ms) =
   661       Quote x :: replace_quotes xs ms;
   662 
   663 fun fillin_mixfix f ms args =
   664   let
   665     fun fillin [] [] =
   666          []
   667       | fillin (Arg :: ms) (a :: args) =
   668           f a :: fillin ms args
   669       | fillin (Ignore :: ms) args =
   670           fillin ms args
   671       | fillin (Module :: ms) args =
   672           fillin ms args
   673       | fillin (Pretty p :: ms) args =
   674           p :: fillin ms args
   675       | fillin (Quote q :: ms) args =
   676           f q :: fillin ms args
   677   in Pretty.block (fillin ms args) end;
   678 
   679 
   680 (**** default code generators ****)
   681 
   682 fun eta_expand t ts i =
   683   let
   684     val (Ts, _) = strip_type (fastype_of t);
   685     val j = i - length ts
   686   in
   687     foldr (fn (T, t) => Abs ("x", T, t))
   688       (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
   689   end;
   690 
   691 fun mk_app _ p [] = p
   692   | mk_app brack p ps = if brack then
   693        Pretty.block (Pretty.str "(" ::
   694          separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"])
   695      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   696 
   697 fun new_names t xs = Name.variant_list
   698   (map (fst o fst o dest_Var) (term_vars t) union
   699     add_term_names (t, ML_Syntax.reserved_names)) (map mk_id xs);
   700 
   701 fun new_name t x = hd (new_names t [x]);
   702 
   703 fun if_library x y = if member (op =) (!mode) "library" then x else y;
   704 
   705 fun default_codegen thy defs gr dep module brack t =
   706   let
   707     val (u, ts) = strip_comb t;
   708     fun codegens brack = foldl_map (invoke_codegen thy defs dep module brack)
   709   in (case u of
   710       Var ((s, i), T) =>
   711         let
   712           val (gr', ps) = codegens true (gr, ts);
   713           val (gr'', _) = invoke_tycodegen thy defs dep module false (gr', T)
   714         in SOME (gr'', mk_app brack (Pretty.str (s ^
   715            (if i=0 then "" else string_of_int i))) ps)
   716         end
   717 
   718     | Free (s, T) =>
   719         let
   720           val (gr', ps) = codegens true (gr, ts);
   721           val (gr'', _) = invoke_tycodegen thy defs dep module false (gr', T)
   722         in SOME (gr'', mk_app brack (Pretty.str s) ps) end
   723 
   724     | Const (s, T) =>
   725       (case get_assoc_code thy (s, T) of
   726          SOME (ms, aux) =>
   727            let val i = num_args_of ms
   728            in if length ts < i then
   729                default_codegen thy defs gr dep module brack (eta_expand u ts i)
   730              else
   731                let
   732                  val (ts1, ts2) = args_of ms ts;
   733                  val (gr1, ps1) = codegens false (gr, ts1);
   734                  val (gr2, ps2) = codegens true (gr1, ts2);
   735                  val (gr3, ps3) = codegens false (gr2, quotes_of ms);
   736                  val (gr4, _) = invoke_tycodegen thy defs dep module false
   737                    (gr3, funpow (length ts) (hd o tl o snd o dest_Type) T);
   738                  val (module', suffix) = (case get_defn thy defs s T of
   739                      NONE => (if_library (thyname_of_const s thy) module, "")
   740                    | SOME ((U, (module', _)), NONE) =>
   741                        (if_library module' module, "")
   742                    | SOME ((U, (module', _)), SOME i) =>
   743                        (if_library module' module, " def" ^ string_of_int i));
   744                  val node_id = s ^ suffix;
   745                  fun p module' = mk_app brack (Pretty.block
   746                    (pretty_mixfix module module' ms ps1 ps3)) ps2
   747                in SOME (case try (get_node gr4) node_id of
   748                    NONE => (case get_aux_code aux of
   749                        [] => (gr4, p module)
   750                      | xs => (add_edge (node_id, dep) (new_node
   751                          (node_id, (NONE, module', space_implode "\n" xs ^ "\n")) gr4),
   752                            p module'))
   753                  | SOME (_, module'', _) =>
   754                      (add_edge (node_id, dep) gr4, p module''))
   755                end
   756            end
   757        | NONE => (case get_defn thy defs s T of
   758            NONE => NONE
   759          | SOME ((U, (thyname, (args, rhs))), k) =>
   760              let
   761                val module' = if_library thyname module;
   762                val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   763                val node_id = s ^ suffix;
   764                val (gr', (ps, def_id)) = codegens true (gr, ts) |>>>
   765                  mk_const_id module' (s ^ suffix);
   766                val p = mk_app brack (Pretty.str (mk_qual_id module def_id)) ps
   767              in SOME (case try (get_node gr') node_id of
   768                  NONE =>
   769                    let
   770                      val _ = message ("expanding definition of " ^ s);
   771                      val (Ts, _) = strip_type U;
   772                      val (args', rhs') =
   773                        if not (null args) orelse null Ts then (args, rhs) else
   774                          let val v = Free (new_name rhs "x", hd Ts)
   775                          in ([v], betapply (rhs, v)) end;
   776                      val (gr1, p') = invoke_codegen thy defs node_id module' false
   777                        (add_edge (node_id, dep)
   778                           (new_node (node_id, (NONE, "", "")) gr'), rhs');
   779                      val (gr2, xs) = codegens false (gr1, args');
   780                      val (gr3, _) = invoke_tycodegen thy defs dep module false (gr2, T);
   781                      val (gr4, ty) = invoke_tycodegen thy defs node_id module' false (gr3, U);
   782                    in (map_node node_id (K (NONE, module', Pretty.string_of
   783                        (Pretty.block (separate (Pretty.brk 1)
   784                          (if null args' then
   785                             [Pretty.str ("val " ^ snd def_id ^ " :"), ty]
   786                           else Pretty.str ("fun " ^ snd def_id) :: xs) @
   787                         [Pretty.str " =", Pretty.brk 1, p', Pretty.str ";"])) ^ "\n\n")) gr4,
   788                      p)
   789                    end
   790                | SOME _ => (add_edge (node_id, dep) gr', p))
   791              end))
   792 
   793     | Abs _ =>
   794       let
   795         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   796         val t = strip_abs_body u
   797         val bs' = new_names t bs;
   798         val (gr1, ps) = codegens true (gr, ts);
   799         val (gr2, p) = invoke_codegen thy defs dep module false
   800           (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
   801       in
   802         SOME (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
   803           [Pretty.str ")"])) ps)
   804       end
   805 
   806     | _ => NONE)
   807   end;
   808 
   809 fun default_tycodegen thy defs gr dep module brack (TVar ((s, i), _)) =
   810       SOME (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
   811   | default_tycodegen thy defs gr dep module brack (TFree (s, _)) =
   812       SOME (gr, Pretty.str s)
   813   | default_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   814       (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   815          NONE => NONE
   816        | SOME (ms, aux) =>
   817            let
   818              val (gr', ps) = foldl_map
   819                (invoke_tycodegen thy defs dep module false)
   820                (gr, fst (args_of ms Ts));
   821              val (gr'', qs) = foldl_map
   822                (invoke_tycodegen thy defs dep module false)
   823                (gr', quotes_of ms);
   824              val module' = if_library (thyname_of_type s thy) module;
   825              val node_id = s ^ " (type)";
   826              fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   827            in SOME (case try (get_node gr'') node_id of
   828                NONE => (case get_aux_code aux of
   829                    [] => (gr'', p module')
   830                  | xs => (fst (mk_type_id module' s
   831                        (add_edge (node_id, dep) (new_node (node_id,
   832                          (NONE, module', space_implode "\n" xs ^ "\n")) gr''))),
   833                      p module'))
   834              | SOME (_, module'', _) =>
   835                  (add_edge (node_id, dep) gr'', p module''))
   836            end);
   837 
   838 val _ = Context.add_setup
   839  (add_codegen "default" default_codegen #>
   840   add_tycodegen "default" default_tycodegen);
   841 
   842 
   843 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   844 
   845 fun add_to_module name s = AList.map_entry (op =) name (suffix s);
   846 
   847 fun output_code gr module xs =
   848   let
   849     val code = map_filter (fn s =>
   850       let val c as (_, module', _) = Graph.get_node gr s
   851       in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   852         (rev (Graph.all_preds gr xs));
   853     fun string_of_cycle (a :: b :: cs) =
   854           let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   855             if a = a' then Option.map (pair x)
   856               (find_first (equal b o #2 o Graph.get_node gr)
   857                 (Graph.imm_succs gr x))
   858             else NONE) code
   859           in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   860       | string_of_cycle _ = ""
   861   in
   862     if module = "" then
   863       let
   864         val modules = distinct (op =) (map (#2 o snd) code);
   865         val mod_gr = foldr (uncurry Graph.add_edge_acyclic)
   866           (foldr (uncurry (Graph.new_node o rpair ())) Graph.empty modules)
   867           (maps (fn (s, (_, module, _)) => map (pair module)
   868             (filter_out (equal module) (map (#2 o Graph.get_node gr)
   869               (Graph.imm_succs gr s)))) code);
   870         val modules' =
   871           rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   872       in
   873         foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   874           (map (rpair "") modules') code
   875       end handle Graph.CYCLES (cs :: _) =>
   876         error ("Cyclic dependency of modules:\n" ^ commas cs ^
   877           "\n" ^ string_of_cycle cs)
   878     else [(module, implode (map (#3 o snd) code))]
   879   end;
   880 
   881 fun gen_generate_code prep_term thy modules module =
   882   setmp print_mode [] (Pretty.setmp_margin (!margin) (fn xs =>
   883   let
   884     val _ = (module <> "" orelse
   885         member (op =) (!mode) "library" andalso forall (equal "" o fst) xs)
   886       orelse error "missing module name";
   887     val graphs = get_modules thy;
   888     val defs = mk_deftab thy;
   889     val gr = new_node ("<Top>", (NONE, module, ""))
   890       (foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   891         (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   892            module = module') (gr, gr'),
   893          (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   894            (map (fn s => case Symtab.lookup graphs s of
   895                 NONE => error ("Undefined code module: " ^ s)
   896               | SOME gr => gr) modules))
   897       handle Graph.DUPS ks => error ("Duplicate code for " ^ commas ks);
   898     fun expand (t as Abs _) = t
   899       | expand t = (case fastype_of t of
   900           Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   901     val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
   902       (invoke_codegen thy defs "<Top>" module false (gr, t)))
   903         (gr, map (apsnd (expand o preprocess_term thy o prep_term thy)) xs);
   904     val code = map_filter
   905       (fn ("", _) => NONE
   906         | (s', p) => SOME (Pretty.string_of (Pretty.block
   907           [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"]))) ps;
   908     val code' = space_implode "\n\n" code ^ "\n\n";
   909     val code'' =
   910       map_filter (fn (name, s) =>
   911           if member (op =) (!mode) "library" andalso name = module andalso null code
   912           then NONE
   913           else SOME (name, mk_struct name s))
   914         ((if null code then I
   915           else add_to_module module code')
   916            (output_code (fst gr') (if_library "" module) ["<Top>"]))
   917   in
   918     (code'', del_nodes ["<Top>"] gr')
   919   end));
   920 
   921 val generate_code_i = gen_generate_code Sign.cert_term;
   922 val generate_code = gen_generate_code Sign.read_term;
   923 
   924 
   925 (**** Reflection ****)
   926 
   927 val strip_tname = implode o tl o explode;
   928 
   929 fun pretty_list xs = Pretty.block (Pretty.str "[" ::
   930   flat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
   931   [Pretty.str "]"]);
   932 
   933 fun mk_type p (TVar ((s, i), _)) = Pretty.str
   934       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   935   | mk_type p (TFree (s, _)) = Pretty.str (strip_tname s ^ "T")
   936   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   937       [Pretty.str "Type", Pretty.brk 1, Pretty.str ("(\"" ^ s ^ "\","),
   938        Pretty.brk 1, pretty_list (map (mk_type false) Ts), Pretty.str ")"]);
   939 
   940 fun mk_term_of gr module p (TVar ((s, i), _)) = Pretty.str
   941       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   942   | mk_term_of gr module p (TFree (s, _)) = Pretty.str (strip_tname s ^ "F")
   943   | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   944       (Pretty.block (separate (Pretty.brk 1)
   945         (Pretty.str (mk_qual_id module
   946           (get_type_id' (fn s' => "term_of_" ^ s') s gr)) ::
   947         maps (fn T =>
   948           [mk_term_of gr module true T, mk_type true T]) Ts)));
   949 
   950 
   951 (**** Test data generators ****)
   952 
   953 fun mk_gen gr module p xs a (TVar ((s, i), _)) = Pretty.str
   954       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   955   | mk_gen gr module p xs a (TFree (s, _)) = Pretty.str (strip_tname s ^ "G")
   956   | mk_gen gr module p xs a (Type (s, Ts)) = (if p then parens else I)
   957       (Pretty.block (separate (Pretty.brk 1)
   958         (Pretty.str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') s gr) ^
   959           (if member (op =) xs s then "'" else "")) ::
   960          map (mk_gen gr module true xs a) Ts @
   961          (if member (op =) xs s then [Pretty.str a] else []))));
   962 
   963 val test_fn : (int -> (string * term) list option) ref = ref (fn _ => NONE);
   964 
   965 fun test_term thy sz i t =
   966   let
   967     val _ = (null (term_tvars t) andalso null (term_tfrees t)) orelse
   968       error "Term to be tested contains type variables";
   969     val _ = null (term_vars t) orelse
   970       error "Term to be tested contains schematic variables";
   971     val frees = map dest_Free (term_frees t);
   972     val frees' = frees ~~
   973       map (fn i => "arg" ^ string_of_int i) (1 upto length frees);
   974     val (code, gr) = setmp mode ["term_of", "test"]
   975       (generate_code_i thy [] "Generated") [("testf", list_abs_free (frees, t))];
   976     val s = setmp print_mode [] (fn () => "structure TestTerm =\nstruct\n\n" ^
   977       space_implode "\n" (map snd code) ^
   978       "\nopen Generated;\n\n" ^ Pretty.string_of
   979         (Pretty.block [Pretty.str "val () = Codegen.test_fn :=",
   980           Pretty.brk 1, Pretty.str ("(fn i =>"), Pretty.brk 1,
   981           Pretty.blk (0, [Pretty.str "let", Pretty.brk 1,
   982             Pretty.blk (0, separate Pretty.fbrk (map (fn ((s, T), s') =>
   983               Pretty.block [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1,
   984               mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   985               Pretty.str "i;"]) frees')),
   986             Pretty.brk 1, Pretty.str "in", Pretty.brk 1,
   987             Pretty.block [Pretty.str "if ",
   988               mk_app false (Pretty.str "testf") (map (Pretty.str o snd) frees'),
   989               Pretty.brk 1, Pretty.str "then NONE",
   990               Pretty.brk 1, Pretty.str "else ",
   991               Pretty.block [Pretty.str "SOME ", Pretty.block (Pretty.str "[" ::
   992                 flat (separate [Pretty.str ",", Pretty.brk 1]
   993                   (map (fn ((s, T), s') => [Pretty.block
   994                     [Pretty.str ("(" ^ quote (Symbol.escape s) ^ ","), Pretty.brk 1,
   995                      mk_app false (mk_term_of gr "Generated" false T)
   996                        [Pretty.str s'], Pretty.str ")"]]) frees')) @
   997                   [Pretty.str "]"])]],
   998             Pretty.brk 1, Pretty.str "end"]), Pretty.str ");"]) ^
   999       "\n\nend;\n") ();
  1000     val _ = use_text "" Output.ml_output false s;
  1001     fun iter f k = if k > i then NONE
  1002       else (case (f () handle Match =>
  1003           (warning "Exception Match raised in generated code"; NONE)) of
  1004         NONE => iter f (k+1) | SOME x => SOME x);
  1005     fun test k = if k > sz then NONE
  1006       else (priority ("Test data size: " ^ string_of_int k);
  1007         case iter (fn () => !test_fn k) 1 of
  1008           NONE => test (k+1) | SOME x => SOME x);
  1009   in test 0 end;
  1010 
  1011 fun test_goal ({size, iterations, default_type}, tvinsts) i st =
  1012   let
  1013     val thy = Toplevel.theory_of st;
  1014     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
  1015       | strip t = t;
  1016     val (gi, frees) = Logic.goal_params
  1017       (prop_of (snd (snd (Proof.get_goal (Toplevel.proof_of st))))) i;
  1018     val gi' = ObjectLogic.atomize_term thy (map_types
  1019       (map_type_tfree (fn p as (s, _) =>
  1020         the_default (the_default (TFree p) default_type)
  1021           (AList.lookup (op =) tvinsts s))) (subst_bounds (frees, strip gi)));
  1022   in case test_term (Toplevel.theory_of st) size iterations gi' of
  1023       NONE => writeln "No counterexamples found."
  1024     | SOME cex => writeln ("Counterexample found:\n" ^
  1025         Pretty.string_of (Pretty.chunks (map (fn (s, t) =>
  1026           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1,
  1027             Sign.pretty_term thy t]) cex)))
  1028   end;
  1029 
  1030 
  1031 (**** Evaluator for terms ****)
  1032 
  1033 val eval_result = ref (Bound 0);
  1034 
  1035 fun eval_term thy = setmp print_mode [] (fn t =>
  1036   let
  1037     val _ = (null (term_tvars t) andalso null (term_tfrees t)) orelse
  1038       error "Term to be evaluated contains type variables";
  1039     val _ = (null (term_vars t) andalso null (term_frees t)) orelse
  1040       error "Term to be evaluated contains variables";
  1041     val (code, gr) = setmp mode ["term_of"]
  1042       (generate_code_i thy [] "Generated") [("result", t)];
  1043     val s = "structure EvalTerm =\nstruct\n\n" ^
  1044       space_implode "\n" (map snd code) ^
  1045       "\nopen Generated;\n\n" ^ Pretty.string_of
  1046         (Pretty.block [Pretty.str "val () = Codegen.eval_result :=",
  1047           Pretty.brk 1,
  1048           mk_app false (mk_term_of gr "Generated" false (fastype_of t))
  1049             [Pretty.str "result"],
  1050           Pretty.str ";"])  ^
  1051       "\n\nend;\n";
  1052     val _ = use_text "" Output.ml_output false s
  1053   in !eval_result end);
  1054 
  1055 fun print_evaluated_term s = Toplevel.keep (fn state =>
  1056   let
  1057     val ctxt = Toplevel.context_of state;
  1058     val thy = ProofContext.theory_of ctxt;
  1059     val t = eval_term thy (ProofContext.read_term ctxt s);
  1060     val T = Term.type_of t;
  1061   in
  1062     writeln (Pretty.string_of
  1063       (Pretty.block [Pretty.quote (ProofContext.pretty_term ctxt t), Pretty.fbrk,
  1064         Pretty.str "::", Pretty.brk 1, Pretty.quote (ProofContext.pretty_typ ctxt T)]))
  1065   end);
  1066 
  1067 exception Evaluation of term;
  1068 
  1069 fun evaluation_oracle (thy, Evaluation t) =
  1070   Logic.mk_equals (t, eval_term thy t);
  1071 
  1072 fun evaluation_conv ct =
  1073   let val {thy, t, ...} = rep_cterm ct
  1074   in Thm.invoke_oracle_i thy "Pure.evaluation" (thy, Evaluation t) end;
  1075 
  1076 val _ = Context.add_setup
  1077   (Theory.add_oracle ("evaluation", evaluation_oracle));
  1078 
  1079 (**** Interface ****)
  1080 
  1081 val str = setmp print_mode [] Pretty.str;
  1082 
  1083 fun parse_mixfix rd s =
  1084   (case Scan.finite Symbol.stopper (Scan.repeat
  1085      (   $$ "_" >> K Arg
  1086       || $$ "?" >> K Ignore
  1087       || $$ "\\<module>" >> K Module
  1088       || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
  1089       || $$ "{" |-- $$ "*" |-- Scan.repeat1
  1090            (   $$ "'" |-- Scan.one Symbol.not_eof
  1091             || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --|
  1092          $$ "*" --| $$ "}" >> (Quote o rd o implode)
  1093       || Scan.repeat1
  1094            (   $$ "'" |-- Scan.one Symbol.not_eof
  1095             || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
  1096                  (Scan.one Symbol.not_eof)) >> (Pretty o str o implode)))
  1097        (Symbol.explode s) of
  1098      (p, []) => p
  1099    | _ => error ("Malformed annotation: " ^ quote s));
  1100 
  1101 val _ = Context.add_setup
  1102   (fold assoc_type [("fun", (parse_mixfix (K dummyT) "(_ ->/ _)",
  1103      [("term_of",
  1104        "fun term_of_fun_type _ T _ U _ = Free (\"<function>\", T --> U);\n"),
  1105       ("test",
  1106        "fun gen_fun_type _ G i =\n\
  1107        \  let\n\
  1108        \    val f = ref (fn x => raise Match);\n\
  1109        \    val _ = (f := (fn x =>\n\
  1110        \      let\n\
  1111        \        val y = G i;\n\
  1112        \        val f' = !f\n\
  1113        \      in (f := (fn x' => if x = x' then y else f' x'); y) end))\n\
  1114        \  in (fn x => !f x) end;\n")]))]);
  1115 
  1116 
  1117 structure P = OuterParse and K = OuterKeyword;
  1118 
  1119 fun strip_whitespace s = implode (fst (take_suffix (equal "\n" orf equal " ")
  1120   (snd (take_prefix (equal "\n" orf equal " ") (explode s))))) ^ "\n";
  1121 
  1122 val parse_attach = Scan.repeat (P.$$$ "attach" |--
  1123   Scan.optional (P.$$$ "(" |-- P.xname --| P.$$$ ")") "" --
  1124     (P.verbatim >> strip_whitespace));
  1125 
  1126 val assoc_typeP =
  1127   OuterSyntax.command "types_code"
  1128   "associate types with target language types" K.thy_decl
  1129     (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
  1130      (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
  1131        (fn ((name, mfx), aux) => (name, (parse_mixfix
  1132          (Sign.read_typ thy) mfx, aux)))) xs thy)));
  1133 
  1134 val assoc_constP =
  1135   OuterSyntax.command "consts_code"
  1136   "associate constants with target language code" K.thy_decl
  1137     (Scan.repeat1
  1138        (P.term --|
  1139         P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
  1140      (fn xs => Toplevel.theory (fn thy => fold (assoc_const o 
  1141        (fn ((const, mfx), aux) =>
  1142          (const, (parse_mixfix (Sign.read_term thy) mfx, aux)))) xs thy)));
  1143 
  1144 fun parse_code lib =
  1145   Scan.optional (P.$$$ "(" |-- P.enum "," P.xname --| P.$$$ ")") (!mode) --
  1146   (if lib then Scan.optional P.name "" else P.name) --
  1147   Scan.option (P.$$$ "file" |-- P.name) --
  1148   (if lib then Scan.succeed []
  1149    else Scan.optional (P.$$$ "imports" |-- Scan.repeat1 P.name) []) --|
  1150   P.$$$ "contains" --
  1151   (   Scan.repeat1 (P.name --| P.$$$ "=" -- P.term)
  1152    || Scan.repeat1 (P.term >> pair "")) >>
  1153   (fn ((((mode', module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
  1154      let
  1155        val mode'' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode');
  1156        val (code, gr) = setmp mode mode'' (generate_code thy modules module) xs
  1157      in ((case opt_fname of
  1158          NONE => use_text "" Output.ml_output false
  1159            (space_implode "\n" (map snd code))
  1160        | SOME fname =>
  1161            if lib then
  1162              app (fn (name, s) => File.write
  1163                  (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
  1164                (("ROOT", implode (map (fn (name, _) =>
  1165                    "use \"" ^ name ^ ".ML\";\n") code)) :: code)
  1166            else File.write (Path.explode fname) (snd (hd code)));
  1167            if lib then thy
  1168            else map_modules (Symtab.update (module, gr)) thy)
  1169      end));
  1170 
  1171 val code_libraryP =
  1172   OuterSyntax.command "code_library"
  1173     "generates code for terms (one structure for each theory)" K.thy_decl
  1174     (parse_code true);
  1175 
  1176 val code_moduleP =
  1177   OuterSyntax.command "code_module"
  1178     "generates code for terms (single structure, incremental)" K.thy_decl
  1179     (parse_code false);
  1180 
  1181 val params =
  1182   [("size", P.nat >> (K o set_size)),
  1183    ("iterations", P.nat >> (K o set_iterations)),
  1184    ("default_type", P.typ >> set_default_type)];
  1185 
  1186 val parse_test_params = P.short_ident :-- (fn s =>
  1187   P.$$$ "=" |-- (AList.lookup (op =) params s |> the_default Scan.fail)) >> snd;
  1188 
  1189 fun parse_tyinst xs =
  1190   (P.type_ident --| P.$$$ "=" -- P.typ >> (fn (v, s) => fn thy =>
  1191     fn (x, ys) => (x, (v, Sign.read_typ thy s) :: ys))) xs;
  1192 
  1193 fun app [] x = x
  1194   | app (f :: fs) x = app fs (f x);
  1195 
  1196 val test_paramsP =
  1197   OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl
  1198     (P.$$$ "[" |-- P.list1 parse_test_params --| P.$$$ "]" >>
  1199       (fn fs => Toplevel.theory (fn thy =>
  1200          map_test_params (app (map (fn f => f thy) fs)) thy)));
  1201 
  1202 val testP =
  1203   OuterSyntax.command "quickcheck" "try to find counterexample for subgoal" K.diag
  1204   (Scan.option (P.$$$ "[" |-- P.list1
  1205     (   parse_test_params >> (fn f => fn thy => apfst (f thy))
  1206      || parse_tyinst) --| P.$$$ "]") -- Scan.optional P.nat 1 >>
  1207     (fn (ps, g) => Toplevel.keep (fn st =>
  1208       test_goal (app (the_default [] (Option.map (map (fn f => f (Toplevel.theory_of st))) ps))
  1209         (get_test_params (Toplevel.theory_of st), [])) g st)));
  1210 
  1211 val valueP =
  1212   OuterSyntax.improper_command "value" "read, evaluate and print term" K.diag
  1213     (P.term >> (Toplevel.no_timing oo print_evaluated_term));
  1214 
  1215 val _ = OuterSyntax.add_keywords ["attach", "file", "contains"];
  1216 
  1217 val _ = OuterSyntax.add_parsers
  1218   [assoc_typeP, assoc_constP, code_libraryP, code_moduleP, test_paramsP, testP, valueP];
  1219 
  1220 end;