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