src/Pure/codegen.ML
author wenzelm
Thu Apr 07 09:26:29 2005 +0200 (2005-04-07)
changeset 15664 7c150afba112
parent 15574 b1d1b5bfc464
child 15801 d2f5ca3c048d
permissions -rw-r--r--
added some, peek, trace'; tuned;
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@11520
    18
    | Pretty of Pretty.T
berghofe@12452
    19
    | Quote of 'a;
berghofe@11520
    20
berghofe@12452
    21
  type 'a codegen
berghofe@12452
    22
berghofe@12452
    23
  val add_codegen: string -> term codegen -> theory -> theory
berghofe@12452
    24
  val add_tycodegen: string -> typ codegen -> theory -> theory
berghofe@14197
    25
  val add_attribute: string -> (Args.T list -> theory attribute * Args.T list) -> theory -> theory
berghofe@15261
    26
  val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory
berghofe@15261
    27
  val preprocess: theory -> thm list -> thm list
berghofe@11520
    28
  val print_codegens: theory -> unit
berghofe@11520
    29
  val generate_code: theory -> (string * string) list -> string
berghofe@11520
    30
  val generate_code_i: theory -> (string * term) list -> string
berghofe@12452
    31
  val assoc_consts: (xstring * string option * term mixfix list) list -> theory -> theory
berghofe@12452
    32
  val assoc_consts_i: (xstring * typ option * term mixfix list) list -> theory -> theory
berghofe@12452
    33
  val assoc_types: (xstring * typ mixfix list) list -> theory -> theory
berghofe@12452
    34
  val get_assoc_code: theory -> string -> typ -> term mixfix list option
berghofe@12452
    35
  val get_assoc_type: theory -> string -> typ mixfix list option
berghofe@12452
    36
  val invoke_codegen: theory -> string -> bool ->
berghofe@12452
    37
    (exn option * string) Graph.T * term -> (exn option * string) Graph.T * Pretty.T
berghofe@12452
    38
  val invoke_tycodegen: theory -> string -> bool ->
berghofe@12452
    39
    (exn option * string) Graph.T * typ -> (exn option * string) Graph.T * Pretty.T
berghofe@14858
    40
  val mk_id: string -> string
berghofe@11520
    41
  val mk_const_id: Sign.sg -> string -> string
berghofe@11520
    42
  val mk_type_id: Sign.sg -> string -> string
berghofe@11520
    43
  val rename_term: term -> term
berghofe@15398
    44
  val new_names: term -> string list -> string list
berghofe@15398
    45
  val new_name: term -> string -> string
berghofe@11520
    46
  val get_defn: theory -> string -> typ -> ((term list * term) * int option) option
berghofe@11520
    47
  val is_instance: theory -> typ -> typ -> bool
berghofe@11520
    48
  val parens: Pretty.T -> Pretty.T
berghofe@11520
    49
  val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
berghofe@11520
    50
  val eta_expand: term -> term list -> int -> term
berghofe@14105
    51
  val strip_tname: string -> string
berghofe@13753
    52
  val mk_type: bool -> typ -> Pretty.T
berghofe@13753
    53
  val mk_term_of: Sign.sg -> bool -> typ -> Pretty.T
berghofe@14105
    54
  val mk_gen: Sign.sg -> bool -> string list -> string -> typ -> Pretty.T
berghofe@14105
    55
  val test_fn: (int -> (string * term) list option) ref
berghofe@14105
    56
  val test_term: theory -> int -> int -> term -> (string * term) list option
berghofe@12452
    57
  val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
berghofe@11520
    58
  val parsers: OuterSyntax.parser list
berghofe@11520
    59
  val setup: (theory -> theory) list
berghofe@11520
    60
end;
berghofe@11520
    61
berghofe@11520
    62
structure Codegen : CODEGEN =
berghofe@11520
    63
struct
berghofe@11520
    64
berghofe@11520
    65
val quiet_mode = ref true;
berghofe@11520
    66
fun message s = if !quiet_mode then () else writeln s;
berghofe@11520
    67
berghofe@13753
    68
val mode = ref ([] : string list);
berghofe@13753
    69
berghofe@13886
    70
val margin = ref 80;
berghofe@13886
    71
berghofe@11520
    72
(**** Mixfix syntax ****)
berghofe@11520
    73
berghofe@12452
    74
datatype 'a mixfix =
berghofe@11520
    75
    Arg
berghofe@11520
    76
  | Ignore
berghofe@11520
    77
  | Pretty of Pretty.T
berghofe@12452
    78
  | Quote of 'a;
berghofe@11520
    79
berghofe@11520
    80
fun is_arg Arg = true
berghofe@11520
    81
  | is_arg Ignore = true
berghofe@11520
    82
  | is_arg _ = false;
berghofe@11520
    83
berghofe@12452
    84
fun quotes_of [] = []
berghofe@12452
    85
  | quotes_of (Quote q :: ms) = q :: quotes_of ms
berghofe@12452
    86
  | quotes_of (_ :: ms) = quotes_of ms;
berghofe@12452
    87
berghofe@12452
    88
fun args_of [] xs = ([], xs)
berghofe@12452
    89
  | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
berghofe@12452
    90
  | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
berghofe@12452
    91
  | args_of (_ :: ms) xs = args_of ms xs;
berghofe@11520
    92
skalberg@15570
    93
fun num_args x = length (List.filter is_arg x);
berghofe@11520
    94
berghofe@11520
    95
berghofe@11520
    96
(**** theory data ****)
berghofe@11520
    97
berghofe@14105
    98
(* type of code generators *)
berghofe@11520
    99
berghofe@12452
   100
type 'a codegen = theory -> (exn option * string) Graph.T ->
berghofe@12452
   101
  string -> bool -> 'a -> ((exn option * string) Graph.T * Pretty.T) option;
berghofe@12452
   102
berghofe@14105
   103
(* parameters for random testing *)
berghofe@14105
   104
berghofe@14105
   105
type test_params =
berghofe@14105
   106
  {size: int, iterations: int, default_type: typ option};
berghofe@14105
   107
berghofe@14105
   108
fun merge_test_params
berghofe@14105
   109
  {size = size1, iterations = iterations1, default_type = default_type1}
berghofe@14105
   110
  {size = size2, iterations = iterations2, default_type = default_type2} =
berghofe@14105
   111
  {size = Int.max (size1, size2),
berghofe@14105
   112
   iterations = Int.max (iterations1, iterations2),
berghofe@14105
   113
   default_type = case default_type1 of
skalberg@15531
   114
       NONE => default_type2
berghofe@14105
   115
     | _ => default_type1};
