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