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