src/Pure/codegen.ML
author berghofe
Thu Mar 28 16:28:12 2002 +0100 (2002-03-28)
changeset 13073 cc9d7f403a4b
parent 13003 3d5807d45439
child 13731 e2d17090052b
permissions -rw-r--r--
mk_const_id now checks for clashes with reserved ML identifiers.
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
(**** retrieve definition of constant ****)
berghofe@11520
   210
berghofe@11520
   211
fun is_instance thy T1 T2 =
berghofe@11520
   212
  Type.typ_instance (Sign.tsig_of (sign_of thy), T1, Type.varifyT T2);
berghofe@11520
   213
berghofe@11520
   214
fun get_assoc_code thy s T = apsome snd (find_first (fn ((s', T'), _) =>
berghofe@11520
   215
  s = s' andalso is_instance thy T T') (#consts (CodegenData.get thy)));
berghofe@11520
   216
berghofe@11520
   217
fun get_defn thy s T =
berghofe@11520
   218
  let
berghofe@11520
   219
    val axms = flat (map (Symtab.dest o #axioms o Theory.rep_theory)
berghofe@11520
   220
      (thy :: Theory.ancestors_of thy));
berghofe@11520
   221
    val defs = mapfilter (fn (_, t) =>
berghofe@11520
   222
      (let
berghofe@11520
   223
         val (lhs, rhs) = Logic.dest_equals t;
berghofe@11520
   224
         val (c, args) = strip_comb lhs;
berghofe@11520
   225
         val (s', T') = dest_Const c
berghofe@11520
   226
       in if s=s' then Some (T', (args, rhs)) else None end) handle TERM _ =>
berghofe@11520
   227
         None) axms;
berghofe@11520
   228
    val i = find_index (is_instance thy T o fst) defs
berghofe@11520
   229
  in
berghofe@11520
   230
    if i>=0 then Some (snd (nth_elem (i, defs)),
berghofe@11520
   231
      if length defs = 1 then None else Some i)
berghofe@11520
   232
    else None
berghofe@11520
   233
  end;
berghofe@11520
   234
berghofe@11520
   235
berghofe@11520
   236
(**** make valid ML identifiers ****)
berghofe@11520
   237
berghofe@11520
   238
fun gen_mk_id kind rename sg s =
berghofe@11520
   239
  let
berghofe@11520
   240
    val (xs as x::_) = explode (rename (space_implode "_"
berghofe@11520
   241
      (NameSpace.unpack (Sign.cond_extern sg kind s))));
berghofe@11520
   242
    fun check_str [] = ""
berghofe@12555
   243
      | check_str (" " :: xs) = "_" ^ check_str xs
berghofe@12555
   244
      | check_str (x :: xs) =
berghofe@12824
   245
          (if Symbol.is_letdig x then x
berghofe@11520
   246
           else "_" ^ string_of_int (ord x)) ^ check_str xs
berghofe@11520
   247
  in
berghofe@11520
   248
    (if not (Symbol.is_letter x) then "id" else "") ^ check_str xs
berghofe@11520
   249
  end;
berghofe@11520
   250
berghofe@13073
   251
val mk_const_id = gen_mk_id Sign.constK
berghofe@13073
   252
  (fn s => if s mem ThmDatabase.ml_reserved then s ^ "_const" else s);
berghofe@13073
   253
berghofe@11520
   254
val mk_type_id = gen_mk_id Sign.typeK
berghofe@11520
   255
  (fn s => if s mem ThmDatabase.ml_reserved then s ^ "_type" else s);
berghofe@11520
   256
berghofe@11520
   257
fun rename_term t =
berghofe@11520
   258
  let
berghofe@11520
   259
    val names = add_term_names (t, map (fst o fst o dest_Var) (term_vars t));
berghofe@11520
   260
    val clash = names inter ThmDatabase.ml_reserved;
berghofe@11520
   261
    val ps = clash ~~ variantlist (clash, names);
berghofe@11520
   262
berghofe@11520
   263
    fun rename (Var ((a, i), T)) = Var ((if_none (assoc (ps, a)) a, i), T)
berghofe@11520
   264
      | rename (Free (a, T)) = Free (if_none (assoc (ps, a)) a, T)
berghofe@11520
   265
      | rename (Abs (s, T, t)) = Abs (s, T, rename t)
berghofe@11520
   266
      | rename (t $ u) = rename t $ rename u
berghofe@11520
   267
      | rename t = t;
berghofe@11520
   268
  in
berghofe@11520
   269
    rename t
berghofe@11520
   270
  end;
berghofe@11520
   271
berghofe@11520
   272
berghofe@12452
   273
(**** invoke suitable code generator for term / type ****)
berghofe@11520
   274
berghofe@12452
   275
fun invoke_codegen thy dep brack (gr, t) = (case get_first
berghofe@11520
   276
   (fn (_, f) => f thy gr dep brack t) (#codegens (CodegenData.get thy)) of
berghofe@11520
   277
      None => error ("Unable to generate code for term:\n" ^
berghofe@11520
   278
        Sign.string_of_term (sign_of thy) t ^ "\nrequired by:\n" ^
berghofe@11520
   279
        commas (Graph.all_succs gr [dep]))
berghofe@12452
   280
    | Some x => x);
berghofe@12452
   281
berghofe@12452
   282
fun invoke_tycodegen thy dep brack (gr, T) = (case get_first
berghofe@12452
   283
   (fn (_, f) => f thy gr dep brack T) (#tycodegens (CodegenData.get thy)) of
berghofe@12452
   284
      None => error ("Unable to generate code for type:\n" ^
berghofe@12452
   285
        Sign.string_of_typ (sign_of thy) T ^ "\nrequired by:\n" ^
berghofe@12452
   286
        commas (Graph.all_succs gr [dep]))
berghofe@12452
   287
    | Some x => x);
berghofe@11520
   288
berghofe@11520
   289
berghofe@11520
   290
(**** code generator for mixfix expressions ****)
berghofe@11520
   291
berghofe@11520
   292
fun parens p = Pretty.block [Pretty.str "(", p, Pretty.str ")"];
berghofe@11520
   293
berghofe@11520
   294
fun pretty_fn [] p = [p]
berghofe@11520
   295
  | pretty_fn (x::xs) p = Pretty.str ("fn " ^ x ^ " =>") ::
berghofe@11520
   296
      Pretty.brk 1 :: pretty_fn xs p;
berghofe@11520
   297
berghofe@11520
   298
fun pretty_mixfix [] [] _ = []
berghofe@11520
   299
  | pretty_mixfix (Arg :: ms) (p :: ps) qs = p :: pretty_mixfix ms ps qs
berghofe@12452
   300
  | pretty_mixfix (Ignore :: ms) ps qs = pretty_mixfix ms ps qs
berghofe@11520
   301
  | pretty_mixfix (Pretty p :: ms) ps qs = p :: pretty_mixfix ms ps qs
berghofe@12452
   302
  | pretty_mixfix (Quote _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs;
berghofe@11520
   303
berghofe@11520
   304
berghofe@12452
   305
(**** default code generators ****)
berghofe@11520
   306
berghofe@11520
   307
fun eta_expand t ts i =
berghofe@11520
   308
  let
berghofe@11520
   309
    val (Ts, _) = strip_type (fastype_of t);
berghofe@11520
   310
    val j = i - length ts
berghofe@11520
   311
  in
berghofe@11520
   312
    foldr (fn (T, t) => Abs ("x", T, t))
berghofe@11520
   313
      (take (j, Ts), list_comb (t, ts @ map Bound (j-1 downto 0)))
berghofe@11520
   314
  end;
berghofe@11520
   315
berghofe@11520
   316
fun mk_app _ p [] = p
berghofe@11520
   317
  | mk_app brack p ps = if brack then
berghofe@11520
   318
       Pretty.block (Pretty.str "(" ::
berghofe@11520
   319
         separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"])
berghofe@11520
   320
     else Pretty.block (separate (Pretty.brk 1) (p :: ps));
berghofe@11520
   321
berghofe@11520
   322
fun new_names t xs = variantlist (xs,
berghofe@11520
   323
  map (fst o fst o dest_Var) (term_vars t) union
berghofe@11520
   324
  add_term_names (t, ThmDatabase.ml_reserved));
berghofe@11520
   325
berghofe@11520
   326
fun new_name t x = hd (new_names t [x]);
berghofe@11520
   327
berghofe@11520
   328
fun default_codegen thy gr dep brack t =
berghofe@11520
   329
  let
berghofe@11520
   330
    val (u, ts) = strip_comb t;
berghofe@12452
   331
    fun codegens brack = foldl_map (invoke_codegen thy dep brack)
berghofe@11520
   332
  in (case u of
berghofe@11520
   333
      Var ((s, i), _) =>
berghofe@12452
   334
        let val (gr', ps) = codegens true (gr, ts)
berghofe@11520
   335
        in Some (gr', mk_app brack (Pretty.str (s ^
berghofe@11520
   336
           (if i=0 then "" else string_of_int i))) ps)
berghofe@11520
   337
        end
berghofe@11520
   338
berghofe@11520
   339
    | Free (s, _) =>
berghofe@12452
   340
        let val (gr', ps) = codegens true (gr, ts)
berghofe@11520
   341
        in Some (gr', mk_app brack (Pretty.str s) ps) end
berghofe@11520
   342
berghofe@11520
   343
    | Const (s, T) =>
berghofe@11520
   344
      (case get_assoc_code thy s T of
berghofe@11520
   345
         Some ms =>
berghofe@11520
   346
           let val i = num_args ms
berghofe@11520
   347
           in if length ts < i then
berghofe@11520
   348
               default_codegen thy gr dep brack (eta_expand u ts i)
berghofe@11520
   349
             else
berghofe@11520
   350
               let
berghofe@12452
   351
                 val (ts1, ts2) = args_of ms ts;
berghofe@12452
   352
                 val (gr1, ps1) = codegens false (gr, ts1);
berghofe@12452
   353
                 val (gr2, ps2) = codegens true (gr1, ts2);
berghofe@12452
   354
                 val (gr3, ps3) = codegens false (gr2, quotes_of ms);
berghofe@11520
   355
               in
berghofe@11520
   356
                 Some (gr3, mk_app brack (Pretty.block (pretty_mixfix ms ps1 ps3)) ps2)
berghofe@11520
   357
               end
berghofe@11520
   358
           end
berghofe@11520
   359
       | None => (case get_defn thy s T of
berghofe@11520
   360
           None => None
berghofe@11520
   361
         | Some ((args, rhs), k) =>
berghofe@11520
   362
             let
berghofe@11520
   363
               val id = mk_const_id (sign_of thy) s ^ (case k of
berghofe@11520
   364
                 None => "" | Some i => "_def" ^ string_of_int i);
berghofe@12452
   365
               val (gr', ps) = codegens true (gr, ts);
berghofe@11520
   366
             in
berghofe@11520
   367
               Some (Graph.add_edge (id, dep) gr' handle Graph.UNDEF _ =>
berghofe@11520
   368
                 let
berghofe@11520
   369
                   val _ = message ("expanding definition of " ^ s);
berghofe@11520
   370
                   val (Ts, _) = strip_type T;
berghofe@11520
   371
                   val (args', rhs') =
berghofe@11520
   372
                     if not (null args) orelse null Ts then (args, rhs) else
berghofe@11520
   373
                       let val v = Free (new_name rhs "x", hd Ts)
berghofe@11520
   374
                       in ([v], betapply (rhs, v)) end;
berghofe@12452
   375
                   val (gr1, p) = invoke_codegen thy id false
berghofe@12452
   376
                     (Graph.add_edge (id, dep)
berghofe@12452
   377
                        (Graph.new_node (id, (None, "")) gr'), rhs');
berghofe@12452
   378
                   val (gr2, xs) = codegens false (gr1, args');
berghofe@12580
   379
                   val (gr3, ty) = invoke_tycodegen thy id false (gr2, T);
berghofe@11520
   380
                 in Graph.map_node id (K (None, Pretty.string_of (Pretty.block
berghofe@12580
   381
                   (separate (Pretty.brk 1) (if null args' then
berghofe@12580
   382
                       [Pretty.str ("val " ^ id ^ " :"), ty]
berghofe@12580
   383
                     else Pretty.str ("fun " ^ id) :: xs) @
berghofe@12580
   384
                    [Pretty.str " =", Pretty.brk 1, p, Pretty.str ";"])) ^ "\n\n")) gr3
berghofe@11520
   385
                 end, mk_app brack (Pretty.str id) ps)
berghofe@11520
   386
             end))
berghofe@11520
   387
berghofe@11520
   388
    | Abs _ =>
berghofe@11520
   389
      let
berghofe@11520
   390
        val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
berghofe@11520
   391
        val t = strip_abs_body u
berghofe@11520
   392
        val bs' = new_names t bs;
berghofe@12452
   393
        val (gr1, ps) = codegens true (gr, ts);
berghofe@12452
   394
        val (gr2, p) = invoke_codegen thy dep false
berghofe@12452
   395
          (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
berghofe@11520
   396
      in
berghofe@11520
   397
        Some (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
berghofe@11520
   398
          [Pretty.str ")"])) ps)
berghofe@11520
   399
      end
berghofe@11520
   400
berghofe@11520
   401
    | _ => None)
berghofe@11520
   402
  end;
berghofe@11520
   403
berghofe@12452
   404
fun default_tycodegen thy gr dep brack (TVar ((s, i), _)) =
berghofe@12452
   405
      Some (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
berghofe@12452
   406
  | default_tycodegen thy gr dep brack (TFree (s, _)) = Some (gr, Pretty.str s)
berghofe@12452
   407
  | default_tycodegen thy gr dep brack (Type (s, Ts)) =
berghofe@12452
   408
      (case assoc (#types (CodegenData.get thy), s) of
berghofe@12452
   409
         None => None
berghofe@12452
   410
       | Some ms =>
berghofe@12452
   411
           let
berghofe@12452
   412
             val (gr', ps) = foldl_map
berghofe@12452
   413
               (invoke_tycodegen thy dep false) (gr, fst (args_of ms Ts));
berghofe@12452
   414
             val (gr'', qs) = foldl_map
berghofe@12452
   415
               (invoke_tycodegen thy dep false) (gr', quotes_of ms)
berghofe@12452
   416
           in Some (gr'', Pretty.block (pretty_mixfix ms ps qs)) end);
berghofe@12452
   417
berghofe@11520
   418
berghofe@11520
   419
fun output_code gr xs = implode (map (snd o Graph.get_node gr)
berghofe@11520
   420
  (rev (Graph.all_preds gr xs)));
berghofe@11520
   421
berghofe@11520
   422
fun gen_generate_code prep_term thy = Pretty.setmp_margin 80 (fn xs =>
berghofe@11520
   423
  let
berghofe@11520
   424
    val sg = sign_of thy;
berghofe@11520
   425
    val gr = Graph.new_node ("<Top>", (None, "")) Graph.empty;
berghofe@11520
   426
    val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
berghofe@12452
   427
      (invoke_codegen thy "<Top>" false (gr, t)))
berghofe@12452
   428
        (gr, map (apsnd (prep_term sg)) xs)
berghofe@11520
   429
  in
berghofe@11520
   430
    "structure Generated =\nstruct\n\n" ^
berghofe@11520
   431
    output_code gr' ["<Top>"] ^
berghofe@11520
   432
    space_implode "\n\n" (map (fn (s', p) => Pretty.string_of (Pretty.block
berghofe@11520
   433
      [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"])) ps) ^
berghofe@11520
   434
    "\n\nend;\n\nopen Generated;\n"
berghofe@11520
   435
  end);
berghofe@11520
   436
berghofe@11520
   437
val generate_code_i = gen_generate_code (K I);
berghofe@11520
   438
val generate_code = gen_generate_code
berghofe@11520
   439
  (fn sg => term_of o read_cterm sg o rpair TypeInfer.logicT);
berghofe@11520
   440
berghofe@12452
   441
berghofe@12452
   442
(**** Interface ****)
berghofe@12452
   443
berghofe@11520
   444
fun parse_mixfix rd s =
berghofe@11520
   445
  (case Scan.finite Symbol.stopper (Scan.repeat
berghofe@11520
   446
     (   $$ "_" >> K Arg
berghofe@11520
   447
      || $$ "?" >> K Ignore
berghofe@11520
   448
      || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
berghofe@11520
   449
      || $$ "{" |-- $$ "*" |-- Scan.repeat1
berghofe@11520
   450
           (   $$ "'" |-- Scan.one Symbol.not_eof
berghofe@11520
   451
            || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --|
berghofe@12452
   452
         $$ "*" --| $$ "}" >> (Quote o rd o implode)
berghofe@11520
   453
      || Scan.repeat1
berghofe@11520
   454
           (   $$ "'" |-- Scan.one Symbol.not_eof
berghofe@11520
   455
            || Scan.unless ($$ "_" || $$ "?" || $$ "/" || $$ "{" |-- $$ "*")
berghofe@11520
   456
                 (Scan.one Symbol.not_eof)) >> (Pretty o Pretty.str o implode)))
berghofe@11520
   457
       (Symbol.explode s) of
berghofe@11520
   458
     (p, []) => p
berghofe@11520
   459
   | _ => error ("Malformed annotation: " ^ quote s));
berghofe@11520
   460
wenzelm@11546
   461
structure P = OuterParse and K = OuterSyntax.Keyword;
berghofe@11520
   462
berghofe@11520
   463
val assoc_typeP =
berghofe@11520
   464
  OuterSyntax.command "types_code"
wenzelm@11546
   465
  "associate types with target language types" K.thy_decl
berghofe@11520
   466
    (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")") >>
berghofe@12452
   467
     (fn xs => Toplevel.theory (fn thy => assoc_types
berghofe@12452
   468
       (map (fn (name, mfx) => (name, parse_mixfix
berghofe@12452
   469
         (typ_of o read_ctyp (sign_of thy)) mfx)) xs) thy)));
berghofe@11520
   470
berghofe@11520
   471
val assoc_constP =
berghofe@11520
   472
  OuterSyntax.command "consts_code"
wenzelm@11546
   473
  "associate constants with target language code" K.thy_decl
berghofe@11520
   474
    (Scan.repeat1
wenzelm@13003
   475
       (P.xname -- (Scan.option (P.$$$ "::" |-- P.typ)) --|
berghofe@11520
   476
        P.$$$ "(" -- P.string --| P.$$$ ")") >>
berghofe@11520
   477
     (fn xs => Toplevel.theory (fn thy => assoc_consts
berghofe@11520
   478
       (map (fn ((name, optype), mfx) => (name, optype, parse_mixfix
berghofe@11520
   479
         (term_of o read_cterm (sign_of thy) o rpair TypeInfer.logicT) mfx))
berghofe@11520
   480
           xs) thy)));
berghofe@11520
   481
berghofe@11520
   482
val generate_codeP =
wenzelm@11546
   483
  OuterSyntax.command "generate_code" "generates code for terms" K.thy_decl
wenzelm@13003
   484
    (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") --
wenzelm@13003
   485
     Scan.repeat1 (P.name --| P.$$$ "=" -- P.term) >>
berghofe@11520
   486
     (fn (opt_fname, xs) => Toplevel.theory (fn thy =>
berghofe@11520
   487
        ((case opt_fname of
berghofe@11520
   488
            None => use_text Context.ml_output false
berghofe@11520
   489
          | Some fname => File.write (Path.unpack fname))
berghofe@11520
   490
              (generate_code thy xs); thy))));
berghofe@11520
   491
berghofe@11520
   492
val parsers = [assoc_typeP, assoc_constP, generate_codeP];
berghofe@11520
   493
berghofe@12452
   494
val setup =
berghofe@12452
   495
  [CodegenData.init,
berghofe@12452
   496
   add_codegen "default" default_codegen,
berghofe@12452
   497
   add_tycodegen "default" default_tycodegen,
berghofe@12555
   498
   assoc_types [("fun", parse_mixfix (K dummyT) "(_ ->/ _)")],
berghofe@12555
   499
   Attrib.add_attributes [("code",
berghofe@12555
   500
     (code_attr, K Attrib.undef_local_attribute),
berghofe@12555
   501
     "declare theorems for code generation")]];
berghofe@11520
   502
berghofe@11520
   503
end;
berghofe@11520
   504
berghofe@11520
   505
OuterSyntax.add_parsers Codegen.parsers;