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