src/Pure/codegen.ML
author berghofe
Wed Nov 27 17:22:18 2002 +0100 (2002-11-27)
changeset 13731 e2d17090052b
parent 13073 cc9d7f403a4b
child 13753 38b76f457b9c
permissions -rw-r--r--
Parameters in definitions are now renamed to avoid clashes with
reserved ML keywords.
berghofe@11520
     1
(*  Title:      Pure/codegen.ML
berghofe@11520
     2
    ID:         $Id$
wenzelm@11539
     3
    Author:     Stefan Berghofer, TU Muenchen
wenzelm@11539
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
berghofe@11520
     5
wenzelm@11539
     6
Generic code generator.
berghofe@11520
     7
*)
berghofe@11520
     8
berghofe@11520
     9
signature CODEGEN =
berghofe@11520
    10
sig
berghofe@11520
    11
  val quiet_mode : bool ref
berghofe@11520
    12
  val message : string -> unit
berghofe@11520
    13
berghofe@12452
    14
  datatype 'a mixfix =
berghofe@11520
    15
      Arg
berghofe@11520
    16
    | Ignore
berghofe@11520
    17
    | Pretty of Pretty.T
berghofe@12452
    18
    | Quote of 'a;
berghofe@11520
    19
berghofe@12452
    20
  type 'a codegen
berghofe@12452
    21
berghofe@12452
    22
  val add_codegen: string -> term codegen -> theory -> theory
berghofe@12452
    23
  val add_tycodegen: string -> typ codegen -> theory -> theory
berghofe@12555
    24
  val add_attribute: string -> theory attribute -> theory -> theory
berghofe@11520
    25
  val print_codegens: theory -> unit
berghofe@11520
    26
  val generate_code: theory -> (string * string) list -> string
berghofe@11520
    27
  val generate_code_i: theory -> (string * term) list -> string
berghofe@12452
    28
  val assoc_consts: (xstring * string option * term mixfix list) list -> theory -> theory
berghofe@12452
    29
  val assoc_consts_i: (xstring * typ option * term mixfix list) list -> theory -> theory
berghofe@12452
    30
  val assoc_types: (xstring * typ mixfix list) list -> theory -> theory
berghofe@12452
    31
  val get_assoc_code: theory -> string -> typ -> term mixfix list option
berghofe@12452
    32
  val get_assoc_type: theory -> string -> typ mixfix list option
berghofe@12452
    33
  val invoke_codegen: theory -> string -> bool ->
berghofe@12452
    34
    (exn option * string) Graph.T * term -> (exn option * string) Graph.T * Pretty.T
berghofe@12452
    35
  val invoke_tycodegen: theory -> string -> bool ->
berghofe@12452
    36
    (exn option * string) Graph.T * typ -> (exn option * string) Graph.T * Pretty.T
berghofe@11520
    37
  val mk_const_id: Sign.sg -> string -> string
berghofe@11520
    38
  val mk_type_id: Sign.sg -> string -> string
berghofe@11520
    39
  val rename_term: term -> term
berghofe@11520
    40
  val get_defn: theory -> string -> typ -> ((term list * term) * int option) option
berghofe@11520
    41
  val is_instance: theory -> typ -> typ -> bool
berghofe@11520
    42
  val parens: Pretty.T -> Pretty.T
berghofe@11520
    43
  val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
berghofe@11520
    44
  val eta_expand: term -> term list -> int -> term
berghofe@12452
    45
  val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
berghofe@11520
    46
  val parsers: OuterSyntax.parser list
berghofe@11520
    47
  val setup: (theory -> theory) list
berghofe@11520
    48
end;
berghofe@11520
    49
berghofe@11520
    50
structure Codegen : CODEGEN =
berghofe@11520
    51
struct
berghofe@11520
    52
berghofe@11520
    53
val quiet_mode = ref true;
berghofe@11520
    54
fun message s = if !quiet_mode then () else writeln s;
berghofe@11520
    55
berghofe@11520
    56
(**** Mixfix syntax ****)
berghofe@11520
    57
berghofe@12452
    58
datatype 'a mixfix =
berghofe@11520
    59
    Arg
berghofe@11520
    60
  | Ignore
berghofe@11520
    61
  | Pretty of Pretty.T
berghofe@12452
    62
  | Quote of 'a;
berghofe@11520
    63
berghofe@11520
    64