berghofe@14105
   116
berghofe@14105
   117
val default_test_params : test_params =
skalberg@15531
   118
  {size = 10, iterations = 100, default_type = NONE};
berghofe@14105
   119
berghofe@14105
   120
fun set_size size ({iterations, default_type, ...} : test_params) =
berghofe@14105
   121
  {size = size, iterations = iterations, default_type = default_type};
berghofe@14105
   122
berghofe@14105
   123
fun set_iterations iterations ({size, default_type, ...} : test_params) =
berghofe@14105
   124
  {size = size, iterations = iterations, default_type = default_type};
berghofe@14105
   125
berghofe@14105
   126
fun set_default_type s sg ({size, iterations, ...} : test_params) =
berghofe@14105
   127
  {size = size, iterations = iterations,
skalberg@15531
   128
   default_type = SOME (typ_of (read_ctyp sg s))};
berghofe@14105
   129
berghofe@14105
   130
(* data kind 'Pure/codegen' *)
berghofe@14105
   131
 
berghofe@11520
   132
structure CodegenArgs =
berghofe@11520
   133
struct
berghofe@11520
   134
  val name = "Pure/codegen";
berghofe@11520
   135
  type T =
berghofe@12452
   136
    {codegens : (string * term codegen) list,
berghofe@12452
   137
     tycodegens : (string * typ codegen) list,
berghofe@12452
   138
     consts : ((string * typ) * term mixfix list) list,
berghofe@12555
   139
     types : (string * typ mixfix list) list,
berghofe@14197
   140
     attrs: (string * (Args.T list -> theory attribute * Args.T list)) list,
berghofe@15261
   141
     preprocs: (stamp * (theory -> thm list -> thm list)) list,
berghofe@14105
   142
     test_params: test_params};
berghofe@11520
   143
berghofe@12555
   144
  val empty =
berghofe@14105
   145
    {codegens = [], tycodegens = [], consts = [], types = [], attrs = [],
berghofe@15261
   146
     preprocs = [], test_params = default_test_params};
berghofe@11520
   147
  val copy = I;
berghofe@11520
   148
  val prep_ext = I;
berghofe@11520
   149
berghofe@12555
   150
  fun merge
berghofe@12555
   151
    ({codegens = codegens1, tycodegens = tycodegens1,
berghofe@14105
   152
      consts = consts1, types = types1, attrs = attrs1,
berghofe@15261
   153
      preprocs = preprocs1, test_params = test_params1},
berghofe@12555
   154
     {codegens = codegens2, tycodegens = tycodegens2,
berghofe@14105
   155
      consts = consts2, types = types2, attrs = attrs2,
berghofe@15261
   156
      preprocs = preprocs2, test_params = test_params2}) =
berghofe@15261
   157
    {codegens = merge_alists' codegens1 codegens2,
berghofe@15261
   158
     tycodegens = merge_alists' tycodegens1 tycodegens2,
berghofe@12555
   159
     consts = merge_alists consts1 consts2,
berghofe@12555
   160
     types = merge_alists types1 types2,
berghofe@14105
   161
     attrs = merge_alists attrs1 attrs2,
berghofe@15261
   162
     preprocs = merge_alists' preprocs1 preprocs2,
berghofe@14105
   163
     test_params = merge_test_params test_params1 test_params2};
berghofe@11520
   164
berghofe@12452
   165
  fun print sg ({codegens, tycodegens, ...} : T) =
berghofe@12452
   166
    Pretty.writeln (Pretty.chunks
berghofe@12452
   167
      [Pretty.strs ("term code generators:" :: map fst codegens),
berghofe@12452
   168
       Pretty.strs ("type code generators:" :: map fst tycodegens)]);
berghofe@11520
   169
end;
berghofe@11520
   170
berghofe@11520
   171
structure CodegenData = TheoryDataFun(CodegenArgs);
berghofe@11520
   172
val print_codegens = CodegenData.print;
berghofe@11520
   173
berghofe@11520
   174
berghofe@14105
   175
(**** access parameters for random testing ****)
berghofe@14105
   176
berghofe@14105
   177
fun get_test_params thy = #test_params (CodegenData.get thy);
berghofe@14105
   178
berghofe@14105
   179
fun map_test_params f thy =
berghofe@15261
   180
  let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@14105
   181
    CodegenData.get thy;
berghofe@14105
   182
  in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
berghofe@15261
   183
    consts = consts, types = types, attrs = attrs, preprocs = preprocs,
berghofe@14105
   184
    test_params = f test_params} thy
berghofe@14105
   185
  end;
berghofe@14105
   186
berghofe@14105
   187
berghofe@12452
   188
(**** add new code generators to theory ****)
berghofe@11520
   189
berghofe@11520
   190
fun add_codegen name f thy =
berghofe@15261
   191
  let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@14105
   192
    CodegenData.get thy
berghofe@11520
   193
  in (case assoc (codegens, name) of
skalberg@15531
   194
      NONE => CodegenData.put {codegens = (name, f) :: codegens,
berghofe@12555
   195
        tycodegens = tycodegens, consts = consts, types = types,
berghofe@15261
   196
        attrs = attrs, preprocs = preprocs, test_params = test_params} thy
skalberg@15531
   197
    | SOME _ => error ("Code generator " ^ name ^ " already declared"))
berghofe@12452
   198
  end;
berghofe@12452
   199
berghofe@12452
   200
fun add_tycodegen name f thy =
berghofe@15261
   201
  let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@14105
   202
    CodegenData.get thy
berghofe@12452
   203
  in (case assoc (tycodegens, name) of
skalberg@15531
   204
      NONE => CodegenData.put {tycodegens = (name, f) :: tycodegens,
berghofe@12555
   205
        codegens = codegens, consts = consts, types = types,
berghofe@15261
   206
        attrs = attrs, preprocs = preprocs, test_params = test_params} thy
skalberg@15531
   207
    | SOME _ => error ("Code generator " ^ name ^ " already declared"))
berghofe@11520
   208
  end;
berghofe@11520
   209
berghofe@11520
   210
berghofe@12555
   211
(**** code attribute ****)
berghofe@12555
   212
berghofe@12555
   213
fun add_attribute name att thy =
berghofe@15261
   214
  let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@14105
   215
    CodegenData.get thy
berghofe@12555
   216
  in (case assoc (attrs, name) of
skalberg@15531
   217
      NONE => CodegenData.put {tycodegens = tycodegens,
berghofe@12555
   218
        codegens = codegens, consts = consts, types = types,
berghofe@15261
   219
        attrs = if name = "" then attrs @ [(name, att)] else (name, att) :: attrs,
berghofe@15261
   220
        preprocs = preprocs,
berghofe@15261
   221
        test_params = test_params} thy
skalberg@15531
   222
    | SOME _ => error ("Code attribute " ^ name ^ " already declared"))
