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