src/Pure/Tools/codegen_package.ML
author haftmann
Tue, 10 Oct 2006 09:17:17 +0200
changeset 20931 19d9b78218fd
parent 20896 1484c7af6d68
child 20976 e324808e9f1f
permissions -rw-r--r--
added code_abstype and code_constsubst
haftmann@18169
     1
(*  Title:      Pure/Tools/codegen_package.ML
haftmann@18169
     2
    ID:         $Id$
haftmann@18169
     3
    Author:     Florian Haftmann, TU Muenchen
haftmann@18169
     4
haftmann@20855
     5
Code generator extraction kernel. Code generator Isar setup.
haftmann@18169
     6
*)
haftmann@18169
     7
haftmann@18169
     8
signature CODEGEN_PACKAGE =
haftmann@18169
     9
sig
haftmann@20456
    10
  include BASIC_CODEGEN_THINGOL;
haftmann@20600
    11
  val codegen_term: theory -> term -> thm * iterm;
haftmann@20600
    12
  val eval_term: theory -> (string (*reference name!*) * 'a option ref) * term -> 'a;
haftmann@20699
    13
  val const_of_idf: theory -> string -> string * typ;
haftmann@20896
    14
  val get_root_module: theory -> CodegenThingol.code;
haftmann@18217
    15
haftmann@19884
    16
  type appgen;
haftmann@20439
    17
  val add_appconst: string * appgen -> theory -> theory;
haftmann@20600
    18
  val appgen_numeral: (theory -> term -> IntInf.int) -> appgen;
haftmann@19607
    19
  val appgen_char: (term -> int option) -> appgen;
haftmann@20105
    20
  val appgen_case: (theory -> term
haftmann@20105
    21
    -> ((string * typ) list * ((term * typ) * (term * term) list)) option)
haftmann@20105
    22
    -> appgen;
haftmann@20105
    23
  val appgen_let: appgen;
haftmann@18169
    24
end;
haftmann@18169
    25
haftmann@18217
    26
structure CodegenPackage : CODEGEN_PACKAGE =
haftmann@18169
    27
struct
haftmann@18169
    28
haftmann@20896
    29
open BasicCodegenThingol;
haftmann@20896
    30
val tracing = CodegenThingol.tracing;
haftmann@20896
    31
val succeed = CodegenThingol.succeed;
haftmann@20896
    32
val fail = CodegenThingol.fail;
haftmann@19038
    33
haftmann@20699
    34
(** code extraction **)
haftmann@19038
    35
haftmann@20699
    36
(* theory data *)
haftmann@18217
    37
haftmann@20931
    38
structure Code = CodeDataFun
haftmann@20931
    39
(struct
haftmann@20931
    40
  val name = "Pure/code";
haftmann@20931
    41
  type T = CodegenThingol.code;
haftmann@20931
    42
  val empty = CodegenThingol.empty_code;
haftmann@20931
    43
  fun merge _ = CodegenThingol.merge_code;
haftmann@20931
    44
  fun purge _ NONE _ = CodegenThingol.empty_code
haftmann@20931
    45
    | purge NONE _ _ = CodegenThingol.empty_code
haftmann@20931
    46
    | purge (SOME thy) (SOME cs) code =
haftmann@20931
    47
        let
haftmann@20931
    48
          val cs_exisiting =
haftmann@20931
    49
            map_filter (CodegenNames.const_rev thy) (Graph.keys code);
haftmann@20931
    50
        in
haftmann@20931
    51
          Graph.del_nodes
haftmann@20931
    52
            ((Graph.all_succs code
haftmann@20931
    53
              o map (CodegenNames.const thy)
haftmann@20931
    54
              o filter (member CodegenConsts.eq_const cs_exisiting)
haftmann@20931
    55
              ) cs)
haftmann@20931
    56
            code
haftmann@20931
    57
        end;
haftmann@20931
    58
end);
haftmann@20931
    59
haftmann@20600
    60
type appgen = theory -> ((sort -> sort) * Sorts.algebra) * Consts.T
haftmann@20600
    61
  -> CodegenFuncgr.T
haftmann@20896
    62
  -> bool * string list option
haftmann@20896
    63
  -> (string * typ) * term list -> CodegenThingol.transact -> iterm * CodegenThingol.transact;
haftmann@20439
    64
haftmann@20439
    65
type appgens = (int * (appgen * stamp)) Symtab.table;
haftmann@20931
    66
val merge_appgens : appgens * appgens -> appgens =
haftmann@20931
    67
  Symtab.merge (fn ((bounds1, (_, stamp1)), (bounds2, (_, stamp2))) =>
haftmann@20931
    68
    bounds1 = bounds2 andalso stamp1 = stamp2);
haftmann@18217
    69
haftmann@20931
    70
structure Consttab = CodegenConsts.Consttab;
haftmann@20931
    71
type abstypes = typ Symtab.table * CodegenConsts.const Consttab.table;
haftmann@20931
    72
fun merge_abstypes ((typs1, consts1) : abstypes, (typs2, consts2) : abstypes) =
haftmann@20931
    73
  (Symtab.merge (Type.eq_type Vartab.empty) (typs1, typs2),
haftmann@20931
    74
    Consttab.merge CodegenConsts.eq_const (consts1, consts2));
haftmann@20456
    75
haftmann@20600
    76
structure CodegenPackageData = TheoryDataFun
haftmann@18217
    77
(struct
haftmann@19953
    78
  val name = "Pure/codegen_package";
haftmann@20931
    79
  type T = appgens * abstypes;
haftmann@20931
    80
  val empty = (Symtab.empty, (Symtab.empty, Consttab.empty));
haftmann@18217
    81
  val copy = I;
haftmann@18217
    82
  val extend = I;
haftmann@20931
    83
  fun merge _ ((appgens1, abstypes1), (appgens2, abstypes2)) =
haftmann@20931
    84
    (merge_appgens (appgens1, appgens2), merge_abstypes (abstypes1, abstypes2));
haftmann@20456
    85
  fun print _ _ = ();
haftmann@18217
    86
end);
haftmann@18217
    87
haftmann@20600
    88
val _ = Context.add_setup (Code.init #> CodegenPackageData.init);
wenzelm@18708
    89
haftmann@18865
    90
haftmann@20386
    91
(* extraction kernel *)
haftmann@18865
    92
haftmann@20931
    93
fun check_strict (false, _) has_seri x =
haftmann@19884
    94
      false
haftmann@20931
    95
  | check_strict (_, SOME targets) has_seri x =
haftmann@20699
    96
      not (has_seri targets x)
haftmann@20931
    97
  | check_strict (true, _) has_seri x =
haftmann@19884
    98
      true;
haftmann@19884
    99
haftmann@20931
   100
fun get_abstype thy (tyco, tys) = case Symtab.lookup ((fst o snd o CodegenPackageData.get) thy) tyco
haftmann@20931
   101
 of SOME ty => SOME ((map_atyps (fn TFree (n, _) => nth tys (the (Int.fromString n)))) ty)
haftmann@20931
   102
  | NONE => NONE;
haftmann@20931
   103
haftmann@20896
   104
fun ensure_def_class thy (algbr as ((proj_sort, _), _)) funcgr strct class trns =
haftmann@20456
   105
  let
haftmann@20896
   106
    val (v, cs) = (ClassPackage.the_consts_sign thy) class;
haftmann@20896
   107
    val superclasses = (proj_sort o Sign.super_classes thy) class;
haftmann@20896
   108
    val classops' = map (CodegenNames.const thy o CodegenConsts.norm_of_typ thy) cs;
haftmann@20896
   109
    val class' = CodegenNames.class thy class;
haftmann@20896
   110
    fun defgen_class trns =
haftmann@20896
   111
      trns
haftmann@20896
   112
      |> fold_map (ensure_def_class thy algbr funcgr strct) superclasses
haftmann@20896
   113
      ||>> (fold_map (exprgen_type thy algbr funcgr strct) o map snd) cs
haftmann@20896
   114
      |-> (fn (superclasses, classoptyps) => succeed
haftmann@20896
   115
        (CodegenThingol.Class (superclasses,
haftmann@20896
   116
          (unprefix "'" v, classops' ~~ classoptyps))))
haftmann@20456
   117
  in
haftmann@20456
   118
    trns
haftmann@20896
   119
    |> tracing (fn _ => "generating class " ^ quote class)
haftmann@20896
   120
    |> CodegenThingol.ensure_def defgen_class true
haftmann@20896
   121
        ("generating class " ^ quote class) class'
haftmann@20896
   122
    |> pair class'
haftmann@20456
   123
  end
haftmann@20600
   124
and ensure_def_tyco thy algbr funcgr strct tyco trns =
haftmann@20456
   125
  let
haftmann@20896
   126
    fun defgen_datatype trns =
haftmann@20896
   127
      case CodegenData.get_datatype thy tyco
haftmann@20896
   128
       of SOME (vs, cos) =>
haftmann@20896
   129
            trns
haftmann@20896
   130
            |> fold_map (exprgen_tyvar_sort thy algbr funcgr strct) vs
haftmann@20896
   131
            ||>> fold_map (fn (c, tys) =>
haftmann@20896
   132
              fold_map (exprgen_type thy algbr funcgr strct) tys
haftmann@20896
   133
              #-> (fn tys' =>
haftmann@20896
   134
                pair ((CodegenNames.const thy o CodegenConsts.norm_of_typ thy)
haftmann@20896
   135
                  (c, tys ---> Type (tyco, map TFree vs)), tys'))) cos
haftmann@20896
   136
            |-> (fn (vs, cos) => succeed (CodegenThingol.Datatype (vs, cos)))
haftmann@20896
   137
        | NONE =>
haftmann@20896
   138
            trns
haftmann@20896
   139
            |> fail ("No such datatype: " ^ quote tyco)
haftmann@20699
   140
    val tyco' = CodegenNames.tyco thy tyco;
haftmann@20931
   141
    val strict = check_strict strct (CodegenSerializer.tyco_has_serialization thy) tyco';
haftmann@20456
   142
  in
haftmann@20456
   143
    trns
haftmann@20835
   144
    |> tracing (fn _ => "generating type constructor " ^ quote tyco)
haftmann@20896
   145
    |> CodegenThingol.ensure_def defgen_datatype strict
haftmann@20456
   146
        ("generating type constructor " ^ quote tyco) tyco'
haftmann@20456
   147
    |> pair tyco'
haftmann@20456
   148
  end
haftmann@20600
   149
and exprgen_tyvar_sort thy (algbr as ((proj_sort, _), _)) funcgr strct (v, sort) trns =
haftmann@20456
   150
  trns
haftmann@20600
   151
  |> fold_map (ensure_def_class thy algbr funcgr strct) (proj_sort sort)
haftmann@20456
   152
  |-> (fn sort => pair (unprefix "'" v, sort))
haftmann@20600
   153
and exprgen_type thy algbr funcgr strct (TVar _) trns =
haftmann@20456
   154
      error "TVar encountered in typ during code generation"
haftmann@20600
   155
  | exprgen_type thy algbr funcgr strct (TFree vs) trns =
haftmann@20456
   156
      trns
haftmann@20600
   157
      |> exprgen_tyvar_sort thy algbr funcgr strct vs
haftmann@20456
   158
      |-> (fn (v, sort) => pair (ITyVar v))
haftmann@20600
   159
  | exprgen_type thy algbr funcgr strct (Type ("fun", [t1, t2])) trns =
haftmann@20456
   160
      trns
haftmann@20600
   161
      |> exprgen_type thy algbr funcgr strct t1
haftmann@20600
   162
      ||>> exprgen_type thy algbr funcgr strct t2
haftmann@20456
   163
      |-> (fn (t1', t2') => pair (t1' `-> t2'))
haftmann@20600
   164
  | exprgen_type thy algbr funcgr strct (Type (tyco, tys)) trns =
haftmann@20931
   165
      case get_abstype thy (tyco, tys)
haftmann@20931
   166
       of SOME ty =>
haftmann@20931
   167
            trns
haftmann@20931
   168
            |> exprgen_type thy algbr funcgr strct ty
haftmann@20931
   169
        | NONE =>
haftmann@20931
   170
            trns
haftmann@20931
   171
            |> ensure_def_tyco thy algbr funcgr strct tyco
haftmann@20931
   172
            ||>> fold_map (exprgen_type thy algbr funcgr strct) tys
haftmann@20931
   173
            |-> (fn (tyco, tys) => pair (tyco `%% tys));
haftmann@20456
   174
haftmann@20835
   175
exception CONSTRAIN of (string * typ) * typ;
haftmann@20600
   176
haftmann@20600
   177
fun exprgen_typinst thy (algbr as ((proj_sort, algebra), consts)) funcgr strct (ty_ctxt, sort_decl) trns =
haftmann@20456
   178
  let
haftmann@20456
   179
    val pp = Sign.pp thy;
haftmann@20456
   180
    datatype inst =
haftmann@20456
   181
        Inst of (class * string) * inst list list
haftmann@20456
   182
      | Contxt of (string * sort) * (class list * int);
haftmann@20456
   183
    fun classrel (l as Contxt (v_sort, (classes, n)), _) class  =
haftmann@20456
   184
          Contxt (v_sort, (class :: classes, n))
haftmann@20456
   185
      | classrel (Inst ((_, tyco), lss), _) class =
haftmann@20456
   186
          Inst ((class, tyco), lss);
haftmann@20456
   187
    fun constructor tyco iss class =
haftmann@20456
   188
      Inst ((class, tyco), (map o map) fst iss);
haftmann@20456
   189
    fun variable (TFree (v, sort)) =
haftmann@20456
   190
      let
haftmann@20456
   191
        val sort' = proj_sort sort;
haftmann@20456
   192
      in map_index (fn (n, class) => (Contxt ((v, sort'), ([], n)), class)) sort' end;
haftmann@20456
   193
    val insts = Sorts.of_sort_derivation pp algebra
haftmann@20456
   194
      {classrel = classrel, constructor = constructor, variable = variable}
haftmann@20456
   195
      (ty_ctxt, proj_sort sort_decl);
haftmann@20456
   196
    fun mk_dict (Inst (inst, instss)) trns =
haftmann@20456
   197
          trns
haftmann@20600
   198
          |> ensure_def_inst thy algbr funcgr strct inst
haftmann@20456
   199
          ||>> (fold_map o fold_map) mk_dict instss
haftmann@20456
   200
          |-> (fn (inst, instss) => pair (Instance (inst, instss)))
haftmann@20456
   201
      | mk_dict (Contxt ((v, sort), (classes, k))) trns =
haftmann@20456
   202
          trns
haftmann@20600
   203
          |> fold_map (ensure_def_class thy algbr funcgr strct) classes
haftmann@20456
   204
          |-> (fn classes => pair (Context (classes, (unprefix "'" v,
haftmann@20456
   205
                if length sort = 1 then ~1 else k))))
haftmann@20456
   206
  in
haftmann@20456
   207
    trns
haftmann@20456
   208
    |> fold_map mk_dict insts
haftmann@20456
   209
  end
haftmann@20600
   210
and exprgen_typinst_const thy (algbr as (_, consts)) funcgr strct (c, ty_ctxt) trns =
haftmann@20600
   211
  let
haftmann@20600
   212
    val c' = CodegenConsts.norm_of_typ thy (c, ty_ctxt)
haftmann@20699
   213
    val idf = CodegenNames.const thy c';
haftmann@20466
   214
    val ty_decl = Consts.declaration consts idf;
haftmann@20466
   215
    val insts = (op ~~ o apsnd (map (snd o dest_TVar)) oo pairself)
haftmann@20466
   216
      (curry (Consts.typargs consts) idf) (ty_ctxt, ty_decl);
haftmann@20600
   217
    val _ = if exists not (map (Sign.of_sort thy) insts)
haftmann@20835
   218
      then raise CONSTRAIN ((c, ty_decl), ty_ctxt) else ();
haftmann@18702
   219
  in
haftmann@18702
   220
    trns
haftmann@20600
   221
    |> fold_map (exprgen_typinst thy algbr funcgr strct) insts
haftmann@18865
   222
  end
haftmann@20896
   223
and ensure_def_inst thy (algbr as ((proj_sort, _), _)) funcgr strct (class, tyco) trns =
haftmann@18454
   224
  let
haftmann@20896
   225
    val (vs, classop_defs) = ((apsnd o map) Const o ClassPackage.the_inst_sign thy)
haftmann@20896
   226
      (class, tyco);
haftmann@20896
   227
    val classops = (map (CodegenConsts.norm_of_typ thy) o snd
haftmann@20896
   228
      o ClassPackage.the_consts_sign thy) class;
haftmann@20896
   229
    val arity_typ = Type (tyco, (map TFree vs));
haftmann@20896
   230
    val superclasses = (proj_sort o Sign.super_classes thy) class
haftmann@20896
   231
    fun gen_superarity superclass trns =
haftmann@20896
   232
      trns
haftmann@20896
   233
      |> ensure_def_class thy algbr funcgr strct superclass
haftmann@20896
   234
      ||>> exprgen_typinst thy algbr funcgr strct (arity_typ, [superclass])
haftmann@20896
   235
      |-> (fn (superclass, [Instance (inst, iss)]) => pair (superclass, (inst, iss)));
haftmann@20896
   236
    fun gen_classop_def (classop, t) trns =
haftmann@20896
   237
      trns
haftmann@20896
   238
      |> ensure_def_const thy algbr funcgr strct classop
haftmann@20896
   239
      ||>> exprgen_term thy algbr funcgr strct t;
haftmann@20896
   240
    fun defgen_inst trns =
haftmann@20896
   241
      trns
haftmann@20896
   242
      |> ensure_def_class thy algbr funcgr strct class
haftmann@20896
   243
      ||>> ensure_def_tyco thy algbr funcgr strct tyco
haftmann@20896
   244
      ||>> fold_map (exprgen_tyvar_sort thy algbr funcgr strct) vs
haftmann@20896
   245
      ||>> fold_map gen_superarity superclasses
haftmann@20896
   246
      ||>> fold_map gen_classop_def (classops ~~ classop_defs)
haftmann@20896
   247
      |-> (fn ((((class, tyco), arity), superarities), classops) =>
haftmann@20896
   248
             succeed (CodegenThingol.Classinst ((class, (tyco, arity)), (superarities, classops))));
haftmann@20896
   249
    val inst = CodegenNames.instance thy (class, tyco);
haftmann@18865
   250
  in
haftmann@18865
   251
    trns
haftmann@20896
   252
    |> tracing (fn _ => "generating instance " ^ quote class ^ " / " ^ quote tyco)
haftmann@20896
   253
    |> CodegenThingol.ensure_def defgen_inst true
haftmann@20896
   254
         ("generating instance " ^ quote class ^ " / " ^ quote tyco) inst
haftmann@18865
   255
    |> pair inst
haftmann@18865
   256
  end
haftmann@20896
   257
and ensure_def_const thy (algbr as (_, consts)) funcgr strct (c, tys) trns =
haftmann@18865
   258
  let
haftmann@20896
   259
    val c' = CodegenNames.const thy (c, tys);
haftmann@20896
   260
    fun defgen_datatypecons trns =
haftmann@20896
   261
      trns
haftmann@20896
   262
      |> ensure_def_tyco thy algbr funcgr strct
haftmann@20896
   263
          ((the o CodegenData.get_datatype_of_constr thy) (c, tys))
haftmann@20896
   264
      |-> (fn _ => succeed CodegenThingol.Bot);
haftmann@20896
   265
    fun defgen_classop trns =
haftmann@20896
   266
      trns
haftmann@20896
   267
      |> ensure_def_class thy algbr funcgr strct ((the o AxClass.class_of_param thy) c)
haftmann@20896
   268
      |-> (fn _ => succeed CodegenThingol.Bot);
haftmann@20896
   269
    fun defgen_fun trns =
haftmann@20931
   270
      case CodegenFuncgr.get_funcs funcgr
haftmann@20931
   271
        (perhaps (Consttab.lookup ((snd o snd o CodegenPackageData.get) thy)) (c, tys))
haftmann@20456
   272
       of eq_thms as eq_thm :: _ =>
haftmann@20456
   273
            let
haftmann@20456
   274
              val msg = cat_lines ("generating code for theorems " :: map string_of_thm eq_thms);
haftmann@20600
   275
              val ty = (Logic.unvarifyT o CodegenData.typ_func thy) eq_thm;
haftmann@20466
   276
              val vs = (map dest_TFree o Consts.typargs consts) (c', ty);
haftmann@20835
   277
              val dest_eqthm =
haftmann@20835
   278
                apfst (snd o strip_comb) o Logic.dest_equals o Logic.unvarify o prop_of;
haftmann@20456
   279
              fun exprgen_eq (args, rhs) trns =
haftmann@20456
   280
                trns
haftmann@20600
   281
                |> fold_map (exprgen_term thy algbr funcgr strct) args
haftmann@20600
   282
                ||>> exprgen_term thy algbr funcgr strct rhs;
haftmann@20456
   283
            in
haftmann@20456
   284
              trns
haftmann@20896
   285
              |> CodegenThingol.message msg (fn trns => trns
haftmann@20456
   286
              |> fold_map (exprgen_eq o dest_eqthm) eq_thms
haftmann@20600
   287
              ||>> fold_map (exprgen_tyvar_sort thy algbr funcgr strct) vs
haftmann@20600
   288
              ||>> exprgen_type thy algbr funcgr strct ty
haftmann@20896
   289
              |-> (fn ((eqs, vs), ty) => succeed (CodegenThingol.Fun (eqs, (vs, ty)))))
haftmann@20456
   290
            end
haftmann@20456
   291
        | [] =>
haftmann@20456
   292
              trns
haftmann@20456
   293
              |> fail ("No defining equations found for "
haftmann@20600
   294
                   ^ (quote o CodegenConsts.string_of_const thy) (c, tys));
haftmann@20896
   295
    val defgen =
haftmann@20896
   296
      if CodegenNames.has_nsp CodegenNames.nsp_fun c'
haftmann@20896
   297
      then defgen_fun
haftmann@20896
   298
      else if CodegenNames.has_nsp CodegenNames.nsp_classop c'
haftmann@20896
   299
      then defgen_classop
haftmann@20896
   300
      else if CodegenNames.has_nsp CodegenNames.nsp_dtco c'
haftmann@20896
   301
      then defgen_datatypecons
haftmann@20896
   302
      else error ("Illegal shallow name space for constant: " ^ quote c');
haftmann@20931
   303
    val strict = check_strict strct (CodegenSerializer.const_has_serialization thy) c';
haftmann@18865
   304
  in
haftmann@18865
   305
    trns
haftmann@20835
   306
    |> tracing (fn _ => "generating constant "
haftmann@20600
   307
        ^ (quote o CodegenConsts.string_of_const thy) (c, tys))
haftmann@20896
   308
    |> CodegenThingol.ensure_def defgen strict ("generating constant "
haftmann@20896
   309
         ^ CodegenConsts.string_of_const thy (c, tys)) c'
haftmann@20896
   310
    |> pair c'
haftmann@18865
   311
  end
haftmann@20896
   312
and exprgen_term thy algbr funcgr strct (Const (c, ty)) trns =
haftmann@18517
   313
      trns
haftmann@20896
   314
      |> select_appgen thy algbr funcgr strct ((c, ty), [])
haftmann@20600
   315
  | exprgen_term thy algbr funcgr strct (Var _) trns =
haftmann@20389
   316
      error "Var encountered in term during code generation"
haftmann@20600
   317
  | exprgen_term thy algbr funcgr strct (Free (v, ty)) trns =
haftmann@18516
   318
      trns
haftmann@20600
   319
      |> exprgen_type thy algbr funcgr strct ty
haftmann@20896
   320
      |-> (fn _ => pair (IVar v))
haftmann@20600
   321
  | exprgen_term thy algbr funcgr strct (Abs (raw_v, ty, raw_t)) trns =
haftmann@19136
   322
      let
haftmann@20386
   323
        val (v, t) = Syntax.variant_abs (CodegenNames.purify_var raw_v, ty, raw_t);
haftmann@19136
   324
      in
haftmann@19136
   325
        trns
haftmann@20600
   326
        |> exprgen_type thy algbr funcgr strct ty
haftmann@20600
   327
        ||>> exprgen_term thy algbr funcgr strct t
haftmann@20896
   328
        |-> (fn (ty, t) => pair ((v, ty) `|-> t))
haftmann@19136
   329
      end
haftmann@20896
   330
  | exprgen_term thy algbr funcgr strct (t as _ $ _) trns =
haftmann@20896
   331
      case strip_comb t
haftmann@20896
   332
       of (Const (c, ty), ts) =>
haftmann@18516
   333
            trns
haftmann@20896
   334
            |> select_appgen thy algbr funcgr strct ((c, ty), ts)
haftmann@20896
   335
            |-> (fn t => pair t)
haftmann@20896
   336
        | (t', ts) =>
haftmann@18516
   337
            trns
haftmann@20600
   338
            |> exprgen_term thy algbr funcgr strct t'
haftmann@20600
   339
            ||>> fold_map (exprgen_term thy algbr funcgr strct) ts
haftmann@20896
   340
            |-> (fn (t, ts) => pair (t `$$ ts))
haftmann@20600
   341
and appgen_default thy algbr funcgr strct ((c, ty), ts) trns =
haftmann@18865
   342
  trns
haftmann@20600
   343
  |> ensure_def_const thy algbr funcgr strct (CodegenConsts.norm_of_typ thy (c, ty))
haftmann@20600
   344
  ||>> exprgen_type thy algbr funcgr strct ty
haftmann@20600
   345
  ||>> exprgen_typinst_const thy algbr funcgr strct (c, ty)
haftmann@20600
   346
  ||>> fold_map (exprgen_term thy algbr funcgr strct) ts
haftmann@20896
   347
  |-> (fn (((c, ty), iss), ts) =>
haftmann@20896
   348
         pair (IConst (c, (iss, ty)) `$$ ts))
haftmann@20896
   349
and select_appgen thy algbr funcgr strct ((c, ty), ts) trns =
haftmann@20931
   350
  case Symtab.lookup (fst (CodegenPackageData.get thy)) c
haftmann@20896
   351
   of SOME (i, (appgen, _)) =>
haftmann@20105
   352
        if length ts < i then
haftmann@18865
   353
          let
haftmann@20105
   354
            val tys = Library.take (i - length ts, ((fst o strip_type) ty));
haftmann@20896
   355
            val vs = Name.names (Name.declare c Name.context) "a" tys;
haftmann@18865
   356
          in
haftmann@18865
   357
            trns
haftmann@20600
   358
            |> fold_map (exprgen_type thy algbr funcgr strct) tys
haftmann@20896
   359
            ||>> appgen thy algbr funcgr strct ((c, ty), ts @ map Free vs)
haftmann@20896
   360
            |-> (fn (tys, t) => pair (map2 (fn (v, _) => pair v) vs tys `|--> t))
haftmann@18865
   361
          end
haftmann@20105
   362
        else if length ts > i then
haftmann@18865
   363
          trns
haftmann@20896
   364
          |> appgen thy algbr funcgr strct ((c, ty), Library.take (i, ts))
haftmann@20600
   365
          ||>> fold_map (exprgen_term thy algbr funcgr strct) (Library.drop (i, ts))
haftmann@20896
   366
          |-> (fn (t, ts) => pair (t `$$ ts))
haftmann@18865
   367
        else
haftmann@18865
   368
          trns
haftmann@20896
   369
          |> appgen thy algbr funcgr strct ((c, ty), ts)
haftmann@18865
   370
    | NONE =>
haftmann@18865
   371
        trns
haftmann@20896
   372
        |> appgen_default thy algbr funcgr strct ((c, ty), ts);
haftmann@20600
   373
haftmann@20600
   374
haftmann@20835
   375
(* entrance points into extraction kernel *)
haftmann@20600
   376
haftmann@20600
   377
fun ensure_def_const' thy algbr funcgr strct c trns =
haftmann@20600
   378
  ensure_def_const thy algbr funcgr strct c trns
haftmann@20835
   379
  handle CONSTRAIN ((c, ty), ty_decl) => error (
haftmann@20600
   380
    "Constant " ^ c ^ " with most general type\n"
haftmann@20600
   381
    ^ Sign.string_of_typ thy ty
haftmann@20600
   382
    ^ "\noccurs with type\n"
haftmann@20600
   383
    ^ Sign.string_of_typ thy ty_decl);
haftmann@20600
   384
fun exprgen_term' thy algbr funcgr strct t trns =
haftmann@20600
   385
  exprgen_term thy algbr funcgr strct t trns
haftmann@20835
   386
  handle CONSTRAIN ((c, ty), ty_decl) => error ("In term " ^ (quote o Sign.string_of_term thy) t
haftmann@20600
   387
    ^ ",\nconstant " ^ c ^ " with most general type\n"
haftmann@20600
   388
    ^ Sign.string_of_typ thy ty
haftmann@20600
   389
    ^ "\noccurs with type\n"
haftmann@20600
   390
    ^ Sign.string_of_typ thy ty_decl);
haftmann@18516
   391
haftmann@18702
   392
haftmann@20439
   393
(* parametrized application generators, for instantiation in object logic *)
haftmann@20439
   394
(* (axiomatic extensions of extraction kernel *)
haftmann@18217
   395
haftmann@20600
   396
fun appgen_numeral int_of_numeral thy algbr funcgr strct (app as (c, ts)) trns =
haftmann@20485
   397
  case try (int_of_numeral thy) (list_comb (Const c, ts))
haftmann@20835
   398
   of SOME i =>
haftmann@20353
   399
        trns
haftmann@20835
   400
        |> appgen_default thy algbr funcgr strct app
haftmann@20896
   401
        |-> (fn t => pair (CodegenThingol.INum (i, t)))
haftmann@19884
   402
    | NONE =>
haftmann@19884
   403
        trns
haftmann@20835
   404
        |> appgen_default thy algbr funcgr strct app;
haftmann@18335
   405
haftmann@20600
   406
fun appgen_char char_to_index thy algbr funcgr strct (app as ((_, ty), _)) trns =
haftmann@19607
   407
  case (char_to_index o list_comb o apfst Const) app
haftmann@19607
   408
   of SOME i =>
haftmann@19607
   409
        trns
haftmann@20600
   410
        |> exprgen_type thy algbr funcgr strct ty
haftmann@20600
   411
        ||>> appgen_default thy algbr funcgr strct app
haftmann@20896
   412
        |-> (fn (_, t0) => pair (IChar (chr i, t0)))
haftmann@19607
   413
    | NONE =>
haftmann@19607
   414
        trns
haftmann@20600
   415
        |> appgen_default thy algbr funcgr strct app;
haftmann@19607
   416
haftmann@20600
   417
fun appgen_case dest_case_expr thy algbr funcgr strct (app as (c_ty, ts)) trns =
haftmann@20105
   418
  let
haftmann@20105
   419
    val SOME ([], ((st, sty), ds)) = dest_case_expr thy (list_comb (Const c_ty, ts));
haftmann@20105
   420
    fun clausegen (dt, bt) trns =
haftmann@20105
   421
      trns
haftmann@20600
   422
      |> exprgen_term thy algbr funcgr strct dt
haftmann@20600
   423
      ||>> exprgen_term thy algbr funcgr strct bt;
haftmann@20105
   424
  in
haftmann@20105
   425
    trns
haftmann@20600
   426
    |> exprgen_term thy algbr funcgr strct st
haftmann@20600
   427
    ||>> exprgen_type thy algbr funcgr strct sty
haftmann@20105
   428
    ||>> fold_map clausegen ds
haftmann@20600
   429
    ||>> appgen_default thy algbr funcgr strct app
haftmann@20105
   430
    |-> (fn (((se, sty), ds), e0) => pair (ICase (((se, sty), ds), e0)))
haftmann@20105
   431
  end;
haftmann@20105
   432
haftmann@20600
   433
fun appgen_let thy algbr funcgr strct (app as (_, [st, ct])) trns =
haftmann@20105
   434
  trns
haftmann@20600
   435
  |> exprgen_term thy algbr funcgr strct ct
haftmann@20600
   436
  ||>> exprgen_term thy algbr funcgr strct st
haftmann@20600
   437
  ||>> appgen_default thy algbr funcgr strct app
haftmann@20105
   438
  |-> (fn (((v, ty) `|-> be, se), e0) =>
haftmann@20105
   439
            pair (ICase (((se, ty), case be
haftmann@20105
   440
              of ICase (((IVar w, _), ds), _) => if v = w then ds else [(IVar v, be)]
haftmann@20105
   441
               | _ => [(IVar v, be)]
haftmann@20105
   442
            ), e0))
haftmann@20105
   443
        | (_, e0) => pair e0);
haftmann@20105
   444
haftmann@20439
   445
fun add_appconst (c, appgen) thy =
haftmann@20439
   446
  let
haftmann@20931
   447
    val i = (length o fst o strip_type o Sign.the_const_type thy) c;
haftmann@20931
   448
    val _ = Code.change thy (K CodegenThingol.empty_code);
haftmann@20931
   449
  in
haftmann@20931
   450
    (CodegenPackageData.map o apfst)
haftmann@20931
   451
      (Symtab.update (c, (i, (appgen, stamp ())))) thy
haftmann@20931
   452
  end;
haftmann@20931
   453
haftmann@20931
   454
haftmann@20931
   455
haftmann@20931
   456
(** abstype and constsubst interface **)
haftmann@20931
   457
haftmann@20931
   458
fun gen_abstyp prep_const prep_typ (raw_abstyp, raw_substtyp) raw_absconsts thy =
haftmann@20931
   459
  let
haftmann@20931
   460
    val abstyp = Type.no_tvars (prep_typ thy raw_abstyp);
haftmann@20931
   461
    val substtyp = Type.no_tvars (prep_typ thy raw_substtyp);
haftmann@20931
   462
    val absconsts = (map o pairself) (prep_const thy) raw_absconsts;
haftmann@20931
   463
    val Type (abstyco, tys) = abstyp handle BIND => error ("bad type: " ^ Sign.string_of_typ thy abstyp);
haftmann@20931
   464
    val typarms = map (fst o dest_TFree) tys handle MATCH => error ("bad type: " ^ Sign.string_of_typ thy abstyp);
haftmann@20931
   465
    fun mk_index v = 
haftmann@20931
   466
      let
haftmann@20931
   467
        val k = find_index (fn w => v = w) typarms;
haftmann@20931
   468
      in if k = ~1
haftmann@20931
   469
        then error ("free type variable: " ^ quote v)
haftmann@20931
   470
        else TFree (string_of_int k, [])
haftmann@20931
   471
      end;
haftmann@20931
   472
    val typpat = map_atyps (fn TFree (v, _) => mk_index v) substtyp;
haftmann@20931
   473
    fun apply_typpat (Type (tyco, tys)) =
haftmann@20931
   474
          let
haftmann@20931
   475
            val tys' = map apply_typpat tys;
haftmann@20931
   476
          in if tyco = abstyco then
haftmann@20931
   477
            (map_atyps (fn TFree (n, _) => nth tys' (the (Int.fromString n)))) typpat
haftmann@20931
   478
          else
haftmann@20931
   479
            Type (tyco, tys')
haftmann@20931
   480
          end
haftmann@20931
   481
      | apply_typpat ty = ty;
haftmann@20931
   482
    val string_of_typ = setmp show_sorts true (Sign.string_of_typ thy);
haftmann@20931
   483
    fun add_consts (c1, c2) =
haftmann@20931
   484
      let
haftmann@20931
   485
        val _ = if CodegenNames.has_nsp CodegenNames.nsp_fun (CodegenNames.const thy c2)
haftmann@20931
   486
          then ()
haftmann@20931
   487
          else error ("not a function: " ^ CodegenConsts.string_of_const thy c2);
haftmann@20931
   488
        val funcgr = CodegenFuncgr.mk_funcgr thy [c1, c2] [];
haftmann@20931
   489
        val ty_map = CodegenFuncgr.get_func_typs funcgr;
haftmann@20931
   490
        val ty1 = (apply_typpat o the o AList.lookup CodegenConsts.eq_const ty_map) c1;
haftmann@20931
   491
        val ty2 = (the o AList.lookup CodegenConsts.eq_const ty_map) c2;
haftmann@20931
   492
        val _ = if Sign.typ_equiv thy (ty1, ty2) then () else
haftmann@20931
   493
          error ("Incompatiable type signatures of " ^ CodegenConsts.string_of_const thy c1
haftmann@20931
   494
            ^ " and " ^ CodegenConsts.string_of_const thy c2 ^ ":\n"
haftmann@20931
   495
            ^ string_of_typ ty1 ^ "\n" ^ string_of_typ ty2);
haftmann@20931
   496
      in Consttab.update (c1, c2) end;
haftmann@20931
   497
    val _ = Code.change thy (K CodegenThingol.empty_code);
haftmann@20931
   498
  in
haftmann@20931
   499
    thy
haftmann@20931
   500
    |> (CodegenPackageData.map o apsnd) (fn (abstypes, abscs) =>
haftmann@20931
   501
          (abstypes
haftmann@20931
   502
          |> Symtab.update (abstyco, typpat),
haftmann@20931
   503
          abscs
haftmann@20931
   504
          |> fold add_consts absconsts)
haftmann@20931
   505
       )
haftmann@20931
   506
  end;
haftmann@20931
   507
haftmann@20931
   508
fun gen_constsubst prep_const raw_constsubsts thy =
haftmann@20931
   509
  let
haftmann@20931
   510
    val constsubsts = (map o pairself) (prep_const thy) raw_constsubsts;
haftmann@20931
   511
    val string_of_typ = setmp show_sorts true (Sign.string_of_typ thy);
haftmann@20931
   512
    fun add_consts (c1, c2) =
haftmann@20931
   513
      let
haftmann@20931
   514
        val _ = if CodegenNames.has_nsp CodegenNames.nsp_fun (CodegenNames.const thy c2)
haftmann@20931
   515
          then ()
haftmann@20931
   516
          else error ("not a function: " ^ CodegenConsts.string_of_const thy c2);
haftmann@20931
   517
        val funcgr = CodegenFuncgr.mk_funcgr thy [c1, c2] [];
haftmann@20931
   518
        val ty_map = CodegenFuncgr.get_func_typs funcgr;
haftmann@20931
   519
        val ty1 = (the o AList.lookup CodegenConsts.eq_const ty_map) c1;
haftmann@20931
   520
        val ty2 = (the o AList.lookup CodegenConsts.eq_const ty_map) c2;
haftmann@20931
   521
        val _ = if Sign.typ_equiv thy (ty1, ty2) then () else
haftmann@20931
   522
          error ("Incompatiable type signatures of " ^ CodegenConsts.string_of_const thy c1
haftmann@20931
   523
            ^ " and " ^ CodegenConsts.string_of_const thy c2 ^ ":\n"
haftmann@20931
   524
            ^ string_of_typ ty1 ^ "\n" ^ string_of_typ ty2);
haftmann@20931
   525
      in Consttab.update (c1, c2) end;
haftmann@20931
   526
    val _ = Code.change thy (K CodegenThingol.empty_code);
haftmann@20931
   527
  in
haftmann@20931
   528
    thy
haftmann@20931
   529
    |> (CodegenPackageData.map o apsnd o apsnd) (fold add_consts constsubsts)
haftmann@20931
   530
  end;
haftmann@20931
   531
haftmann@20931
   532
val abstyp = gen_abstyp CodegenConsts.norm Sign.certify_typ;
haftmann@20931
   533
val abstyp_e = gen_abstyp CodegenConsts.read_const (fn thy => Sign.read_typ (thy, K NONE));
haftmann@20931
   534
haftmann@20931
   535
val constsubst = gen_constsubst CodegenConsts.norm;
haftmann@20931
   536
val constsubst_e = gen_constsubst CodegenConsts.read_const;
haftmann@18217
   537
haftmann@18516
   538
haftmann@18217
   539
haftmann@20439
   540
(** code generation interfaces **)
haftmann@18217
   541
haftmann@20600
   542
fun generate thy (cs, rhss) targets init gen it =
haftmann@20466
   543
  let
haftmann@20931
   544
    val raw_funcgr = CodegenFuncgr.mk_funcgr thy cs rhss;
haftmann@20931
   545
    val cs' = map_filter (Consttab.lookup ((snd o snd o CodegenPackageData.get) thy))
haftmann@20931
   546
      (CodegenFuncgr.Constgraph.keys raw_funcgr);
haftmann@20931
   547
    val funcgr = CodegenFuncgr.mk_funcgr thy cs' [];
haftmann@20931
   548
    val qnaming = NameSpace.qualified_names NameSpace.default_naming;
haftmann@20466
   549
    val algebr = ClassPackage.operational_algebra thy;
haftmann@20466
   550
    val consttab = Consts.empty
haftmann@20466
   551
      |> fold (fn (c, ty) => Consts.declare qnaming
haftmann@20699
   552
           ((CodegenNames.const thy c, ty), true))
haftmann@20931
   553
           (CodegenFuncgr.get_func_typs funcgr);
haftmann@20466
   554
    val algbr = (algebr, consttab);
haftmann@20466
   555
  in   
haftmann@20896
   556
    Code.change_yield thy (CodegenThingol.start_transact init (gen thy algbr funcgr
haftmann@20600
   557
        (true, targets) it))
haftmann@20600
   558
    |> (fn (x, modl) => x)
haftmann@20466
   559
  end;
haftmann@18516
   560
haftmann@20600
   561
fun codegen_term thy t =
haftmann@20353
   562
  let
haftmann@20835
   563
    fun const_typ (c, ty) =
haftmann@20835
   564
      let
haftmann@20835
   565
        val const = CodegenConsts.norm_of_typ thy (c, ty);
haftmann@20835
   566
        val funcgr = CodegenFuncgr.mk_funcgr thy [const] [];
haftmann@20835
   567
      in case CodegenFuncgr.get_funcs funcgr const
haftmann@20835
   568
       of (thm :: _) => CodegenData.typ_func thy thm
haftmann@20835
   569
        | [] => Sign.the_const_type thy c
haftmann@20835
   570
      end;
haftmann@20600
   571
    val ct = Thm.cterm_of thy t;
haftmann@20835
   572
    val (thm, ct') = CodegenData.preprocess_cterm thy
haftmann@20835
   573
      (const_typ) ct;
haftmann@20835
   574
    val t' = Thm.term_of ct';
haftmann@20699
   575
    val cs_rhss = CodegenConsts.consts_of thy t';
haftmann@20353
   576
  in
haftmann@20600
   577
    (thm, generate thy cs_rhss (SOME []) NONE exprgen_term' t')
haftmann@20353
   578
  end;
haftmann@19136
   579
haftmann@20699
   580
fun const_of_idf thy =
haftmann@20699
   581
  CodegenConsts.typ_of_inst thy o the o CodegenNames.const_rev thy;
haftmann@19150
   582
haftmann@19967
   583
fun get_root_module thy =
haftmann@20600
   584
  Code.get thy;
haftmann@19042
   585
haftmann@20600
   586
fun eval_term thy (ref_spec, t) =
haftmann@20213
   587
  let
haftmann@20401
   588
    val _ = Term.fold_atyps (fn _ =>
haftmann@20401
   589
      error ("Term" ^ Sign.string_of_term thy t ^ "is polymorhpic"))
haftmann@20401
   590
      (Term.fastype_of t);
haftmann@20835
   591
    val (_, t') = codegen_term thy t;
haftmann@20213
   592
  in
haftmann@20699
   593
    CodegenSerializer.eval_term thy (ref_spec, t') (Code.get thy)
haftmann@20213
   594
  end;
haftmann@20213
   595
haftmann@18516
   596
haftmann@19884
   597
haftmann@20439
   598
(** toplevel interface and setup **)
haftmann@18217
   599
haftmann@18756
   600
local
haftmann@19150
   601
haftmann@20699
   602
structure P = OuterParse
haftmann@20699
   603
and K = OuterKeyword
haftmann@20699
   604
haftmann@20439
   605
fun code raw_cs seris thy =
haftmann@18217
   606
  let
haftmann@20600
   607
    val cs = map (CodegenConsts.read_const thy) raw_cs;
haftmann@20456
   608
    val targets = case map fst seris
haftmann@20456
   609
     of [] => NONE
haftmann@20456
   610
      | xs => SOME xs;
haftmann@20896
   611
    val seris' = map_filter (fn (target, args as _ :: _) =>
haftmann@20896
   612
      SOME (CodegenSerializer.get_serializer thy (target, args)) | _ => NONE) seris;
haftmann@20439
   613
    fun generate' thy = case cs
haftmann@20600
   614
     of [] => []
haftmann@20439
   615
      | _ =>
haftmann@20600
   616
          generate thy (cs, []) targets NONE (fold_map oooo ensure_def_const') cs;
haftmann@20896
   617
    fun serialize' [] code seri =
haftmann@20896
   618
          seri NONE code 
haftmann@20896
   619
      | serialize' cs code seri =
haftmann@20896
   620
          seri (SOME cs) code;
haftmann@20600
   621
    val cs = generate' thy;
haftmann@20699
   622
    val code = Code.get thy;
haftmann@18217
   623
  in
haftmann@20699
   624
    (map (serialize' cs code) seris'; ())
haftmann@18217
   625
  end;
haftmann@18217
   626
haftmann@20931
   627
val (codeK, code_abstypeK, code_constsubstK) =
haftmann@20931
   628
  ("code_gen", "code_abstype", "code_constsubst");
haftmann@20699
   629
haftmann@18217
   630
in
haftmann@18217
   631
haftmann@20439
   632
val codeP =
haftmann@20835
   633
  OuterSyntax.improper_command codeK "generate and serialize executable code for constants" K.diag (
haftmann@20439
   634
    Scan.repeat P.term
haftmann@20439
   635
    -- Scan.repeat (P.$$$ "(" |--
haftmann@20896
   636
        P.name -- P.arguments
haftmann@20439
   637
        --| P.$$$ ")")
haftmann@20600
   638
    >> (fn (raw_cs, seris) => Toplevel.keep (code raw_cs seris o Toplevel.theory_of))
haftmann@20439
   639
  );
haftmann@20439
   640
haftmann@20931
   641
val code_abstypeP =
haftmann@20931
   642
  OuterSyntax.command code_abstypeK "axiomatic abstypes for code generation" K.thy_decl (
haftmann@20931
   643
    (P.typ -- P.typ -- Scan.optional (P.$$$ "where" |-- Scan.repeat1
haftmann@20931
   644
        (P.term --| (P.$$$ "\\<equiv>" || P.$$$ "==") -- P.term)) [])
haftmann@20931
   645
    >> (Toplevel.theory o uncurry abstyp_e)
haftmann@18865
   646
  );
haftmann@18865
   647
haftmann@20931
   648
val code_constsubstP =
haftmann@20931
   649
  OuterSyntax.command code_constsubstK "axiomatic constant substitutions for code generation" K.thy_decl (
haftmann@20931
   650
    Scan.repeat1 (P.term --| (P.$$$ "\\<equiv>" || P.$$$ "==") -- P.term)
haftmann@20931
   651
    >> (Toplevel.theory o constsubst_e)
haftmann@20428
   652
  );
haftmann@20428
   653
haftmann@20931
   654
val _ = OuterSyntax.add_parsers [codeP, code_abstypeP, code_constsubstP];
haftmann@18217
   655
haftmann@18217
   656
end; (* local *)
haftmann@18217
   657
haftmann@18217
   658
end; (* struct *)