fun is_arg Arg = true
berghofe@11520
    65
  | is_arg Ignore = true
berghofe@11520
    66
  | is_arg _ = false;
berghofe@11520
    67
berghofe@12452
    68
fun quotes_of [] = []
berghofe@12452
    69
  | quotes_of (Quote q :: ms) = q :: quotes_of ms
berghofe@12452
    70
  | quotes_of (_ :: ms) = quotes_of ms;
berghofe@12452
    71
berghofe@12452
    72
fun args_of [] xs = ([], xs)
berghofe@12452
    73
  | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
berghofe@12452
    74
  | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
berghofe@12452
    75
  | args_of (_ :: ms) xs = args_of ms xs;
berghofe@11520
    76
wenzelm@12490
    77
fun num_args x = length (filter is_arg x);
berghofe@11520
    78
berghofe@11520
    79
berghofe@11520
    80
(**** theory data ****)
berghofe@11520
    81
berghofe@11520
    82
(* data kind 'Pure/codegen' *)
berghofe@11520
    83
berghofe@12452
    84
type 'a codegen = theory -> (exn option * string) Graph.T ->
berghofe@12452
    85
  string -> bool -> 'a -> ((exn option * string) Graph.T * Pretty.T) option;
berghofe@12452
    86
berghofe@11520
    87
structure CodegenArgs =
berghofe@11520
    88
struct
berghofe@11520
    89
  val name = "Pure/codegen";
berghofe@11520
    90
  type T =
berghofe@12452
    91
    {codegens : (string * term codegen) list,
berghofe@12452
    92
     tycodegens : (string * typ codegen) list,
berghofe@12452
    93
     consts : ((string * typ) * term mixfix list) list,
berghofe@12555
    94
     types : (string * typ mixfix list) list,
berghofe@12555
    95
     attrs: (string * theory attribute) list};
berghofe@11520
    96
berghofe@12555
    97
  val empty =
berghofe@12555
    98
    {codegens = [], tycodegens = [], consts = [], types = [], attrs = []};
berghofe@11520
    99
  val copy = I;
berghofe@11520
   100
  val prep_ext = I;
berghofe@11520
   101
berghofe@12555
   102
  fun merge
berghofe@12555
   103
    ({codegens = codegens1, tycodegens = tycodegens1,
berghofe@12555
   104
      consts = consts1, types = types1, attrs = attrs1},
berghofe@12555
   105
     {codegens = codegens2, tycodegens = tycodegens2,
berghofe@12555
   106
      consts = consts2, types = types2, attrs = attrs2}) =
berghofe@11520
   107
    {codegens = rev (merge_alists (rev codegens1) (rev codegens2)),
berghofe@12452
   108
     tycodegens = rev (merge_alists (rev tycodegens1) (rev tycodegens2)),
berghofe@12555
   109
     consts = merge_alists consts1 consts2,
berghofe@12555
   110
     types = merge_alists types1 types2,
berghofe@12555
   111
     attrs = merge_alists attrs1 attrs2};
berghofe@11520
   112
berghofe@12452
   113
  fun print sg ({codegens, tycodegens, ...} : T) =
berghofe@12452
   114
    Pretty.writeln (Pretty.chunks
berghofe@12452
   115
      [Pretty.strs ("term code generators:" :: map fst codegens),
berghofe@12452
   116
       Pretty.strs ("type code generators:" :: map fst tycodegens)]);
berghofe@11520
   117
end;
berghofe@11520
   118
berghofe@11520
   119
structure CodegenData = TheoryDataFun(CodegenArgs);
berghofe@11520
   120
val print_codegens = CodegenData.print;
berghofe@11520
   121
berghofe@11520
   122
berghofe@12452
   123
(**** add new code generators to theory ****)
berghofe@11520
   124
berghofe@11520
   125
fun add_codegen name f thy =
berghofe@12555
   126
  let val {codegens, tycodegens, consts, types, attrs} = CodegenData.get thy
berghofe@11520
   127
  in (case assoc (codegens, name) of
berghofe@12452
   128
      None => CodegenData.put {codegens = (name, f) :: codegens,
berghofe@12555
   129
        tycodegens = tycodegens, consts = consts, types = types,
berghofe@12555
   130
        attrs = attrs} thy
berghofe@12452
   131
    | Some _ => error ("Code generator " ^ name ^ " already declared"))
