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