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