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