berghofe@12555
   223
  end;
berghofe@12555
   224
berghofe@14197
   225
fun mk_parser (a, p) = (if a = "" then Scan.succeed "" else Args.$$$ a) |-- p;
berghofe@14197
   226
berghofe@12555
   227
val code_attr =
wenzelm@15664
   228
  Attrib.syntax (Scan.peek (fn thy => foldr op || Scan.fail (map mk_parser
wenzelm@15664
   229
    (#attrs (CodegenData.get thy)))));
berghofe@12555
   230
berghofe@12555
   231
berghofe@15261
   232
(**** preprocessors ****)
berghofe@15261
   233
berghofe@15261
   234
fun add_preprocessor p thy =
berghofe@15261
   235
  let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@15261
   236
    CodegenData.get thy
berghofe@15261
   237
  in CodegenData.put {tycodegens = tycodegens,
berghofe@15261
   238
    codegens = codegens, consts = consts, types = types,
berghofe@15261
   239
    attrs = attrs, preprocs = (stamp (), p) :: preprocs,
berghofe@15261
   240
    test_params = test_params} thy
berghofe@15261
   241
  end;
berghofe@15261
   242
berghofe@15261
   243
fun preprocess thy ths =
berghofe@15261
   244
  let val {preprocs, ...} = CodegenData.get thy
skalberg@15570
   245
  in Library.foldl (fn (ths, (_, f)) => f thy ths) (ths, preprocs) end;
berghofe@15261
   246
berghofe@15261
   247
fun unfold_attr (thy, eqn) =
berghofe@15261
   248
  let
berghofe@15261
   249
    val (name, _) = dest_Const (head_of
berghofe@15261
   250
      (fst (Logic.dest_equals (prop_of eqn))));
berghofe@15261
   251
    fun prep thy = map (fn th =>
berghofe@15261
   252
      if name mem term_consts (prop_of th) then
berghofe@15398
   253
        rewrite_rule [eqn] (Thm.transfer thy th)
berghofe@15261
   254
      else th)
berghofe@15261
   255
  in (add_preprocessor prep thy, eqn) end;
berghofe@15261
   256
berghofe@15261
   257
berghofe@11520
   258
(**** associate constants with target language code ****)
berghofe@11520
   259
skalberg@15570
   260
fun gen_assoc_consts prep_type xs thy = Library.foldl (fn (thy, (s, tyopt, syn)) =>
berghofe@11520
   261
  let
berghofe@11520
   262
    val sg = sign_of thy;
berghofe@15261
   263
    val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@14105
   264
      CodegenData.get thy;
berghofe@11520
   265
    val cname = Sign.intern_const sg s;
berghofe@11520
   266
  in
berghofe@11520
   267
    (case Sign.const_type sg cname of
skalberg@15531
   268
       SOME T =>
berghofe@11520
   269
         let val T' = (case tyopt of
skalberg@15531
   270
                NONE => T
skalberg@15531
   271
              | SOME ty =>
berghofe@11520
   272
                  let val U = prep_type sg ty
wenzelm@14769
   273
                  in if Sign.typ_instance sg (U, T) then U
berghofe@11520
   274
                    else error ("Illegal type constraint for constant " ^ cname)
berghofe@11520
   275
                  end)
berghofe@11520
   276
         in (case assoc (consts, (cname, T')) of
skalberg@15531
   277
             NONE => CodegenData.put {codegens = codegens,
berghofe@12452
   278
               tycodegens = tycodegens,
berghofe@12555
   279
               consts = ((cname, T'), syn) :: consts,
berghofe@15261
   280
               types = types, attrs = attrs, preprocs = preprocs,
berghofe@15261
   281
               test_params = test_params} thy
skalberg@15531
   282
           | SOME _ => error ("Constant " ^ cname ^ " already associated with code"))
berghofe@11520
   283
         end
berghofe@11520
   284
     | _ => error ("Not a constant: " ^ s))
berghofe@11520
   285
  end) (thy, xs);
berghofe@11520
   286
berghofe@11520
   287
val assoc_consts_i = gen_assoc_consts (K I);
berghofe@11520
   288
val assoc_consts = gen_assoc_consts (fn sg => typ_of o read_ctyp sg);
berghofe@11520
   289
berghofe@11520
   290
(**** associate types with target language types ****)
berghofe@11520
   291
skalberg@15570
   292
fun assoc_types xs thy = Library.foldl (fn (thy, (s, syn)) =>
berghofe@11520
   293
  let
berghofe@15261
   294
    val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} =
berghofe@14105
   295
      CodegenData.get thy;
berghofe@11520
   296
    val tc = Sign.intern_tycon (sign_of thy) s
berghofe@11520
   297
  in
berghofe@11520
   298
    (case assoc (types, tc) of
skalberg@15531
   299
       NONE => CodegenData.put {codegens = codegens,
berghofe@12452
   300
         tycodegens = tycodegens, consts = consts,
berghofe@14105
   301
         types = (tc, syn) :: types, attrs = attrs,
berghofe@15261
   302
         preprocs = preprocs, test_params = test_params} thy
skalberg@15531
   303
     | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
berghofe@11520
   304
  end) (thy, xs);
berghofe@11520
   305
berghofe@12452
   306
fun get_assoc_type thy s = assoc (#types (CodegenData.get thy), s);
wenzelm@11546
   307
berghofe@11520
   308
berghofe@11520
   309
(**** make valid ML identifiers ****)
berghofe@11520
   310
berghofe@14858
   311
fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
berghofe@14858
   312
  Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
berghofe@14858
   313
berghofe@14858
   314
fun dest_sym s = (case split_last (snd (take_prefix (equal "\\") (explode s))) of
berghofe@14858
   315
    ("<" :: "^" :: xs, ">") => (true, implode xs)
berghofe@14858
   316
  | ("<" :: xs, ">") => (false, implode xs)
berghofe@14858
   317
  | _ => sys_error "dest_sym");
berghofe@14858
   318
  
berghofe@14858
   319
fun mk_id s = if s = "" then "" else
berghofe@11520
   320
  let
berghofe@14858
   321
    fun check_str [] = []
berghofe@14858
   322
      | check_str xs = (case take_prefix is_ascii_letdig xs of
berghofe@14858
   323
          ([], " " :: zs) => check_str zs
berghofe@14858
   324
        | ([], z :: zs) =>
berghofe@14858
   325
          if size z = 1 then string_of_int (ord z) :: check_str zs
berghofe@14858
   326
          else (case dest_sym z of
berghofe@14858
   327
              (true, "isub") => check_str zs
berghofe@14858
   328
            | (true, "isup") => "" :: check_str zs
berghofe@14858
   329
            | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
berghofe@14858
   330
        | (ys, zs) => implode ys :: check_str zs);
berghofe@14858
   331
    val s' = space_implode "_"
skalberg@15570
   332
      (List.concat (map (check_str o Symbol.explode) (NameSpace.unpack s)))
berghofe@11520
   333
  in
berghofe@14858
   334
    if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
berghofe@11520
   335
  end;
berghofe@11520
   336
berghofe@14858
   337
fun mk_const_id sg s =
berghofe@14858
   338
  let val s' = mk_id (Sign.cond_extern sg Sign.constK s)
berghofe@14858
   339
  in if s' mem ThmDatabase.ml_reserved then s' ^ "_const" else s' end;
berghofe@13073
   340
berghofe@14858
   341
fun mk_type_id sg s =
berghofe@14858
   342
  let val s' = mk_id (Sign.cond_extern sg Sign.typeK s)
berghofe@14858
   343
  in if s' mem ThmDatabase.ml_reserved then s' ^ "_type" else s' end;
berghofe@11520
   344
berghofe@13731
   345
fun rename_terms ts =
berghofe@11520
   346
  let
skalberg@15574
   347
    val names = foldr add_term_names
skalberg@15574
   348
      (map (fst o fst) (Drule.vars_of_terms ts)) ts;
berghofe@14858
   349
    val reserved = names inter ThmDatabase.ml_reserved;
skalberg@15570
   350
    val (illegal, alt_names) = split_list (List.mapPartial (fn s =>
skalberg@15531
   351
      let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
berghofe@14858
   352
    val ps = (reserved @ illegal) ~~
berghofe@14858
   353
      variantlist (map (suffix "'") reserved @ alt_names, names);
berghofe@11520
   354
skalberg@15570
   355
    fun rename_id s = getOpt (assoc (ps, s), s);
berghofe@14858
   356
berghofe@14858
   357
    fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
berghofe@14858
   358
      | rename (Free (a, T)) = Free (rename_id a, T)
berghofe@11520
   359
      | rename (Abs (s, T, t)) = Abs (s, T, rename t)
berghofe@11520
   360
      | rename (t $ u) = rename t $ rename u
berghofe@11520
   361
      | rename t = t;
berghofe@11520
   362
  in
berghofe@13731
   363
    map rename ts
berghofe@13731
   364
  end;
berghofe@13731
   365
berghofe@13731
   366
val rename_term = hd o rename_terms o single;
berghofe@13731
   367
berghofe@13731
   368
berghofe@13731
   369
(**** retrieve definition of constant ****)
berghofe@13731
   370
berghofe@13731
   371
fun is_instance thy T1 T2 =
wenzelm@14769
   372
  Sign.typ_instance (sign_of thy) (T1, Type.varifyT T2);
berghofe@13731
   373
skalberg@15570
   374
fun get_assoc_code thy s T = Option.map snd (find_first (fn ((s', T'), _) =>
berghofe@13731
   375
  s = s' andalso is_instance thy T T') (#consts (CodegenData.get thy)));
berghofe@13731
   376
berghofe@13731
   377
fun get_defn thy s T =
berghofe@13731
   378
  let
skalberg@15570
   379
    val axms = List.concat (map (Symtab.dest o #axioms o Theory.rep_theory)
berghofe@13731
   380
      (thy :: Theory.ancestors_of thy));
berghofe@15261
   381
    fun prep_def def = (case preprocess thy [def] of
berghofe@15261
   382
      [def'] => prop_of def' | _ => error "get_defn: bad preprocessor");
berghofe@15261
   383
    fun dest t =
berghofe@15261
   384
      let
berghofe@15261
   385
        val (lhs, rhs) = Logic.dest_equals t;
berghofe@15261
   386
        val (c, args) = strip_comb lhs;
berghofe@15261
   387
        val (s', T') = dest_Const c
skalberg@15531
   388
      in if s = s' then SOME (T', (args, rhs)) else NONE
skalberg@15531
   389
      end handle TERM _ => NONE;
skalberg@15570
   390
    val defs = List.mapPartial (fn (name, t) => Option.map (pair name) (dest t)) axms;
berghofe@15261
   391
    val i = find_index (is_instance thy T o fst o snd) defs
berghofe@13731
   392
  in
berghofe@15261
   393
    if i >= 0 then
skalberg@15570
   394
      let val (name, (T', (args, _))) = List.nth (defs, i)
berghofe@15261
   395
      in case dest (prep_def (Thm.get_axiom thy name)) of
skalberg@15531
   396
          NONE => NONE
skalberg@15531
   397
        | SOME (T'', p as (args', rhs)) =>
berghofe@15261
   398
            if T' = T'' andalso args = args' then
skalberg@15531
   399
              SOME (split_last (rename_terms (args @ [rhs])),
skalberg@15531
   400
                if length defs = 1 then NONE else SOME i)
skalberg@15531
   401
            else NONE
berghofe@15261
   402
      end
skalberg@15531
   403
    else NONE
berghofe@11520
   404
  end;
berghofe@11520
   405
berghofe@11520
   406
berghofe@12452
   407
(**** invoke suitable code generator for term / type ****)
berghofe@11520
   408
berghofe@12452
   409
fun invoke_codegen thy dep brack (gr, t) = (case get_first
berghofe@11520
   410
   (fn (_, f) => f thy gr dep brack t) (#codegens (CodegenData.get thy)) of
skalberg@15531
   411
      NONE => error ("Unable to generate code for term:\n" ^
berghofe@11520
   412
        Sign.string_of_term (sign_of thy) t ^ "\nrequired by:\n" ^
berghofe@11520
   413
        commas (Graph.all_succs gr [dep]))
skalberg@15531
   414
    | SOME x => x);
berghofe@12452
   415
berghofe@12452
   416
fun invoke_tycodegen thy dep brack (gr, T) = (case get_first
berghofe@12452
   417
   (fn (_, f) => f thy gr dep brack T) (#tycodegens (CodegenData.get thy)) of
skalberg@15531
   418
      NONE => error ("Unable to generate code for type:\n" ^
berghofe@12452
   419
        Sign.string_of_typ (sign_of thy) T ^ "\nrequired by:\n" ^
berghofe@12452
   420
        commas (Graph.all_succs gr [dep]))
skalberg@15531
   421
    | SOME x => x);
berghofe@11520
   422
berghofe@11520
   423
berghofe@11520
   424
(**** code generator for mixfix expressions ****)
berghofe@11520
   425
berghofe@11520
   426
fun parens p = Pretty.block [Pretty.str "(", p, Pretty.str ")"];
berghofe@11520
   427
berghofe@11520
   428
fun pretty_fn [] p = [p]
berghofe@11520
   429
  | pretty_fn (x::xs) p = Pretty.str ("fn " ^ x ^ " =>") ::
berghofe@11520
   430
      Pretty.brk 1 :: pretty_fn xs p;
berghofe@11520
   431
berghofe@11520
   432
fun pretty_mixfix [] [] _ = []
berghofe@11520
   433
  | pretty_mixfix (Arg :: ms) (p :: ps) qs = p :: pretty_mixfix ms ps qs
berghofe@12452
   434
  | pretty_mixfix (Ignore :: ms) ps qs = pretty_mixfix ms ps qs
berghofe@11520
   435
  | pretty_mixfix (Pretty p :: ms) ps qs = p :: pretty_mixfix ms ps qs
berghofe@12452
   436
  | pretty_mixfix (Quote _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs;
berghofe@11520
   437
berghofe@11520
   438
berghofe@12452
   439
(**** default code generators ****)
berghofe@11520
   440
berghofe@11520
   441
fun eta_expand t ts i =
berghofe@11520
   442
  let
berghofe@11520
   443
    val (Ts, _) = strip_type (fastype_of t);
berghofe@11520
   444
    val j = i - length ts
berghofe@11520
   445
  in
skalberg@15574
   446
    foldr (fn (T, t) => Abs ("x", T, t))
skalberg@15574
   447
      (list_comb (t, ts @ map Bound (j-1 downto 0))) (Library.take (j, Ts))
berghofe@11520
   448
  end;
berghofe@11520
   449
berghofe@11520
   450
fun mk_app _ p [] = p
berghofe@11520
   451
  | mk_app brack p ps = if brack then
berghofe@11520
   452
       Pretty.block (Pretty.str "(" ::
berghofe@11520
   453
         separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"])
berghofe@11520
   454
     else Pretty.block (separate (Pretty.brk 1) (p :: ps));
berghofe@11520
   455
berghofe@14858
   456
fun new_names t xs = variantlist (map mk_id xs,
berghofe@11520
   457
  map (fst o fst o dest_Var) (term_vars t) union
berghofe@11520
   458
  add_term_names (t, ThmDatabase.ml_reserved));
berghofe@11520
   459
berghofe@11520
   460
fun new_name t x = hd (new_names t [x]);
berghofe@11520
   461
berghofe@11520
   462
fun default_codegen thy gr dep brack t =
berghofe@11520
   463
  let
berghofe@11520
   464
    val (u, ts) = strip_comb t;
berghofe@12452
   465
    fun codegens brack = foldl_map (invoke_codegen thy dep brack)
berghofe@11520
   466
  in (case u of
berghofe@14105
   467
      Var ((s, i), T) =>
berghofe@14105
   468
        let
berghofe@14105
   469
          val (gr', ps) = codegens true (gr, ts);
berghofe@14105
   470
          val (gr'', _) = invoke_tycodegen thy dep false (gr', T)
skalberg@15531
   471
        in SOME (gr'', mk_app brack (Pretty.str (s ^
berghofe@11520
   472
           (if i=0 then "" else string_of_int i))) ps)
berghofe@11520
   473
        end
berghofe@11520
   474
berghofe@14105
   475
    | Free (s, T) =>
berghofe@14105
   476
        let
berghofe@14105
   477
          val (gr', ps) = codegens true (gr, ts);
berghofe@14105
   478
          val (gr'', _) = invoke_tycodegen thy dep false (gr', T)
skalberg@15531
   479
        in SOME (gr'', mk_app brack (Pretty.str s) ps) end
berghofe@11520
   480
berghofe@11520
   481
    | Const (s, T) =>
berghofe@11520
   482
      (case get_assoc_code thy s T of
skalberg@15531
   483
         SOME ms =>
berghofe@11520
   484
           let val i = num_args ms
berghofe@11520
   485
           in if length ts < i then
berghofe@11520
   486
               default_codegen thy gr dep brack (eta_expand u ts i)
berghofe@11520
   487
             else
berghofe@11520
   488
               let
berghofe@12452
   489
                 val (ts1, ts2) = args_of ms ts;
berghofe@12452
   490
                 val (gr1, ps1) = codegens false (gr, ts1);
berghofe@12452
   491
                 val (gr2, ps2) = codegens true (gr1, ts2);
berghofe@12452
   492
                 val (gr3, ps3) = codegens false (gr2, quotes_of ms);
berghofe@11520
   493
               in
skalberg@15531
   494
                 SOME (gr3, mk_app brack (Pretty.block (pretty_mixfix ms ps1 ps3)) ps2)
berghofe@11520
   495
               end
berghofe@11520
   496
           end
skalberg@15531
   497
       | NONE => (case get_defn thy s T of
skalberg@15531
   498
           NONE => NONE
skalberg@15531
   499
         | SOME ((args, rhs), k) =>
berghofe@11520
   500
             let
berghofe@11520
   501
               val id = mk_const_id (sign_of thy) s ^ (case k of
skalberg@15531
   502
                 NONE => "" | SOME i => "_def" ^ string_of_int i);
berghofe@12452
   503
               val (gr', ps) = codegens true (gr, ts);
berghofe@11520
   504
             in
skalberg@15531
   505
               SOME (Graph.add_edge (id, dep) gr' handle Graph.UNDEF _ =>
berghofe@11520
   506
                 let
berghofe@11520
   507
                   val _ = message ("expanding definition of " ^ s);
berghofe@11520
   508
                   val (Ts, _) = strip_type T;
berghofe@11520
   509
                   val (args', rhs') =
berghofe@11520
   510
                     if not (null args) orelse null Ts then (args, rhs) else
berghofe@11520
   511
                       let val v = Free (new_name rhs "x", hd Ts)
berghofe@11520
   512
                       in ([v], betapply (rhs, v)) end;
berghofe@12452
   513
                   val (gr1, p) = invoke_codegen thy id false
berghofe@12452
   514
                     (Graph.add_edge (id, dep)
skalberg@15531
   515
                        (Graph.new_node (id, (NONE, "")) gr'), rhs');
berghofe@12452
   516
                   val (gr2, xs) = codegens false (gr1, args');
berghofe@12580
   517
                   val (gr3, ty) = invoke_tycodegen thy id false (gr2, T);
skalberg@15531
   518
                 in Graph.map_node id (K (NONE, Pretty.string_of (Pretty.block
berghofe@12580
   519
                   (separate (Pretty.brk 1) (if null args' then
berghofe@12580
   520
                       [Pretty.str ("val " ^ id ^ " :"), ty]
berghofe@12580
   521
                     else Pretty.str ("fun " ^ id) :: xs) @
wenzelm@14980
   522
                    [Pretty.str " =", Pretty.brk 1, p, Pretty.str ";"])) ^ "\n\n")) gr3
berghofe@11520
   523
                 end, mk_app brack (Pretty.str id) ps)
berghofe@11520
   524
             end))
berghofe@11520
   525
berghofe@11520
   526
    | Abs _ =>
berghofe@11520
   527
      let
berghofe@11520
   528
        val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
berghofe@11520
   529
        val t = strip_abs_body u
berghofe@11520
   530
        val bs' = new_names t bs;
berghofe@12452
   531
        val (gr1, ps) = codegens true (gr, ts);
berghofe@12452
   532
        val (gr2, p) = invoke_codegen thy dep false
berghofe@12452
   533
          (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
berghofe@11520
   534
      in
skalberg@15531
   535
        SOME (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
berghofe@11520
   536
          [Pretty.str ")"])) ps)
berghofe@11520
   537
      end
berghofe@11520
   538
skalberg@15531
   539
    | _ => NONE)
berghofe@11520
   540
  end;
berghofe@11520
   541
berghofe@12452
   542
fun default_tycodegen thy gr dep brack (TVar ((s, i), _)) =
skalberg@15531
   543
      SOME (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
skalberg@15531
   544
  | default_tycodegen thy gr dep brack (TFree (s, _)) = SOME (gr, Pretty.str s)
berghofe@12452
   545
  | default_tycodegen thy gr dep brack (Type (s, Ts)) =
berghofe@12452
   546
      (case assoc (#types (CodegenData.get thy), s) of
skalberg@15531
   547
         NONE => NONE
skalberg@15531
   548
       | SOME ms =>
berghofe@12452
   549
           let
berghofe@12452
   550
             val (gr', ps) = foldl_map
berghofe@12452
   551
               (invoke_tycodegen thy dep false) (gr, fst (args_of ms Ts));
berghofe@12452
   552
             val (gr'', qs) = foldl_map
berghofe@12452
   553
               (invoke_tycodegen thy dep false) (gr', quotes_of ms)
skalberg@15531
   554
           in SOME (gr'', Pretty.block (pretty_mixfix ms ps qs)) end);
berghofe@12452
   555
berghofe@11520
   556
berghofe@11520
   557
fun output_code gr xs = implode (map (snd o Graph.get_node gr)
berghofe@11520
   558
  (rev (Graph.all_preds gr xs)));
berghofe@11520
   559
berghofe@14598
   560
fun gen_generate_code prep_term thy =
berghofe@14598
   561
  setmp print_mode [] (Pretty.setmp_margin (!margin) (fn xs =>
berghofe@11520
   562
  let
berghofe@11520
   563
    val sg = sign_of thy;
skalberg@15531
   564
    val gr = Graph.new_node ("<Top>", (NONE, "")) Graph.empty;
berghofe@11520
   565
    val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
berghofe@12452
   566
      (invoke_codegen thy "<Top>" false (gr, t)))
berghofe@12452
   567
        (gr, map (apsnd (prep_term sg)) xs)
wenzelm@14818
   568
    val code =
wenzelm@14818
   569
      "structure Generated =\nstruct\n\n" ^
wenzelm@14818
   570
      output_code gr' ["<Top>"] ^
wenzelm@14818
   571
      space_implode "\n\n" (map (fn (s', p) => Pretty.string_of (Pretty.block
wenzelm@14818
   572
        [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"])) ps) ^
wenzelm@14818
   573
      "\n\nend;\n\nopen Generated;\n";
wenzelm@14980
   574
  in code end));
berghofe@11520
   575
berghofe@11520
   576
val generate_code_i = gen_generate_code (K I);
berghofe@11520
   577
val generate_code = gen_generate_code
berghofe@11520
   578
  (fn sg => term_of o read_cterm sg o rpair TypeInfer.logicT);
berghofe@11520
   579
berghofe@12452
   580
berghofe@13753
   581
(**** Reflection ****)
berghofe@13753
   582
berghofe@13753
   583
val strip_tname = implode o tl o explode;
berghofe@13753
   584
berghofe@13753
   585
fun pretty_list xs = Pretty.block (Pretty.str "[" ::
skalberg@15570
   586
  List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
berghofe@13753
   587
  [Pretty.str "]"]);
berghofe@13753
   588
berghofe@13753
   589
fun mk_type p (TVar ((s, i), _)) = Pretty.str
berghofe@13753
   590
      (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
berghofe@13753
   591
  | mk_type p (TFree (s, _)) = Pretty.str (strip_tname s ^ "T")
berghofe@13753
   592
  | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
berghofe@13753
   593
      [Pretty.str "Type", Pretty.brk 1, Pretty.str ("(\"" ^ s ^ "\","),
berghofe@13753
   594
       Pretty.brk 1, pretty_list (map (mk_type false) Ts), Pretty.str ")"]);
berghofe@13753
   595
berghofe@13753
   596
fun mk_term_of sg p (TVar ((s, i), _)) = Pretty.str
berghofe@13753
   597
      (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
berghofe@13753
   598
  | mk_term_of sg p (TFree (s, _)) = Pretty.str (strip_tname s ^ "F")
berghofe@13753
   599
  | mk_term_of sg p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
berghofe@13753
   600
      (separate (Pretty.brk 1) (Pretty.str ("term_of_" ^ mk_type_id sg s) ::
skalberg@15570
   601
        List.concat (map (fn T => [mk_term_of sg true T, mk_type true T]) Ts))));
berghofe@13753
   602
berghofe@13753
   603
berghofe@14105
   604
(**** Test data generators ****)
berghofe@14105
   605
berghofe@14105
   606
fun mk_gen sg p xs a (TVar ((s, i), _)) = Pretty.str
berghofe@14105
   607
      (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
berghofe@14105
   608
  | mk_gen sg p xs a (TFree (s, _)) = Pretty.str (strip_tname s ^ "G")
berghofe@14105
   609
  | mk_gen sg p xs a (Type (s, Ts)) = (if p then parens else I) (Pretty.block
berghofe@14105
   610
      (separate (Pretty.brk 1) (Pretty.str ("gen_" ^ mk_type_id sg s ^
berghofe@14105
   611
        (if s mem xs then "'" else "")) :: map (mk_gen sg true xs a) Ts @
berghofe@14105
   612
        (if s mem xs then [Pretty.str a] else []))));
berghofe@14105
   613
skalberg@15531
   614
val test_fn : (int -> (string * term) list option) ref = ref (fn _ => NONE);
berghofe@14105
   615
berghofe@15029
   616
fun test_term thy sz i = setmp print_mode [] (fn t =>
berghofe@14105
   617
  let
berghofe@14105
   618
    val _ = assert (null (term_tvars t) andalso null (term_tfrees t))
berghofe@14105
   619
      "Term to be tested contains type variables";
berghofe@14105
   620
    val _ = assert (null (term_vars t))
berghofe@14105
   621
      "Term to be tested contains schematic variables";
berghofe@14105
   622
    val sg = sign_of thy;
berghofe@14105
   623
    val frees = map dest_Free (term_frees t);
berghofe@14140
   624
    val szname = variant (map fst frees) "i";
berghofe@14105
   625
    val s = "structure TestTerm =\nstruct\n\n" ^
berghofe@14105
   626
      setmp mode ["term_of", "test"] (generate_code_i thy)
berghofe@14105
   627
        [("testf", list_abs_free (frees, t))] ^
wenzelm@14980
   628
      "\n" ^ Pretty.string_of
berghofe@14105
   629
        (Pretty.block [Pretty.str "val () = Codegen.test_fn :=",
berghofe@14140
   630
          Pretty.brk 1, Pretty.str ("(fn " ^ szname ^ " =>"), Pretty.brk 1,
berghofe@14105
   631
          Pretty.blk (0, [Pretty.str "let", Pretty.brk 1,
berghofe@14105
   632
            Pretty.blk (0, separate Pretty.fbrk (map (fn (s, T) =>
berghofe@14886
   633
              Pretty.block [Pretty.str ("val " ^ mk_id s ^ " ="), Pretty.brk 1,
berghofe@14105
   634
              mk_gen sg false [] "" T, Pretty.brk 1,
berghofe@14140
   635
              Pretty.str (szname ^ ";")]) frees)),
berghofe@14105
   636
            Pretty.brk 1, Pretty.str "in", Pretty.brk 1,
berghofe@14105
   637
            Pretty.block [Pretty.str "if ",
berghofe@14886
   638
              mk_app false (Pretty.str "testf") (map (Pretty.str o mk_id o fst) frees),
skalberg@15531
   639
              Pretty.brk 1, Pretty.str "then NONE",
berghofe@14105
   640
              Pretty.brk 1, Pretty.str "else ",
skalberg@15531
   641
              Pretty.block [Pretty.str "SOME ", Pretty.block (Pretty.str "[" ::
skalberg@15570
   642
                List.concat (separate [Pretty.str ",", Pretty.brk 1]
berghofe@14105
   643
                  (map (fn (s, T) => [Pretty.block
berghofe@15326
   644
                    [Pretty.str ("(" ^ Library.quote (Symbol.escape s) ^ ","), Pretty.brk 1,
berghofe@14105
   645
                     mk_app false (mk_term_of sg false T)
berghofe@14886
   646
                       [Pretty.str (mk_id s)], Pretty.str ")"]]) frees)) @
berghofe@14105
   647
                  [Pretty.str "]"])]],
wenzelm@14980
   648
            Pretty.brk 1, Pretty.str "end"]), Pretty.str ");"]) ^
berghofe@14105
   649
      "\n\nend;\n";
berghofe@14105
   650
    val _ = use_text Context.ml_output false s;
skalberg@15531
   651
    fun iter f k = if k > i then NONE
berghofe@14135
   652
      else (case (f () handle Match =>
skalberg@15531
   653
          (warning "Exception Match raised in generated code"; NONE)) of
skalberg@15531
   654
        NONE => iter f (k+1) | SOME x => SOME x);
skalberg@15531
   655
    fun test k = if k > sz then NONE
berghofe@14105
   656
      else (priority ("Test data size: " ^ string_of_int k);
berghofe@14105
   657
        case iter (fn () => !test_fn k) 1 of
skalberg@15531
   658
          NONE => test (k+1) | SOME x => SOME x);
berghofe@15029
   659
  in test 0 end);
berghofe@14105
   660
berghofe@14105
   661
fun test_goal ({size, iterations, default_type}, tvinsts) i st =
berghofe@14105
   662
  let
berghofe@14105
   663
    val sg = Toplevel.sign_of st;
berghofe@14105
   664
    fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
berghofe@14105
   665
      | strip t = t;
berghofe@14105
   666
    val (gi, frees) = Logic.goal_params
berghofe@14105
   667
      (prop_of (snd (snd (Proof.get_goal (Toplevel.proof_of st))))) i;
berghofe@14105
   668
    val gi' = ObjectLogic.atomize_term sg (map_term_types
skalberg@15570
   669
      (map_type_tfree (fn p as (s, _) => getOpt (assoc (tvinsts, s),
skalberg@15570
   670
        getOpt (default_type,TFree p)))) (subst_bounds (frees, strip gi)));
berghofe@14105
   671
  in case test_term (Toplevel.theory_of st) size iterations gi' of
skalberg@15531
   672
      NONE => writeln "No counterexamples found."
skalberg@15531
   673
    | SOME cex => writeln ("Counterexample found:\n" ^
berghofe@14105
   674
        Pretty.string_of (Pretty.chunks (map (fn (s, t) =>
berghofe@14105
   675
          Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1,
berghofe@14105
   676
            Sign.pretty_term sg t]) cex)))
berghofe@14105
   677
  end;
berghofe@14105
   678
berghofe@14105
   679
berghofe@12452
   680
(**** Interface ****)
berghofe@12452
   681
berghofe@13731
   682
val str = setmp print_mode [] Pretty.str;
berghofe@13731
   683
berghofe@11520
   684
fun parse_mixfix rd s =
berghofe@11520
   685
  (case Scan.finite Symbol.stopper (Scan.repeat
berghofe@11520
   686
     (   $$ "_" >> K Arg
berghofe@11520
   687
      || $$ "?" >> K Ignore
berghofe@11520
   688
      || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
berghofe@11520
   689
      || $$ "{" |-- $$ "*" |-- Scan.repeat1
berghofe@11520
   690
           (   $$ "'" |-- Scan.one Symbol.not_eof
berghofe@11520
   691
            || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --|
berghofe@12452
   692
         $$ "*" --| $$ "}" >> (Quote o rd o implode)
berghofe@11520
   693
      || Scan.repeat1
berghofe@11520
   694
           (   $$ "'" |-- Scan.one Symbol.not_eof
berghofe@11520
   695
            || Scan.unless ($$ "_" || $$ "?" || $$ "/" || $$ "{" |-- $$ "*")
berghofe@13731
   696
                 (Scan.one Symbol.not_eof)) >> (Pretty o str o implode)))
berghofe@11520
   697
       (Symbol.explode s) of
berghofe@11520
   698
     (p, []) => p
berghofe@11520
   699
   | _ => error ("Malformed annotation: " ^ quote s));
berghofe@11520
   700
wenzelm@11546
   701
structure P = OuterParse and K = OuterSyntax.Keyword;
berghofe@11520
   702
berghofe@11520
   703
val assoc_typeP =
berghofe@11520
   704
  OuterSyntax.command "types_code"
wenzelm@11546
   705
  "associate types with target language types" K.thy_decl
berghofe@11520
   706
    (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")") >>
berghofe@12452
   707
     (fn xs => Toplevel.theory (fn thy => assoc_types
berghofe@12452
   708
       (map (fn (name, mfx) => (name, parse_mixfix
berghofe@12452
   709
         (typ_of o read_ctyp (sign_of thy)) mfx)) xs) thy)));
berghofe@11520
   710
berghofe@11520
   711
val assoc_constP =
berghofe@11520
   712
  OuterSyntax.command "consts_code"
wenzelm@11546
   713
  "associate constants with target language code" K.thy_decl
berghofe@11520
   714
    (Scan.repeat1
wenzelm@13003
   715
       (P.xname -- (Scan.option (P.$$$ "::" |-- P.typ)) --|
berghofe@11520
   716
        P.$$$ "(" -- P.string --| P.$$$ ")") >>
berghofe@11520
   717
     (fn xs => Toplevel.theory (fn thy => assoc_consts
berghofe@11520
   718
       (map (fn ((name, optype), mfx) => (name, optype, parse_mixfix
berghofe@11520
   719
         (term_of o read_cterm (sign_of thy) o rpair TypeInfer.logicT) mfx))
berghofe@11520
   720
           xs) thy)));
berghofe@11520
   721
berghofe@11520
   722
val generate_codeP =
wenzelm@11546
   723
  OuterSyntax.command "generate_code" "generates code for terms" K.thy_decl
wenzelm@13003
   724
    (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") --
berghofe@13753
   725
     Scan.optional (P.$$$ "[" |-- P.enum "," P.xname --| P.$$$ "]") (!mode) --
wenzelm@13003
   726
     Scan.repeat1 (P.name --| P.$$$ "=" -- P.term) >>
berghofe@13753
   727
     (fn ((opt_fname, mode'), xs) => Toplevel.theory (fn thy =>
berghofe@11520
   728
        ((case opt_fname of
skalberg@15531
   729
            NONE => use_text Context.ml_output false
skalberg@15531
   730
          | SOME fname => File.write (Path.unpack fname))
berghofe@13753
   731
              (setmp mode mode' (generate_code thy) xs); thy))));
berghofe@11520
   732
berghofe@14105
   733
val params =
berghofe@14105
   734
  [("size", P.nat >> (K o set_size)),
berghofe@14105
   735
   ("iterations", P.nat >> (K o set_iterations)),
berghofe@14105
   736
   ("default_type", P.typ >> set_default_type)];
berghofe@14105
   737
berghofe@14105
   738
val parse_test_params = P.short_ident :-- (fn s =>
skalberg@15570
   739
  P.$$$ "=" |-- getOpt (assoc (params, s), Scan.fail)) >> snd;
berghofe@14105
   740
berghofe@14105
   741
fun parse_tyinst xs =
berghofe@14105
   742
  (P.type_ident --| P.$$$ "=" -- P.typ >> (fn (v, s) => fn sg =>
berghofe@14105
   743
    fn (x, ys) => (x, (v, typ_of (read_ctyp sg s)) :: ys))) xs;
berghofe@14105
   744
berghofe@14105
   745
fun app [] x = x
berghofe@14105
   746
  | app (f :: fs) x = app fs (f x);
berghofe@14105
   747
berghofe@14105
   748
val test_paramsP =
berghofe@14105
   749
  OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl
berghofe@14105
   750
    (P.$$$ "[" |-- P.list1 parse_test_params --| P.$$$ "]" >>
berghofe@14105
   751
      (fn fs => Toplevel.theory (fn thy =>
berghofe@14105
   752
         map_test_params (app (map (fn f => f (sign_of thy)) fs)) thy)));
berghofe@14105
   753
berghofe@14105
   754
val testP =
berghofe@14105
   755
  OuterSyntax.command "quickcheck" "try to find counterexample for subgoal" K.diag
berghofe@14105
   756
  (Scan.option (P.$$$ "[" |-- P.list1
berghofe@14105
   757
    (   parse_test_params >> (fn f => fn sg => apfst (f sg))
berghofe@14105
   758
     || parse_tyinst) --| P.$$$ "]") -- Scan.optional P.nat 1 >>
berghofe@14105
   759
    (fn (ps, g) => Toplevel.keep (fn st =>
skalberg@15570
   760
      test_goal (app (getOpt (Option.map
skalberg@15570
   761
          (map (fn f => f (Toplevel.sign_of st))) ps, []))
berghofe@14105
   762
        (get_test_params (Toplevel.theory_of st), [])) g st)));
berghofe@14105
   763
berghofe@14105
   764
val parsers = [assoc_typeP, assoc_constP, generate_codeP, test_paramsP, testP];
berghofe@11520
   765
berghofe@12452
   766
val setup =
berghofe@12452
   767
  [CodegenData.init,
berghofe@12452
   768
   add_codegen "default" default_codegen,
berghofe@12452
   769
   add_tycodegen "default" default_tycodegen,
berghofe@12555
   770
   assoc_types [("fun", parse_mixfix (K dummyT) "(_ ->/ _)")],
berghofe@12555
   771
   Attrib.add_attributes [("code",
berghofe@12555
   772
     (code_attr, K Attrib.undef_local_attribute),
berghofe@15261
   773
     "declare theorems for code generation")],
berghofe@15261
   774
   add_attribute "unfold" (Scan.succeed unfold_attr)];
berghofe@11520
   775
berghofe@11520
   776
end;
berghofe@11520
   777
berghofe@11520
   778
OuterSyntax.add_parsers Codegen.parsers;