berghofe@12452
   132
  end;
berghofe@12452
   133
berghofe@12452
   134
fun add_tycodegen name f thy =
berghofe@12555
   135
  let val {codegens, tycodegens, consts, types, attrs} = CodegenData.get thy
berghofe@12452
   136
  in (case assoc (tycodegens, name) of
berghofe@12452
   137
      None => CodegenData.put {tycodegens = (name, f) :: tycodegens,
berghofe@12555
   138
        codegens = codegens, consts = consts, types = types,
berghofe@12555
   139
        attrs = attrs} thy
berghofe@11520
   140
    | Some _ => error ("Code generator " ^ name ^ " already declared"))
berghofe@11520
   141
  end;
berghofe@11520
   142
berghofe@11520
   143
berghofe@12555
   144
(**** code attribute ****)
berghofe@12555
   145
berghofe@12555
   146
fun add_attribute name att thy =
berghofe@12555
   147
  let val {codegens, tycodegens, consts, types, attrs} = CodegenData.get thy
berghofe@12555
   148
  in (case assoc (attrs, name) of
berghofe@12555
   149
      None => CodegenData.put {tycodegens = tycodegens,
berghofe@12555
   150
        codegens = codegens, consts = consts, types = types,
berghofe@12555
   151
        attrs = (name, att) :: attrs} thy
berghofe@12555
   152
    | Some _ => error ("Code attribute " ^ name ^ " already declared"))
berghofe@12555
   153
  end;
berghofe@12555
   154
berghofe@12555
   155
