src/Pure/codegen.ML
author haftmann
Fri Aug 10 17:04:34 2007 +0200 (2007-08-10)
changeset 24219 e558fe311376
parent 24166 7b28dc69bdbb
child 24280 c9867bdf2424
permissions -rw-r--r--
new structure for code generator modules
     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 -> int -> int -> term -> (string * term) list option
    77   val eval_result: term ref
    78   val eval_term: theory -> term -> term
    79   val evaluation_conv: cterm -> thm
    80   val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    81   val quotes_of: 'a mixfix list -> 'a list
    82   val num_args_of: 'a mixfix list -> int
    83   val replace_quotes: 'b list -> 'a mixfix list -> 'b mixfix list
    84   val fillin_mixfix: ('a -> Pretty.T) -> 'a mixfix list -> 'a list -> Pretty.T
    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 fun fillin_mixfix f ms args =
   627   let
   628     fun fillin [] [] =
   629          []
   630       | fillin (Arg :: ms) (a :: args) =
   631           f a :: fillin ms args
   632       | fillin (Ignore :: ms) args =
   633           fillin ms args
   634       | fillin (Module :: ms) args =
   635           fillin ms args
   636       | fillin (Pretty p :: ms) args =
   637           p :: fillin ms args
   638       | fillin (Quote q :: ms) args =
   639           f q :: fillin ms args
   640   in Pretty.block (fillin ms args) end;
   641 
   642 
   643 (**** default code generators ****)
   644 
   645 fun eta_expand t ts i =
   646   let
   647     val (Ts, _) = strip_type (fastype_of t);
   648     val j = i - length ts
   649   in
   650     List.foldr (fn (T, t) => Abs ("x", T, t))
   651       (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
   652   end;
   653 
   654 fun mk_app _ p [] = p
   655   | mk_app brack p ps = if brack then
   656        Pretty.block (Pretty.str "(" ::
   657          separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"])
   658      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   659 
   660 fun new_names t xs = Name.variant_list
   661   (map (fst o fst o dest_Var) (term_vars t) union
   662     add_term_names (t, ML_Syntax.reserved_names)) (map mk_id xs);
   663 
   664 fun new_name t x = hd (new_names t [x]);
   665 
   666 fun if_library x y = if member (op =) (!mode) "library" then x else y;
   667 
   668 fun default_codegen thy defs gr dep module brack t =
   669   let
   670     val (u, ts) = strip_comb t;
   671     fun codegens brack = foldl_map (invoke_codegen thy defs dep module brack)
   672   in (case u of
   673       Var ((s, i), T) =>
   674         let
   675           val (gr', ps) = codegens true (gr, ts);
   676           val (gr'', _) = invoke_tycodegen thy defs dep module false (gr', T)
   677         in SOME (gr'', mk_app brack (Pretty.str (s ^
   678            (if i=0 then "" else string_of_int i))) ps)
   679         end
   680 
   681     | Free (s, T) =>
   682         let
   683           val (gr', ps) = codegens true (gr, ts);
   684           val (gr'', _) = invoke_tycodegen thy defs dep module false (gr', T)
   685         in SOME (gr'', mk_app brack (Pretty.str s) ps) end
   686 
   687     | Const (s, T) =>
   688       (case get_assoc_code thy (s, T) of
   689          SOME (ms, aux) =>
   690            let val i = num_args_of ms
   691            in if length ts < i then
   692                default_codegen thy defs gr dep module brack (eta_expand u ts i)
   693              else
   694                let
   695                  val (ts1, ts2) = args_of ms ts;
   696                  val (gr1, ps1) = codegens false (gr, ts1);
   697                  val (gr2, ps2) = codegens true (gr1, ts2);
   698                  val (gr3, ps3) = codegens false (gr2, quotes_of ms);
   699                  val (gr4, _) = invoke_tycodegen thy defs dep module false
   700                    (gr3, funpow (length ts) (hd o tl o snd o dest_Type) T);
   701                  val (module', suffix) = (case get_defn thy defs s T of
   702                      NONE => (if_library (thyname_of_const s thy) module, "")
   703                    | SOME ((U, (module', _)), NONE) =>
   704                        (if_library module' module, "")
   705                    | SOME ((U, (module', _)), SOME i) =>
   706                        (if_library module' module, " def" ^ string_of_int i));
   707                  val node_id = s ^ suffix;
   708                  fun p module' = mk_app brack (Pretty.block
   709                    (pretty_mixfix module module' ms ps1 ps3)) ps2
   710                in SOME (case try (get_node gr4) node_id of
   711                    NONE => (case get_aux_code aux of
   712                        [] => (gr4, p module)
   713                      | xs => (add_edge (node_id, dep) (new_node
   714                          (node_id, (NONE, module', space_implode "\n" xs ^ "\n")) gr4),
   715                            p module'))
   716                  | SOME (_, module'', _) =>
   717                      (add_edge (node_id, dep) gr4, p module''))
   718                end
   719            end
   720        | NONE => (case get_defn thy defs s T of
   721            NONE => NONE
   722          | SOME ((U, (thyname, (args, rhs))), k) =>
   723              let
   724                val module' = if_library thyname module;
   725                val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
   726                val node_id = s ^ suffix;
   727                val (gr', (ps, def_id)) = codegens true (gr, ts) |>>>
   728                  mk_const_id module' (s ^ suffix);
   729                val p = mk_app brack (Pretty.str (mk_qual_id module def_id)) ps
   730              in SOME (case try (get_node gr') node_id of
   731                  NONE =>
   732                    let
   733                      val _ = message ("expanding definition of " ^ s);
   734                      val (Ts, _) = strip_type U;
   735                      val (args', rhs') =
   736                        if not (null args) orelse null Ts then (args, rhs) else
   737                          let val v = Free (new_name rhs "x", hd Ts)
   738                          in ([v], betapply (rhs, v)) end;
   739                      val (gr1, p') = invoke_codegen thy defs node_id module' false
   740                        (add_edge (node_id, dep)
   741                           (new_node (node_id, (NONE, "", "")) gr'), rhs');
   742                      val (gr2, xs) = codegens false (gr1, args');
   743                      val (gr3, _) = invoke_tycodegen thy defs dep module false (gr2, T);
   744                      val (gr4, ty) = invoke_tycodegen thy defs node_id module' false (gr3, U);
   745                    in (map_node node_id (K (NONE, module', Pretty.string_of
   746                        (Pretty.block (separate (Pretty.brk 1)
   747                          (if null args' then
   748                             [Pretty.str ("val " ^ snd def_id ^ " :"), ty]
   749                           else Pretty.str ("fun " ^ snd def_id) :: xs) @
   750                         [Pretty.str " =", Pretty.brk 1, p', Pretty.str ";"])) ^ "\n\n")) gr4,
   751                      p)
   752                    end
   753                | SOME _ => (add_edge (node_id, dep) gr', p))
   754              end))
   755 
   756     | Abs _ =>
   757       let
   758         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   759         val t = strip_abs_body u
   760         val bs' = new_names t bs;
   761         val (gr1, ps) = codegens true (gr, ts);
   762         val (gr2, p) = invoke_codegen thy defs dep module false
   763           (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
   764       in
   765         SOME (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
   766           [Pretty.str ")"])) ps)
   767       end
   768 
   769     | _ => NONE)
   770   end;
   771 
   772 fun default_tycodegen thy defs gr dep module brack (TVar ((s, i), _)) =
   773       SOME (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
   774   | default_tycodegen thy defs gr dep module brack (TFree (s, _)) =
   775       SOME (gr, Pretty.str s)
   776   | default_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   777       (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
   778          NONE => NONE
   779        | SOME (ms, aux) =>
   780            let
   781              val (gr', ps) = foldl_map
   782                (invoke_tycodegen thy defs dep module false)
   783                (gr, fst (args_of ms Ts));
   784              val (gr'', qs) = foldl_map
   785                (invoke_tycodegen thy defs dep module false)
   786                (gr', quotes_of ms);
   787              val module' = if_library (thyname_of_type s thy) module;
   788              val node_id = s ^ " (type)";
   789              fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
   790            in SOME (case try (get_node gr'') node_id of
   791                NONE => (case get_aux_code aux of
   792                    [] => (gr'', p module')
   793                  | xs => (fst (mk_type_id module' s
   794                        (add_edge (node_id, dep) (new_node (node_id,
   795                          (NONE, module', space_implode "\n" xs ^ "\n")) gr''))),
   796                      p module'))
   797              | SOME (_, module'', _) =>
   798                  (add_edge (node_id, dep) gr'', p module''))
   799            end);
   800 
   801 val _ = Context.add_setup
   802  (add_codegen "default" default_codegen #>
   803   add_tycodegen "default" default_tycodegen);
   804 
   805 
   806 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
   807 
   808 fun add_to_module name s = AList.map_entry (op =) name (suffix s);
   809 
   810 fun output_code gr module xs =
   811   let
   812     val code = map_filter (fn s =>
   813       let val c as (_, module', _) = Graph.get_node gr s
   814       in if module = "" orelse module = module' then SOME (s, c) else NONE end)
   815         (rev (Graph.all_preds gr xs));
   816     fun string_of_cycle (a :: b :: cs) =
   817           let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
   818             if a = a' then Option.map (pair x)
   819               (find_first (equal b o #2 o Graph.get_node gr)
   820                 (Graph.imm_succs gr x))
   821             else NONE) code
   822           in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
   823       | string_of_cycle _ = ""
   824   in
   825     if module = "" then
   826       let
   827         val modules = distinct (op =) (map (#2 o snd) code);
   828         val mod_gr = fold_rev Graph.add_edge_acyclic
   829           (maps (fn (s, (_, module, _)) => map (pair module)
   830             (filter_out (equal module) (map (#2 o Graph.get_node gr)
   831               (Graph.imm_succs gr s)))) code)
   832           (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
   833         val modules' =
   834           rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
   835       in
   836         List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
   837           (map (rpair "") modules') code
   838       end handle Graph.CYCLES (cs :: _) =>
   839         error ("Cyclic dependency of modules:\n" ^ commas cs ^
   840           "\n" ^ string_of_cycle cs)
   841     else [(module, implode (map (#3 o snd) code))]
   842   end;
   843 
   844 fun gen_generate_code prep_term thy modules module =
   845   PrintMode.with_default (Pretty.setmp_margin (!margin) (fn xs =>
   846   let
   847     val _ = (module <> "" orelse
   848         member (op =) (!mode) "library" andalso forall (equal "" o fst) xs)
   849       orelse error "missing module name";
   850     val graphs = get_modules thy;
   851     val defs = mk_deftab thy;
   852     val gr = new_node ("<Top>", (NONE, module, ""))
   853       (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
   854         (Graph.merge (fn ((_, module, _), (_, module', _)) =>
   855            module = module') (gr, gr'),
   856          (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
   857            (map (fn s => case Symtab.lookup graphs s of
   858                 NONE => error ("Undefined code module: " ^ s)
   859               | SOME gr => gr) modules))
   860       handle Graph.DUP k => error ("Duplicate code for " ^ k);
   861     fun expand (t as Abs _) = t
   862       | expand t = (case fastype_of t of
   863           Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
   864     val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
   865       (invoke_codegen thy defs "<Top>" module false (gr, t)))
   866         (gr, map (apsnd (expand o preprocess_term thy o prep_term thy)) xs);
   867     val code = map_filter
   868       (fn ("", _) => NONE
   869         | (s', p) => SOME (Pretty.string_of (Pretty.block
   870           [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"]))) ps;
   871     val code' = space_implode "\n\n" code ^ "\n\n";
   872     val code'' =
   873       map_filter (fn (name, s) =>
   874           if member (op =) (!mode) "library" andalso name = module andalso null code
   875           then NONE
   876           else SOME (name, mk_struct name s))
   877         ((if null code then I
   878           else add_to_module module code')
   879            (output_code (fst gr') (if_library "" module) ["<Top>"]))
   880   in
   881     (code'', del_nodes ["<Top>"] gr')
   882   end));
   883 
   884 val generate_code_i = gen_generate_code Sign.cert_term;
   885 val generate_code = gen_generate_code Sign.read_term;
   886 
   887 
   888 (**** Reflection ****)
   889 
   890 val strip_tname = implode o tl o explode;
   891 
   892 fun pretty_list xs = Pretty.block (Pretty.str "[" ::
   893   flat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
   894   [Pretty.str "]"]);
   895 
   896 fun mk_type p (TVar ((s, i), _)) = Pretty.str
   897       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   898   | mk_type p (TFree (s, _)) = Pretty.str (strip_tname s ^ "T")
   899   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   900       [Pretty.str "Type", Pretty.brk 1, Pretty.str ("(\"" ^ s ^ "\","),
   901        Pretty.brk 1, pretty_list (map (mk_type false) Ts), Pretty.str ")"]);
   902 
   903 fun mk_term_of gr module p (TVar ((s, i), _)) = Pretty.str
   904       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   905   | mk_term_of gr module p (TFree (s, _)) = Pretty.str (strip_tname s ^ "F")
   906   | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
   907       (Pretty.block (separate (Pretty.brk 1)
   908         (Pretty.str (mk_qual_id module
   909           (get_type_id' (fn s' => "term_of_" ^ s') s gr)) ::
   910         maps (fn T =>
   911           [mk_term_of gr module true T, mk_type true T]) Ts)));
   912 
   913 
   914 (**** Test data generators ****)
   915 
   916 fun mk_gen gr module p xs a (TVar ((s, i), _)) = Pretty.str
   917       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   918   | mk_gen gr module p xs a (TFree (s, _)) = Pretty.str (strip_tname s ^ "G")
   919   | mk_gen gr module p xs a (Type (s, Ts)) = (if p then parens else I)
   920       (Pretty.block (separate (Pretty.brk 1)
   921         (Pretty.str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') s gr) ^
   922           (if member (op =) xs s then "'" else "")) ::
   923          map (mk_gen gr module true xs a) Ts @
   924          (if member (op =) xs s then [Pretty.str a] else []))));
   925 
   926 val test_fn : (int -> (string * term) list option) ref = ref (fn _ => NONE);
   927 
   928 fun test_term thy sz i t =
   929   let
   930     val _ = (null (term_tvars t) andalso null (term_tfrees t)) orelse
   931       error "Term to be tested contains type variables";
   932     val _ = null (term_vars t) orelse
   933       error "Term to be tested contains schematic variables";
   934     val frees = map dest_Free (term_frees t);
   935     val frees' = frees ~~
   936       map (fn i => "arg" ^ string_of_int i) (1 upto length frees);
   937     val (code, gr) = setmp mode ["term_of", "test"]
   938       (generate_code_i thy [] "Generated") [("testf", list_abs_free (frees, t))];
   939     val s = PrintMode.with_default (fn () => "structure TestTerm =\nstruct\n\n" ^
   940       space_implode "\n" (map snd code) ^
   941       "\nopen Generated;\n\n" ^ Pretty.string_of
   942         (Pretty.block [Pretty.str "val () = Codegen.test_fn :=",
   943           Pretty.brk 1, Pretty.str ("(fn i =>"), Pretty.brk 1,
   944           Pretty.blk (0, [Pretty.str "let", Pretty.brk 1,
   945             Pretty.blk (0, separate Pretty.fbrk (map (fn ((s, T), s') =>
   946               Pretty.block [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1,
   947               mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
   948               Pretty.str "i;"]) frees')),
   949             Pretty.brk 1, Pretty.str "in", Pretty.brk 1,
   950             Pretty.block [Pretty.str "if ",
   951               mk_app false (Pretty.str "testf") (map (Pretty.str o snd) frees'),
   952               Pretty.brk 1, Pretty.str "then NONE",
   953               Pretty.brk 1, Pretty.str "else ",
   954               Pretty.block [Pretty.str "SOME ", Pretty.block (Pretty.str "[" ::
   955                 flat (separate [Pretty.str ",", Pretty.brk 1]
   956                   (map (fn ((s, T), s') => [Pretty.block
   957                     [Pretty.str ("(" ^ quote (Symbol.escape s) ^ ","), Pretty.brk 1,
   958                      mk_app false (mk_term_of gr "Generated" false T)
   959                        [Pretty.str s'], Pretty.str ")"]]) frees')) @
   960                   [Pretty.str "]"])]],
   961             Pretty.brk 1, Pretty.str "end"]), Pretty.str ");"]) ^
   962       "\n\nend;\n") ();
   963     val _ = use_text "" Output.ml_output false s;
   964     fun iter f k = if k > i then NONE
   965       else (case (f () handle Match =>
   966           (warning "Exception Match raised in generated code"; NONE)) of
   967         NONE => iter f (k+1) | SOME x => SOME x);
   968     fun test k = if k > sz then NONE
   969       else (priority ("Test data size: " ^ string_of_int k);
   970         case iter (fn () => !test_fn k) 1 of
   971           NONE => test (k+1) | SOME x => SOME x);
   972   in test 0 end;
   973 
   974 fun test_goal ({size, iterations, default_type}, tvinsts) i st =
   975   let
   976     val thy = Toplevel.theory_of st;
   977     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
   978       | strip t = t;
   979     val (gi, frees) = Logic.goal_params
   980       (prop_of (snd (snd (Proof.get_goal (Toplevel.proof_of st))))) i;
   981     val gi' = ObjectLogic.atomize_term thy (map_types
   982       (map_type_tfree (fn p as (s, _) =>
   983         the_default (the_default (TFree p) default_type)
   984           (AList.lookup (op =) tvinsts s))) (subst_bounds (frees, strip gi)));
   985   in case test_term (Toplevel.theory_of st) size iterations gi' of
   986       NONE => writeln "No counterexamples found."
   987     | SOME cex => writeln ("Counterexample found:\n" ^
   988         Pretty.string_of (Pretty.chunks (map (fn (s, t) =>
   989           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1,
   990             Sign.pretty_term thy t]) cex)))
   991   end;
   992 
   993 
   994 (**** Evaluator for terms ****)
   995 
   996 val eval_result = ref (Bound 0);
   997 
   998 fun eval_term thy = PrintMode.with_default (fn t =>
   999   let
  1000     val _ = (null (term_tvars t) andalso null (term_tfrees t)) orelse
  1001       error "Term to be evaluated contains type variables";
  1002     val _ = (null (term_vars t) andalso null (term_frees t)) orelse
  1003       error "Term to be evaluated contains variables";
  1004     val (code, gr) = setmp mode ["term_of"]
  1005       (generate_code_i thy [] "Generated") [("result", t)];
  1006     val s = "structure EvalTerm =\nstruct\n\n" ^
  1007       space_implode "\n" (map snd code) ^
  1008       "\nopen Generated;\n\n" ^ Pretty.string_of
  1009         (Pretty.block [Pretty.str "val () = Codegen.eval_result :=",
  1010           Pretty.brk 1,
  1011           mk_app false (mk_term_of gr "Generated" false (fastype_of t))
  1012             [Pretty.str "result"],
  1013           Pretty.str ";"])  ^
  1014       "\n\nend;\n";
  1015     val _ = use_text "" Output.ml_output false s
  1016   in !eval_result end);
  1017 
  1018 fun print_evaluated_term s = Toplevel.keep (fn state =>
  1019   let
  1020     val ctxt = Toplevel.context_of state;
  1021     val thy = ProofContext.theory_of ctxt;
  1022     val t = eval_term thy (ProofContext.read_term ctxt s);
  1023     val T = Term.type_of t;
  1024   in
  1025     writeln (Pretty.string_of
  1026       (Pretty.block [Pretty.quote (ProofContext.pretty_term ctxt t), Pretty.fbrk,
  1027         Pretty.str "::", Pretty.brk 1, Pretty.quote (ProofContext.pretty_typ ctxt T)]))
  1028   end);
  1029 
  1030 exception Evaluation of term;
  1031 
  1032 fun evaluation_oracle (thy, Evaluation t) =
  1033   Logic.mk_equals (t, eval_term thy t);
  1034 
  1035 fun evaluation_conv ct =
  1036   let val {thy, t, ...} = rep_cterm ct
  1037   in Thm.invoke_oracle_i thy "Pure.evaluation" (thy, Evaluation t) end;
  1038 
  1039 val _ = Context.add_setup
  1040   (Theory.add_oracle ("evaluation", evaluation_oracle));
  1041 
  1042 (**** Interface ****)
  1043 
  1044 val str = PrintMode.with_default Pretty.str;
  1045 
  1046 fun parse_mixfix rd s =
  1047   (case Scan.finite Symbol.stopper (Scan.repeat
  1048      (   $$ "_" >> K Arg
  1049       || $$ "?" >> K Ignore
  1050       || $$ "\\<module>" >> K Module
  1051       || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
  1052       || $$ "{" |-- $$ "*" |-- Scan.repeat1
  1053            (   $$ "'" |-- Scan.one Symbol.is_regular
  1054             || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.is_regular)) --|
  1055          $$ "*" --| $$ "}" >> (Quote o rd o implode)
  1056       || Scan.repeat1
  1057            (   $$ "'" |-- Scan.one Symbol.is_regular
  1058             || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
  1059                  (Scan.one Symbol.is_regular)) >> (Pretty o str o implode)))
  1060        (Symbol.explode s) of
  1061      (p, []) => p
  1062    | _ => error ("Malformed annotation: " ^ quote s));
  1063 
  1064 val _ = Context.add_setup
  1065   (fold assoc_type [("fun", (parse_mixfix (K dummyT) "(_ ->/ _)",
  1066      [("term_of",
  1067        "fun term_of_fun_type _ T _ U _ = Free (\"<function>\", T --> U);\n"),
  1068       ("test",
  1069        "fun gen_fun_type _ G i =\n\
  1070        \  let\n\
  1071        \    val f = ref (fn x => raise Match);\n\
  1072        \    val _ = (f := (fn x =>\n\
  1073        \      let\n\
  1074        \        val y = G i;\n\
  1075        \        val f' = !f\n\
  1076        \      in (f := (fn x' => if x = x' then y else f' x'); y) end))\n\
  1077        \  in (fn x => !f x) end;\n")]))]);
  1078 
  1079 
  1080 structure P = OuterParse and K = OuterKeyword;
  1081 
  1082 fun strip_whitespace s = implode (fst (take_suffix (equal "\n" orf equal " ")
  1083   (snd (take_prefix (equal "\n" orf equal " ") (explode s))))) ^ "\n";
  1084 
  1085 val parse_attach = Scan.repeat (P.$$$ "attach" |--
  1086   Scan.optional (P.$$$ "(" |-- P.xname --| P.$$$ ")") "" --
  1087     (P.verbatim >> strip_whitespace));
  1088 
  1089 val assoc_typeP =
  1090   OuterSyntax.command "types_code"
  1091   "associate types with target language types" K.thy_decl
  1092     (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
  1093      (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
  1094        (fn ((name, mfx), aux) => (name, (parse_mixfix
  1095          (Sign.read_typ thy) mfx, aux)))) xs thy)));
  1096 
  1097 val assoc_constP =
  1098   OuterSyntax.command "consts_code"
  1099   "associate constants with target language code" K.thy_decl
  1100     (Scan.repeat1
  1101        (P.term --|
  1102         P.$$$ "(" -- P.string --| P.$$$ ")" -- parse_attach) >>
  1103      (fn xs => Toplevel.theory (fn thy => fold (assoc_const o 
  1104        (fn ((const, mfx), aux) =>
  1105          (const, (parse_mixfix (Sign.read_term thy) mfx, aux)))) xs thy)));
  1106 
  1107 fun parse_code lib =
  1108   Scan.optional (P.$$$ "(" |-- P.enum "," P.xname --| P.$$$ ")") (!mode) --
  1109   (if lib then Scan.optional P.name "" else P.name) --
  1110   Scan.option (P.$$$ "file" |-- P.name) --
  1111   (if lib then Scan.succeed []
  1112    else Scan.optional (P.$$$ "imports" |-- Scan.repeat1 P.name) []) --|
  1113   P.$$$ "contains" --
  1114   (   Scan.repeat1 (P.name --| P.$$$ "=" -- P.term)
  1115    || Scan.repeat1 (P.term >> pair "")) >>
  1116   (fn ((((mode', module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
  1117      let
  1118        val mode'' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode');
  1119        val (code, gr) = setmp mode mode'' (generate_code thy modules module) xs
  1120      in ((case opt_fname of
  1121          NONE => use_text "" Output.ml_output false
  1122            (space_implode "\n" (map snd code))
  1123        | SOME fname =>
  1124            if lib then
  1125              app (fn (name, s) => File.write
  1126                  (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
  1127                (("ROOT", implode (map (fn (name, _) =>
  1128                    "use \"" ^ name ^ ".ML\";\n") code)) :: code)
  1129            else File.write (Path.explode fname) (snd (hd code)));
  1130            if lib then thy
  1131            else map_modules (Symtab.update (module, gr)) thy)
  1132      end));
  1133 
  1134 val code_libraryP =
  1135   OuterSyntax.command "code_library"
  1136     "generates code for terms (one structure for each theory)" K.thy_decl
  1137     (parse_code true);
  1138 
  1139 val code_moduleP =
  1140   OuterSyntax.command "code_module"
  1141     "generates code for terms (single structure, incremental)" K.thy_decl
  1142     (parse_code false);
  1143 
  1144 val params =
  1145   [("size", P.nat >> (K o set_size)),
  1146    ("iterations", P.nat >> (K o set_iterations)),
  1147    ("default_type", P.typ >> set_default_type)];
  1148 
  1149 val parse_test_params = P.short_ident :|-- (fn s =>
  1150   P.$$$ "=" |-- (AList.lookup (op =) params s |> the_default Scan.fail));
  1151 
  1152 fun parse_tyinst xs =
  1153   (P.type_ident --| P.$$$ "=" -- P.typ >> (fn (v, s) => fn thy =>
  1154     fn (x, ys) => (x, (v, Sign.read_typ thy s) :: ys))) xs;
  1155 
  1156 fun app [] x = x
  1157   | app (f :: fs) x = app fs (f x);
  1158 
  1159 val test_paramsP =
  1160   OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl
  1161     (P.$$$ "[" |-- P.list1 parse_test_params --| P.$$$ "]" >>
  1162       (fn fs => Toplevel.theory (fn thy =>
  1163          map_test_params (app (map (fn f => f thy) fs)) thy)));
  1164 
  1165 val testP =
  1166   OuterSyntax.command "quickcheck" "try to find counterexample for subgoal" K.diag
  1167   (Scan.option (P.$$$ "[" |-- P.list1
  1168     (   parse_test_params >> (fn f => fn thy => apfst (f thy))
  1169      || parse_tyinst) --| P.$$$ "]") -- Scan.optional P.nat 1 >>
  1170     (fn (ps, g) => Toplevel.keep (fn st =>
  1171       test_goal (app (the_default [] (Option.map (map (fn f => f (Toplevel.theory_of st))) ps))
  1172         (get_test_params (Toplevel.theory_of st), [])) g st)));
  1173 
  1174 val valueP =
  1175   OuterSyntax.improper_command "value" "read, evaluate and print term" K.diag
  1176     (P.term >> (Toplevel.no_timing oo print_evaluated_term));
  1177 
  1178 val _ = OuterSyntax.add_keywords ["attach", "file", "contains"];
  1179 
  1180 val _ = OuterSyntax.add_parsers
  1181   [assoc_typeP, assoc_constP, code_libraryP, code_moduleP, test_paramsP, testP, valueP];
  1182 
  1183 end;