val code_attr =
berghofe@12555
   156
  Attrib.syntax (Scan.depend (fn thy => Scan.optional Args.name "" >>
berghofe@12555
   157
    (fn name => (thy, case assoc (#attrs (CodegenData.get thy), name) of
berghofe@12555
   158
          None => error ("Unknown code attribute: " ^ quote name)
berghofe@12555
   159
        | Some att => att)))); 
berghofe@12555
   160
berghofe@12555
   161
berghofe@11520
   162
(**** associate constants with target language code ****)
berghofe@11520
   163
berghofe@11520
   164
fun gen_assoc_consts prep_type xs thy = foldl (fn (thy, (s, tyopt, syn)) =>
berghofe@11520
   165
  let
berghofe@11520
   166
    val sg = sign_of thy;
berghofe@12555
   167
    val {codegens, tycodegens, consts, types, attrs} = CodegenData.get thy;
berghofe@11520
   168
    val cname = Sign.intern_const sg s;
berghofe@11520
   169
  in
berghofe@11520
   170
    (case Sign.const_type sg cname of
berghofe@11520
   171
       Some T =>
berghofe@11520
   172
         let val T' = (case tyopt of
berghofe@11520
   173
                None => T
berghofe@11520
   174
              | Some ty =>
berghofe@11520
   175
                  let val U = prep_type sg ty
berghofe@11520
   176
                  in if Type.typ_instance (Sign.tsig_of sg, U, T) then U
berghofe@11520
   177
                    else error ("Illegal type constraint for constant " ^ cname)
berghofe@11520
   178
                  end)
berghofe@11520
   179
         in (case assoc (consts, (cname, T')) of
berghofe@11520
   180
             None => CodegenData.put {codegens = codegens,
berghofe@12452
   181
               tycodegens = tycodegens,
berghofe@12555
   182
               consts = ((cname, T'), syn) :: consts,
berghofe@12555
   183
               types = types, attrs = attrs} thy
berghofe@11520
   184
           | Some _ => error ("Constant " ^ cname ^ " already associated with code"))
berghofe@11520
   185
         end
berghofe@11520
   186
     | _ => error ("Not a constant: " ^ s))
berghofe@11520
   187
  end) (thy, xs);
berghofe@11520
   188
berghofe@11520
   189
val assoc_consts_i = gen_assoc_consts (K I);
berghofe@11520
   190
val assoc_consts = gen_assoc_consts (fn sg => typ_of o read_ctyp sg);
berghofe@11520
   191
berghofe@11520
   192
(**** associate types with target language types ****)
berghofe@11520
   193
berghofe@11520
   194
fun assoc_types xs thy = foldl (fn (thy, (s, syn)) =>
berghofe@11520
   195
  let
berghofe@12555
   196
    val {codegens, tycodegens, consts, types, attrs} = CodegenData.get thy;
berghofe@11520
   197
    val tc = Sign.intern_tycon (sign_of thy) s
berghofe@11520
   198
  in
berghofe@11520
   199
    (case assoc (types, tc) of
berghofe@12452
   200
       None => CodegenData.put {codegens = codegens,
berghofe@12452
   201
         tycodegens = tycodegens, consts = consts,
berghofe@12555
   202
         types = (tc, syn) :: types, attrs = attrs} thy
berghofe@11520
   203
     | Some _ => error ("Type " ^ tc ^ " already associated with code"))
berghofe@11520
   204
  end) (thy, xs);
berghofe@11520
   205
berghofe@12452
   206
fun get_assoc_type thy s = assoc (#types (CodegenData.get thy), s);
wenzelm@11546
   207
berghofe@11520
   208
berghofe@11520
   209
(**** make valid ML identifiers ****)
berghofe@11520
   210
berghofe@11520
   211
fun gen_mk_id kind rename sg s =
berghofe@11520
   212
  let
berghofe@11520
   213
    val (xs as x::_) = explode (rename (space_implode "_"
berghofe@11520
   214
      (NameSpace.unpack (Sign.cond_extern sg kind s))));
berghofe@11520
   215
    fun check_str [] = ""
berghofe@12555
   216
      | check_str (" " :: xs) = "_" ^ check_str xs
berghofe@12555
   217
      | check_str (x :: xs) =
berghofe@12824
   218
          (if Symbol.is_letdig x then x
berghofe@11520
   219
           else "_" ^ string_of_int (ord x)) ^ check_str xs
berghofe@11520
   220
  in
berghofe@11520
   221
    (if not (Symbol.is_letter x) then "id" else "") ^ check_str xs
berghofe@11520
   222
  end;
berghofe@11520
   223
berghofe@13073
   224
val mk_const_id = gen_mk_id Sign.constK
berghofe@13073
   225
  (fn s => if s mem ThmDatabase.ml_reserved then s ^ "_const" else s);
berghofe@13073
   226
berghofe@11520
   227
val mk_type_id = gen_mk_id Sign.typeK
berghofe@11520
   228
  (fn s => if s mem ThmDatabase.ml_reserved then s ^ "_type" else s);
berghofe@11520
   229
berghofe@13731
   230
fun rename_terms ts =
berghofe@11520
   231
  let
berghofe@13731
   232
    val names = foldr add_term_names
berghofe@13731
   233
      (ts, map (fst o fst) (Drule.vars_of_terms ts));
berghofe@11520
   234
    val clash = names inter ThmDatabase.ml_reserved;
berghofe@11520
   235
    val ps = clash ~~ variantlist (clash, names);
berghofe@11520
   236
berghofe@11520
   237
    fun rename (Var ((a, i), T)) = Var ((if_none (assoc (ps, a)) a, i), T)
berghofe@11520
   238
      | rename (Free (a, T)) = Free (if_none (assoc (ps, a)) a, T)
berghofe@11520
   239
      | rename (Abs (s, T, t)) = Abs (s, T, rename t)
berghofe@11520
   240
      | rename (t $ u) = rename t $ rename u
berghofe@11520
   241
      | rename t = t;
berghofe@11520
   242
  in
berghofe@13731
   243
    map rename ts
berghofe@13731
   244
  end;
berghofe@13731
   245
berghofe@13731
   246
val rename_term = hd o rename_terms o single;
berghofe@13731
   247
berghofe@13731
   248
berghofe@13731
   249
(**** retrieve definition of constant ****)
berghofe@13731
   250
berghofe@13731
   251
fun is_instance thy T1 T2 =
berghofe@13731
   252
  Type.typ_instance (Sign.tsig_of (sign_of thy), T1, Type.varifyT T2);
berghofe@13731
   253
berghofe@13731
   254
fun get_assoc_code thy s T = apsome snd (find_first (fn ((s', T'), _) =>
berghofe@13731
   255
  s = s' andalso is_instance thy T T') (#consts (CodegenData.get thy)));
berghofe@13731
   256
berghofe@13731
   257
fun get_defn thy s T =
berghofe@13731
   258
  let
berghofe@13731
   259
    val axms = flat (map (Symtab.dest o #axioms o Theory.rep_theory)
berghofe@13731
   260
      (thy :: Theory.ancestors_of thy));
berghofe@13731
   261
    val defs = mapfilter (fn (_, t) =>
berghofe@13731
   262
      (let
berghofe@13731
   263
         val (lhs, rhs) = Logic.dest_equals t;
berghofe@13731
   264
         val (c, args) = strip_comb lhs;
berghofe@13731
   265
         val (s', T') = dest_Const c
berghofe@13731
   266
       in if s=s' then Some (T', split_last (rename_terms (args @ [rhs])))
berghofe@13731
   267
         else None end) handle TERM _ => None) axms;
berghofe@13731
   268
    val i = find_index (is_instance thy T o fst) defs
berghofe@13731
   269
  in
berghofe@13731
   270
    if i>=0 then Some (snd (nth_elem (i, defs)),
berghofe@13731
   271
      if length defs = 1 then None else Some i)
berghofe@13731
   272
    else None
berghofe@11520
   273
  end;
berghofe@11520
   274
berghofe@11520
   275
berghofe@12452
   276
(**** invoke suitable code generator for term / type ****)
berghofe@11520
   277
berghofe@12452
   278
fun invoke_codegen thy dep brack (gr, t) = (case get_first
berghofe@11520
   279
   (fn (_, f) => f thy gr dep brack t) (#codegens (CodegenData.get thy)) of
berghofe@11520
   280
      None => error ("Unable to generate code for term:\n" ^
berghofe@11520
   281
        Sign.string_of_term (sign_of thy) t ^ "\nrequired by:\n" ^
berghofe@11520
   282
        commas (Graph.all_succs gr [dep]))
berghofe@12452
   283
    | Some x => x);
berghofe@12452
   284
berghofe@12452
   285
fun invoke_tycodegen thy dep brack (gr, T) = (case get_first
berghofe@12452
   286
   (fn (_, f) => f thy gr dep brack T) (#tycodegens (CodegenData.get thy)) of
berghofe@12452
   287
      None => error ("Unable to generate code for type:\n" ^
berghofe@12452
   288
        Sign.string_of_typ (sign_of thy) T ^ "\nrequired by:\n" ^
berghofe@12452
   289
        commas (Graph.all_succs gr [dep]))
berghofe@12452
   290
    | Some x => x);
berghofe@11520
   291
berghofe@11520
   292
berghofe@11520
   293
(**** code generator for mixfix expressions ****)
berghofe@11520
   294
berghofe@11520
   295
fun parens p = Pretty.block [Pretty.str "(", p, Pretty.str ")"];
berghofe@11520
   296
berghofe@11520
   297
fun pretty_fn [] p = [p]
berghofe@11520
   298
  | pretty_fn (x::xs) p = Pretty.str ("fn " ^ x ^ " =>") ::
berghofe@11520
   299
      Pretty.brk 1 :: pretty_fn xs p;
berghofe@11520
   300
berghofe@11520
   301
fun pretty_mixfix [] [] _ = []
berghofe@11520
   302
  | pretty_mixfix (Arg :: ms) (p :: ps) qs = p :: pretty_mixfix ms ps qs
berghofe@12452
   303
  | pretty_mixfix (Ignore :: ms) ps qs = pretty_mixfix ms ps qs
berghofe@11520
   304
  | pretty_mixfix (Pretty p :: ms) ps qs = p :: pretty_mixfix ms ps qs
berghofe@12452
   305
  | pretty_mixfix (Quote _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs;
berghofe@11520
   306
berghofe@11520
   307
berghofe@12452
   308
(**** default code generators ****)
berghofe@11520
   309
berghofe@11520
   310
fun eta_expand t ts i =
berghofe@11520
   311
  let
berghofe@11520
   312
    val (Ts, _) = strip_type (fastype_of t);
berghofe@11520
   313
    val j = i - length ts
berghofe@11520
   314
  in
berghofe@11520
   315
    foldr (fn (T, t) => Abs ("x", T, t))
berghofe@11520
   316
      (take (j, Ts), list_comb (t, ts @ map Bound (j-1 downto 0)))
berghofe@11520
   317
  end;
berghofe@11520
   318
berghofe@11520
   319
fun mk_app _ p [] = p
berghofe@11520
   320
  | mk_app brack p ps = if brack then
berghofe@11520
   321
       Pretty.block (Pretty.str "(" ::
berghofe@11520
   322
         separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"])
berghofe@11520
   323
     else Pretty.block (separate (Pretty.brk 1) (p :: ps));
berghofe@11520
   324
berghofe@11520
   325
fun new_names t xs = variantlist (xs,
berghofe@11520
   326
  map (fst o fst o dest_Var) (term_vars t) union
berghofe@11520
   327
  add_term_names (t, ThmDatabase.ml_reserved));
berghofe@11520
   328
berghofe@11520
   329
fun new_name t x = hd (new_names t [x]);
berghofe@11520
   330
berghofe@11520
   331
fun default_codegen thy gr dep brack t =
berghofe@11520
   332
  let
berghofe@11520
   333
    val (u, ts) = strip_comb t;
berghofe@12452
   334
    fun codegens brack = foldl_map (invoke_codegen thy dep brack)
berghofe@11520
   335
  in (case u of
berghofe@11520
   336
      Var ((s, i), _) =>
berghofe@12452
   337
        let val (gr', ps) = codegens true (gr, ts)
berghofe@11520
   338
        in Some (gr', mk_app brack (Pretty.str (s ^
berghofe@11520
   339
           (if i=0 then "" else string_of_int i))) ps)
berghofe@11520
   340
        end
berghofe@11520
   341
berghofe@11520
   342
    | Free (s, _) =>
berghofe@12452
   343
        let val (gr', ps) = codegens true (gr, ts)
berghofe@11520
   344
        in Some (gr', mk_app brack (Pretty.str s) ps) end
berghofe@11520
   345
berghofe@11520
   346
    | Const (s, T) =>
berghofe@11520
   347
      (case get_assoc_code thy s T of
berghofe@11520
   348
         Some ms =>
berghofe@11520
   349
           let val i = num_args ms
berghofe@11520
   350
           in if length ts < i then
berghofe@11520
   351
               default_codegen thy gr dep brack (eta_expand u ts i)
berghofe@11520
   352
             else
berghofe@11520
   353
               let
berghofe@12452
   354
                 val (ts1, ts2) = args_of ms ts;
berghofe@12452
   355
                 val (gr1, ps1) = codegens false (gr, ts1);
berghofe@12452
   356
                 val (gr2, ps2) = codegens true (gr1, ts2);
berghofe@12452
   357
                 val (gr3, ps3) = codegens false (gr2, quotes_of ms);
berghofe@11520
   358
               in
berghofe@11520
   359
                 Some (gr3, mk_app brack (Pretty.block (pretty_mixfix ms ps1 ps3)) ps2)
berghofe@11520
   360
               end
berghofe@11520
   361
           end
berghofe@11520
   362
       | None => (case get_defn thy s T of
berghofe@11520
   363
           None => None
berghofe@11520
   364
         | Some ((args, rhs), k) =>
berghofe@11520
   365
             let
berghofe@11520
   366
               val id = mk_const_id (sign_of thy) s ^ (case k of
berghofe@11520
   367
                 None => "" | Some i => "_def" ^ string_of_int i);
berghofe@12452
   368
               val (gr', ps) = codegens true (gr, ts);
berghofe@11520
   369
             in
berghofe@11520
   370
               Some (Graph.add_edge (id, dep) gr' handle Graph.UNDEF _ =>
berghofe@11520
   371
                 let
berghofe@11520
   372
                   val _ = message ("expanding definition of " ^ s);
berghofe@11520
   373
                   val (Ts, _) = strip_type T;
berghofe@11520
   374
                   val (args', rhs') =
berghofe@11520
   375
                     if not (null args) orelse null Ts then (args, rhs) else
berghofe@11520
   376
                       let val v = Free (new_name rhs "x", hd Ts)
berghofe@11520
   377
                       in ([v], betapply (rhs, v)) end;
berghofe@12452
   378
                   val (gr1, p) = invoke_codegen thy id false
berghofe@12452
   379
                     (Graph.add_edge (id, dep)
berghofe@12452
   380
                        (Graph.new_node (id, (None, "")) gr'), rhs');
berghofe@12452
   381
                   val (gr2, xs) = codegens false (gr1, args');
berghofe@12580
   382
                   val (gr3, ty) = invoke_tycodegen thy id false (gr2, T);
berghofe@11520
   383
                 in Graph.map_node id (K (None, Pretty.string_of (Pretty.block
berghofe@12580
   384
                   (separate (Pretty.brk 1) (if null args' then
berghofe@12580
   385
                       [Pretty.str ("val " ^ id ^ " :"), ty]
berghofe@12580
   386
                     else Pretty.str ("fun " ^ id) :: xs) @
berghofe@12580
   387
                    [Pretty.str " =", Pretty.brk 1, p, Pretty.str ";"])) ^ "\n\n")) gr3
berghofe@11520
   388
                 end, mk_app brack (Pretty.str id) ps)
berghofe@11520
   389
             end))
berghofe@11520
   390
berghofe@11520
   391
    | Abs _ =>
berghofe@11520
   392
      let
berghofe@11520
   393
        val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
berghofe@11520
   394
        val t = strip_abs_body u
berghofe@11520
   395
        val bs' = new_names t bs;
berghofe@12452
   396
        val (gr1, ps) = codegens true (gr, ts);
berghofe@12452
   397
        val (gr2, p) = invoke_codegen thy dep false
berghofe@12452
   398
          (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
berghofe@11520
   399
      in
berghofe@11520
   400
        Some (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
berghofe@11520
   401
          [Pretty.str ")"])) ps)
berghofe@11520
   402
      end
berghofe@11520
   403
berghofe@11520
   404
    | _ => None)
berghofe@11520
   405
  end;
berghofe@11520
   406
berghofe@12452
   407
fun default_tycodegen thy gr dep brack (TVar ((s, i), _)) =
berghofe@12452
   408
      Some (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
berghofe@12452
   409
  | default_tycodegen thy gr dep brack (TFree (s, _)) = Some (gr, Pretty.str s)
berghofe@12452
   410
  | default_tycodegen thy gr dep brack (Type (s, Ts)) =
berghofe@12452
   411
      (case assoc (#types (CodegenData.get thy), s) of
berghofe@12452
   412
         None => None
berghofe@12452
   413
       | Some ms =>
berghofe@12452
   414
           let
berghofe@12452
   415
             val (gr', ps) = foldl_map
berghofe@12452
   416
               (invoke_tycodegen thy dep false) (gr, fst (args_of ms Ts));
berghofe@12452
   417
             val (gr'', qs) = foldl_map
berghofe@12452
   418
               (invoke_tycodegen thy dep false) (gr', quotes_of ms)
berghofe@12452
   419
           in Some (gr'', Pretty.block (pretty_mixfix ms ps qs)) end);
berghofe@12452
   420
berghofe@11520
   421
berghofe@11520
   422
fun output_code gr xs = implode (map (snd o Graph.get_node gr)
berghofe@11520
   423
  (rev (Graph.all_preds gr xs)));
berghofe@11520
   424
berghofe@11520
   425
fun gen_generate_code prep_term thy = Pretty.setmp_margin 80 (fn xs =>
berghofe@11520
   426
  let
berghofe@11520
   427
    val sg = sign_of thy;
berghofe@11520
   428
    val gr = Graph.new_node ("<Top>", (None, "")) Graph.empty;
berghofe@11520
   429
    val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
berghofe@12452
   430
      (invoke_codegen thy "<Top>" false (gr, t)))
berghofe@12452
   431
        (gr, map (apsnd (prep_term sg)) xs)
berghofe@11520
   432
  in
berghofe@11520
   433
    "structure Generated =\nstruct\n\n" ^
berghofe@11520
   434
    output_code gr' ["<Top>"] ^
berghofe@11520
   435
    space_implode "\n\n" (map (fn (s', p) => Pretty.string_of (Pretty.block
berghofe@11520
   436
      [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"])) ps) ^
berghofe@11520
   437
    "\n\nend;\n\nopen Generated;\n"
berghofe@11520
   438
  end);
berghofe@11520
   439
berghofe@11520
   440
val generate_code_i = gen_generate_code (K I);
berghofe@11520
   441
val generate_code = gen_generate_code
berghofe@11520
   442
  (fn sg => term_of o read_cterm sg o rpair TypeInfer.logicT);
berghofe@11520
   443
berghofe@12452
   444
berghofe@12452
   445
(**** Interface ****)
berghofe@12452
   446
berghofe@13731
   447
val str = setmp print_mode [] Pretty.str;
berghofe@13731
   448
berghofe@11520
   449
fun parse_mixfix rd s =
berghofe@11520
   450
  (case Scan.finite Symbol.stopper (Scan.repeat
berghofe@11520
   451
     (   $$ "_" >> K Arg
berghofe@11520
   452
      || $$ "?" >> K Ignore
berghofe@11520
   453
      || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
berghofe@11520
   454
      || $$ "{" |-- $$ "*" |-- Scan.repeat1
berghofe@11520
   455
           (   $$ "'" |-- Scan.one Symbol.not_eof
berghofe@11520
   456
            || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --|
berghofe@12452
   457
         $$ "*" --| $$ "}" >> (Quote o rd o implode)
berghofe@11520
   458
      || Scan.repeat1
berghofe@11520
   459
           (   $$ "'" |-- Scan.one Symbol.not_eof
berghofe@11520
   460
            || Scan.unless ($$ "_" || $$ "?" || $$ "/" || $$ "{" |-- $$ "*")
berghofe@13731
   461
                 (Scan.one Symbol.not_eof)) >> (Pretty o str o implode)))
berghofe@11520
   462
       (Symbol.explode s) of
berghofe@11520
   463
     (p, []) => p
berghofe@11520
   464
   | _ => error ("Malformed annotation: " ^ quote s));
berghofe@11520
   465
wenzelm@11546
   466
structure P = OuterParse and K = OuterSyntax.Keyword;
berghofe@11520
   467
berghofe@11520
   468
val assoc_typeP =
berghofe@11520
   469
  OuterSyntax.command "types_code"
wenzelm@11546
   470
  "associate types with target language types" K.thy_decl
berghofe@11520
   471
    (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")") >>
berghofe@12452
   472
     (fn xs => Toplevel.theory (fn thy => assoc_types
berghofe@12452
   473
       (map (fn (name, mfx) => (name, parse_mixfix
berghofe@12452
   474
         (typ_of o read_ctyp (sign_of thy)) mfx)) xs) thy)));
berghofe@11520
   475
berghofe@11520
   476
val assoc_constP =
berghofe@11520
   477
  OuterSyntax.command "consts_code"
wenzelm@11546
   478
  "associate constants with target language code" K.thy_decl
berghofe@11520
   479
    (Scan.repeat1
wenzelm@13003
   480
       (P.xname -- (Scan.option (P.$$$ "::" |-- P.typ)) --|
berghofe@11520
   481
        P.$$$ "(" -- P.string --| P.$$$ ")") >>
berghofe@11520
   482
     (fn xs => Toplevel.theory (fn thy => assoc_consts
berghofe@11520
   483
       (map (fn ((name, optype), mfx) => (name, optype, parse_mixfix
berghofe@11520
   484
         (term_of o read_cterm (sign_of thy) o rpair TypeInfer.logicT) mfx))
berghofe@11520
   485
           xs) thy)));
berghofe@11520
   486
berghofe@11520
   487
val generate_codeP =
wenzelm@11546
   488
  OuterSyntax.command "generate_code" "generates code for terms" K.thy_decl
wenzelm@13003
   489
    (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") --
wenzelm@13003
   490
     Scan.repeat1 (P.name --| P.$$$ "=" -- P.term) >>
berghofe@11520
   491
     (fn (opt_fname, xs) => Toplevel.theory (fn thy =>
berghofe@11520
   492
        ((case opt_fname of
berghofe@11520
   493
            None => use_text Context.ml_output false
berghofe@11520
   494
          | Some fname => File.write (Path.unpack fname))
berghofe@11520
   495
              (generate_code thy xs); thy))));
berghofe@11520
   496
berghofe@11520
   497
val parsers = [assoc_typeP, assoc_constP, generate_codeP];
berghofe@11520
   498
berghofe@12452
   499
val setup =
berghofe@12452
   500
  [CodegenData.init,
berghofe@12452
   501
   add_codegen "default" default_codegen,
berghofe@12452
   502
   add_tycodegen "default" default_tycodegen,
berghofe@12555
   503
   assoc_types [("fun", parse_mixfix (K dummyT) "(_ ->/ _)")],
berghofe@12555
   504
   Attrib.add_attributes [("code",
berghofe@12555
   505
     (code_attr, K Attrib.undef_local_attribute),
berghofe@12555
   506
     "declare theorems for code generation")]];
berghofe@11520
   507
berghofe@11520
   508
end;
berghofe@11520
   509
berghofe@11520
   510
OuterSyntax.add_parsers Codegen.parsers;