src/Pure/Isar/code.ML
author haftmann
Mon Jan 11 16:45:02 2010 +0100 (2010-01-11 ago)
changeset 34874 89c230bf8feb
parent 34272 95df5e6dd41c
child 34891 99b9a6290446
permissions -rw-r--r--
added code certificates
haftmann@24219
     1
(*  Title:      Pure/Isar/code.ML
haftmann@24219
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@24219
     3
haftmann@34173
     4
Abstract executable ingredients of theory.  Management of data
haftmann@34173
     5
dependent on executable ingredients as synchronized cache; purged
haftmann@34173
     6
on any change of underlying executable ingredients.
haftmann@24219
     7
*)
haftmann@24219
     8
haftmann@24219
     9
signature CODE =
haftmann@24219
    10
sig
haftmann@31957
    11
  (*constants*)
haftmann@31957
    12
  val check_const: theory -> term -> string
haftmann@31957
    13
  val read_bare_const: theory -> string -> string * typ
haftmann@31957
    14
  val read_const: theory -> string -> string
haftmann@31962
    15
  val string_of_const: theory -> string -> string
haftmann@33940
    16
  val cert_signature: theory -> typ -> typ
haftmann@33940
    17
  val read_signature: theory -> string -> typ
haftmann@33940
    18
  val const_typ: theory -> string -> typ
haftmann@33940
    19
  val subst_signatures: theory -> term -> term
haftmann@31962
    20
  val args_number: theory -> string -> int
haftmann@31957
    21
haftmann@31156
    22
  (*constructor sets*)
haftmann@31156
    23
  val constrset_of_consts: theory -> (string * typ) list
haftmann@31156
    24
    -> string * ((string * sort) list * (string * typ list) list)
haftmann@31156
    25
haftmann@34874
    26
  (*code equations and certificates*)
haftmann@31962
    27
  val mk_eqn: theory -> thm * bool -> thm * bool
haftmann@31962
    28
  val mk_eqn_warning: theory -> thm -> (thm * bool) option
haftmann@31962
    29
  val mk_eqn_liberal: theory -> thm -> (thm * bool) option
haftmann@31156
    30
  val assert_eqn: theory -> thm * bool -> thm * bool
haftmann@31156
    31
  val assert_eqns_const: theory -> string
haftmann@31156
    32
    -> (thm * bool) list -> (thm * bool) list
haftmann@31957
    33
  val const_typ_eqn: theory -> thm -> string * typ
haftmann@31156
    34
  val typscheme_eqn: theory -> thm -> (string * sort) list * typ
haftmann@32873
    35
  val typscheme_eqns: theory -> string -> thm list -> (string * sort) list * typ
haftmann@32929
    36
  val standard_typscheme: theory -> thm list -> thm list
haftmann@34874
    37
  type cert = thm * bool list
haftmann@34874
    38
  val cert_of_eqns: theory -> (thm * bool) list -> cert
haftmann@34874
    39
  val constrain_cert: theory -> sort list -> cert -> cert
haftmann@34874
    40
  val dest_cert: theory -> cert -> (string * ((string * sort) list * typ)) * ((term list * term) * bool) list
haftmann@34874
    41
  val eqns_of_cert: theory -> cert -> (thm * bool) list
haftmann@31156
    42
haftmann@31962
    43
  (*executable code*)
haftmann@33940
    44
  val add_type: string -> theory -> theory
haftmann@33940
    45
  val add_type_cmd: string -> theory -> theory
haftmann@33940
    46
  val add_signature: string * typ -> theory -> theory
haftmann@33940
    47
  val add_signature_cmd: string * string -> theory -> theory
haftmann@31156
    48
  val add_datatype: (string * typ) list -> theory -> theory
haftmann@31156
    49
  val add_datatype_cmd: string list -> theory -> theory
haftmann@31156
    50
  val type_interpretation:
haftmann@31156
    51
    (string * ((string * sort) list * (string * typ list) list)
haftmann@31156
    52
      -> theory -> theory) -> theory -> theory
haftmann@28368
    53
  val add_eqn: thm -> theory -> theory
haftmann@31088
    54
  val add_nbe_eqn: thm -> theory -> theory
haftmann@28368
    55
  val add_default_eqn: thm -> theory -> theory
haftmann@28703
    56
  val add_default_eqn_attribute: attribute
haftmann@28703
    57
  val add_default_eqn_attrib: Attrib.src
haftmann@28368
    58
  val del_eqn: thm -> theory -> theory
haftmann@28368
    59
  val del_eqns: string -> theory -> theory
haftmann@24844
    60
  val add_case: thm -> theory -> theory
haftmann@24844
    61
  val add_undefined: string -> theory -> theory
haftmann@24219
    62
  val get_datatype: theory -> string -> ((string * sort) list * (string * typ list) list)
haftmann@24423
    63
  val get_datatype_of_constr: theory -> string -> string option
haftmann@31156
    64
  val these_eqns: theory -> string -> (thm * bool) list
haftmann@34874
    65
  val eqn_cert: theory -> string -> cert
haftmann@30023
    66
  val get_case_scheme: theory -> string -> (int * (int * string list)) option
haftmann@31890
    67
  val undefineds: theory -> string list
haftmann@24219
    68
  val print_codesetup: theory -> unit
haftmann@31957
    69
haftmann@31957
    70
  (*infrastructure*)
haftmann@31998
    71
  val set_code_target_attr: (string -> thm -> theory -> theory) -> theory -> theory
haftmann@31957
    72
  val purge_data: theory -> theory
haftmann@24219
    73
end;
haftmann@24219
    74
haftmann@24219
    75
signature CODE_DATA_ARGS =
haftmann@24219
    76
sig
haftmann@24219
    77
  type T
haftmann@24219
    78
  val empty: T
haftmann@24219
    79
end;
haftmann@24219
    80
haftmann@24219
    81
signature CODE_DATA =
haftmann@24219
    82
sig
haftmann@24219
    83
  type T
haftmann@34251
    84
  val change: theory -> (T -> T) -> T
haftmann@34251
    85
  val change_yield: theory -> (T -> 'a * T) -> 'a * T
haftmann@24219
    86
end;
haftmann@24219
    87
haftmann@24219
    88
signature PRIVATE_CODE =
haftmann@24219
    89
sig
haftmann@24219
    90
  include CODE
haftmann@34173
    91
  val declare_data: Object.T -> serial
haftmann@24219
    92
  val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
haftmann@34251
    93
    -> theory -> ('a -> 'a) -> 'a
haftmann@24219
    94
  val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
haftmann@34251
    95
    -> theory -> ('a -> 'b * 'a) -> 'b * 'a
haftmann@24219
    96
end;
haftmann@24219
    97
haftmann@24219
    98
structure Code : PRIVATE_CODE =
haftmann@24219
    99
struct
haftmann@24219
   100
haftmann@31962
   101
(** auxiliary **)
haftmann@31962
   102
haftmann@31962
   103
(* printing *)
haftmann@31156
   104
wenzelm@32966
   105
fun string_of_typ thy = setmp_CRITICAL show_sorts true (Syntax.string_of_typ_global thy);
haftmann@31962
   106
haftmann@31156
   107
fun string_of_const thy c = case AxClass.inst_of_param thy c
haftmann@31156
   108
 of SOME (c, tyco) => Sign.extern_const thy c ^ " " ^ enclose "[" "]" (Sign.extern_type thy tyco)
haftmann@31156
   109
  | NONE => Sign.extern_const thy c;
haftmann@31156
   110
haftmann@31962
   111
haftmann@31962
   112
(* constants *)
haftmann@31156
   113
haftmann@33940
   114
fun typ_equiv tys = Type.raw_instance tys andalso Type.raw_instance (swap tys);
haftmann@33940
   115
haftmann@31962
   116
fun check_bare_const thy t = case try dest_Const t
haftmann@31962
   117
 of SOME c_ty => c_ty
haftmann@31962
   118
  | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
haftmann@31156
   119
haftmann@31962
   120
fun check_const thy = AxClass.unoverload_const thy o check_bare_const thy;
haftmann@31962
   121
haftmann@31962
   122
fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
haftmann@31962
   123
haftmann@31962
   124
fun read_const thy = AxClass.unoverload_const thy o read_bare_const thy;
haftmann@31156
   125
haftmann@32872
   126
haftmann@31962
   127
haftmann@31962
   128
(** data store **)
haftmann@31962
   129
haftmann@31962
   130
(* code equations *)
haftmann@31962
   131
haftmann@33006
   132
type eqns = bool * (thm * bool) list;
haftmann@33006
   133
  (*default flag, theorems with proper flag *)
haftmann@31962
   134
haftmann@31962
   135
fun add_drop_redundant thy (thm, proper) thms =
haftmann@31962
   136
  let
haftmann@31962
   137
    val args_of = snd o strip_comb o map_types Type.strip_sorts
haftmann@31962
   138
      o fst o Logic.dest_equals o Thm.plain_prop_of;
haftmann@31962
   139
    val args = args_of thm;
haftmann@31962
   140
    val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
haftmann@31962
   141
    fun matches_args args' = length args <= length args' andalso
haftmann@33957
   142
      Pattern.matchess thy (args, (map incr_idx o take (length args)) args');
haftmann@31962
   143
    fun drop (thm', proper') = if (proper orelse not proper')
haftmann@31962
   144
      andalso matches_args (args_of thm') then 
wenzelm@32091
   145
        (warning ("Code generator: dropping redundant code equation\n" ^
wenzelm@32091
   146
            Display.string_of_thm_global thy thm'); true)
haftmann@31962
   147
      else false;
haftmann@31962
   148
  in (thm, proper) :: filter_out drop thms end;
haftmann@31962
   149
haftmann@33006
   150
fun add_thm thy _ thm (false, thms) = (false, add_drop_redundant thy thm thms)
haftmann@33006
   151
  | add_thm thy true thm (true, thms) = (true, thms @ [thm])
haftmann@33006
   152
  | add_thm thy false thm (true, thms) = (false, [thm]);
haftmann@31962
   153
haftmann@33006
   154
fun del_thm thm = apsnd (remove (eq_fst Thm.eq_thm_prop) (thm, true));
haftmann@31962
   155
haftmann@31962
   156
haftmann@31962
   157
(* executable code data *)
haftmann@31962
   158
haftmann@31962
   159
datatype spec = Spec of {
haftmann@31962
   160
  history_concluded: bool,
haftmann@33940
   161
  signatures: int Symtab.table * typ Symtab.table,
haftmann@31962
   162
  eqns: ((bool * eqns) * (serial * eqns) list) Symtab.table
haftmann@31962
   163
    (*with explicit history*),
haftmann@31962
   164
  dtyps: ((serial * ((string * sort) list * (string * typ list) list)) list) Symtab.table
haftmann@31962
   165
    (*with explicit history*),
haftmann@31962
   166
  cases: (int * (int * string list)) Symtab.table * unit Symtab.table
haftmann@31962
   167
};
haftmann@31962
   168
haftmann@33940
   169
fun make_spec (history_concluded, ((signatures, eqns), (dtyps, cases))) =
haftmann@33940
   170
  Spec { history_concluded = history_concluded,
haftmann@33940
   171
    signatures = signatures, eqns = eqns, dtyps = dtyps, cases = cases };
haftmann@33940
   172
fun map_spec f (Spec { history_concluded = history_concluded, signatures = signatures,
haftmann@33940
   173
  eqns = eqns, dtyps = dtyps, cases = cases }) =
haftmann@33940
   174
  make_spec (f (history_concluded, ((signatures, eqns), (dtyps, cases))));
haftmann@33940
   175
fun merge_spec (Spec { history_concluded = _, signatures = (tycos1, sigs1), eqns = eqns1,
haftmann@31962
   176
    dtyps = dtyps1, cases = (cases1, undefs1) },
haftmann@33940
   177
  Spec { history_concluded = _, signatures = (tycos2, sigs2), eqns = eqns2,
haftmann@31962
   178
    dtyps = dtyps2, cases = (cases2, undefs2) }) =
haftmann@31156
   179
  let
haftmann@33940
   180
    val signatures = (Symtab.merge (op =) (tycos1, tycos2),
haftmann@33940
   181
      Symtab.merge typ_equiv (sigs1, sigs2));
haftmann@31962
   182
    fun merge_eqns ((_, history1), (_, history2)) =
haftmann@31962
   183
      let
haftmann@31962
   184
        val raw_history = AList.merge (op = : serial * serial -> bool)
haftmann@31962
   185
          (K true) (history1, history2)
haftmann@31962
   186
        val filtered_history = filter_out (fst o snd) raw_history
haftmann@31962
   187
        val history = if null filtered_history
haftmann@31962
   188
          then raw_history else filtered_history;
haftmann@31962
   189
      in ((false, (snd o hd) history), history) end;
haftmann@31962
   190
    val eqns = Symtab.join (K merge_eqns) (eqns1, eqns2);
haftmann@31962
   191
    val dtyps = Symtab.join (K (AList.merge (op =) (K true))) (dtyps1, dtyps2);
haftmann@31962
   192
    val cases = (Symtab.merge (K true) (cases1, cases2),
haftmann@31962
   193
      Symtab.merge (K true) (undefs1, undefs2));
haftmann@33940
   194
  in make_spec (false, ((signatures, eqns), (dtyps, cases))) end;
haftmann@31962
   195
haftmann@31962
   196
fun history_concluded (Spec { history_concluded, ... }) = history_concluded;
haftmann@33940
   197
fun the_signatures (Spec { signatures, ... }) = signatures;
haftmann@31962
   198
fun the_eqns (Spec { eqns, ... }) = eqns;
haftmann@31962
   199
fun the_dtyps (Spec { dtyps, ... }) = dtyps;
haftmann@31962
   200
fun the_cases (Spec { cases, ... }) = cases;
haftmann@32544
   201
val map_history_concluded = map_spec o apfst;
haftmann@33940
   202
val map_signatures = map_spec o apsnd o apfst o apfst;
haftmann@33940
   203
val map_eqns = map_spec o apsnd o apfst o apsnd;
haftmann@31962
   204
val map_dtyps = map_spec o apsnd o apsnd o apfst;
haftmann@31962
   205
val map_cases = map_spec o apsnd o apsnd o apsnd;
haftmann@31962
   206
haftmann@31962
   207
haftmann@31962
   208
(* data slots dependent on executable code *)
haftmann@31962
   209
haftmann@31962
   210
(*private copy avoids potential conflict of table exceptions*)
wenzelm@31971
   211
structure Datatab = Table(type key = int val ord = int_ord);
haftmann@31962
   212
haftmann@31962
   213
local
haftmann@31962
   214
haftmann@34173
   215
type kind = { empty: Object.T };
haftmann@31962
   216
wenzelm@32738
   217
val kinds = Unsynchronized.ref (Datatab.empty: kind Datatab.table);
haftmann@31962
   218
haftmann@31962
   219
fun invoke f k = case Datatab.lookup (! kinds) k
haftmann@31962
   220
 of SOME kind => f kind
haftmann@31962
   221
  | NONE => sys_error "Invalid code data identifier";
haftmann@31962
   222
haftmann@31962
   223
in
haftmann@31962
   224
haftmann@34173
   225
fun declare_data empty =
haftmann@31962
   226
  let
haftmann@31962
   227
    val k = serial ();
haftmann@34173
   228
    val kind = { empty = empty };
haftmann@34173
   229
    val _ = CRITICAL (fn () => Unsynchronized.change kinds (Datatab.update (k, kind)));
haftmann@31962
   230
  in k end;
haftmann@31962
   231
haftmann@31962
   232
fun invoke_init k = invoke (fn kind => #empty kind) k;
haftmann@31962
   233
haftmann@31962
   234
end; (*local*)
haftmann@31962
   235
haftmann@31962
   236
haftmann@31962
   237
(* theory store *)
haftmann@31962
   238
haftmann@31962
   239
local
haftmann@31962
   240
haftmann@31962
   241
type data = Object.T Datatab.table;
haftmann@34244
   242
fun empty_dataref () = Synchronized.var "code data" (NONE : (data * theory_ref) option);
haftmann@31962
   243
haftmann@34244
   244
structure Code_Data = Theory_Data
haftmann@31962
   245
(
haftmann@34244
   246
  type T = spec * (data * theory_ref) option Synchronized.var;
haftmann@33940
   247
  val empty = (make_spec (false, (((Symtab.empty, Symtab.empty), Symtab.empty),
haftmann@34244
   248
    (Symtab.empty, (Symtab.empty, Symtab.empty)))), empty_dataref ());
haftmann@34244
   249
  val extend = I
haftmann@34244
   250
  fun merge ((spec1, _), (spec2, _)) =
haftmann@34244
   251
    (merge_spec (spec1, spec2), empty_dataref ());
haftmann@31962
   252
);
haftmann@31962
   253
haftmann@31962
   254
in
haftmann@31962
   255
haftmann@31962
   256
(* access to executable code *)
haftmann@31962
   257
haftmann@31962
   258
val the_exec = fst o Code_Data.get;
haftmann@31962
   259
haftmann@34244
   260
fun map_exec_purge f = Code_Data.map (fn (exec, _) => (f exec, empty_dataref ()));
haftmann@31962
   261
haftmann@34244
   262
val purge_data = (Code_Data.map o apsnd) (fn _ => empty_dataref ());
haftmann@31962
   263
haftmann@34173
   264
fun change_eqns delete c f = (map_exec_purge o map_eqns
haftmann@33006
   265
  o (if delete then Symtab.map_entry c else Symtab.map_default (c, ((false, (true, [])), [])))
haftmann@31962
   266
    o apfst) (fn (_, eqns) => (true, f eqns));
haftmann@31962
   267
haftmann@31962
   268
haftmann@31962
   269
(* tackling equation history *)
haftmann@31962
   270
haftmann@31962
   271
fun continue_history thy = if (history_concluded o the_exec) thy
haftmann@31962
   272
  then thy
haftmann@31962
   273
    |> (Code_Data.map o apfst o map_history_concluded) (K false)
haftmann@31962
   274
    |> SOME
haftmann@31962
   275
  else NONE;
haftmann@31962
   276
haftmann@31962
   277
fun conclude_history thy = if (history_concluded o the_exec) thy
haftmann@31962
   278
  then NONE
haftmann@31962
   279
  else thy
haftmann@31962
   280
    |> (Code_Data.map o apfst)
haftmann@31962
   281
        ((map_eqns o Symtab.map) (fn ((changed, current), history) =>
haftmann@31962
   282
          ((false, current),
haftmann@31962
   283
            if changed then (serial (), current) :: history else history))
haftmann@31962
   284
        #> map_history_concluded (K true))
haftmann@31962
   285
    |> SOME;
haftmann@31962
   286
haftmann@34244
   287
val _ = Context.>> (Context.map_theory (Theory.at_begin continue_history #> Theory.at_end conclude_history));
haftmann@31962
   288
haftmann@31962
   289
haftmann@31962
   290
(* access to data dependent on abstract executable code *)
haftmann@31962
   291
haftmann@34244
   292
fun change_yield_data (kind, mk, dest) theory f =
haftmann@31962
   293
  let
haftmann@34244
   294
    val dataref = (snd o Code_Data.get) theory;
haftmann@34251
   295
    val (datatab, thy_ref) = case Synchronized.value dataref
haftmann@34251
   296
     of SOME (datatab, thy_ref) => if Theory.eq_thy (theory, Theory.deref thy_ref)
haftmann@34251
   297
          then (datatab, thy_ref)
haftmann@34251
   298
          else (Datatab.empty, Theory.check_thy theory)
haftmann@34251
   299
      | NONE => (Datatab.empty, Theory.check_thy theory)
haftmann@34244
   300
    val data = case Datatab.lookup datatab kind
haftmann@34244
   301
     of SOME data => data
haftmann@34244
   302
      | NONE => invoke_init kind;
haftmann@34251
   303
    val result as (x, data') = f (dest data);
haftmann@34244
   304
    val _ = Synchronized.change dataref
haftmann@34244
   305
      ((K o SOME) (Datatab.update (kind, mk data') datatab, thy_ref));
haftmann@34244
   306
  in result end;
haftmann@31962
   307
haftmann@34251
   308
fun change_data ops theory f = change_yield_data ops theory (f #> pair ()) |> snd;
haftmann@31962
   309
haftmann@31962
   310
end; (*local*)
haftmann@31962
   311
haftmann@31962
   312
haftmann@31962
   313
(** foundation **)
haftmann@31962
   314
haftmann@31962
   315
(* constants *)
haftmann@31962
   316
haftmann@33940
   317
fun arity_number thy tyco = case Symtab.lookup ((fst o the_signatures o the_exec) thy) tyco
haftmann@33940
   318
 of SOME n => n
haftmann@33940
   319
  | NONE => Sign.arity_number thy tyco;
haftmann@33940
   320
haftmann@33940
   321
fun build_tsig thy =
haftmann@33940
   322
  let
haftmann@33940
   323
    val (tycos, _) = (the_signatures o the_exec) thy;
haftmann@33940
   324
    val decls = (#types o Type.rep_tsig o Sign.tsig_of) thy
haftmann@34272
   325
      |> snd 
haftmann@34272
   326
      |> Symtab.fold (fn (tyco, n) =>
haftmann@34272
   327
          Symtab.update (tyco, Type.LogicalType n)) tycos;
haftmann@34272
   328
  in
haftmann@34272
   329
    Type.empty_tsig
haftmann@34272
   330
    |> Symtab.fold (fn (tyco, Type.LogicalType n) => Type.add_type Name_Space.default_naming
haftmann@34272
   331
        (Binding.qualified_name tyco, n) | _ => I) decls
haftmann@34272
   332
  end;
haftmann@33940
   333
haftmann@33940
   334
fun cert_signature thy = Logic.varifyT o Type.cert_typ (build_tsig thy) o Type.no_tvars;
haftmann@33940
   335
haftmann@33940
   336
fun read_signature thy = cert_signature thy o Type.strip_sorts
haftmann@33940
   337
  o Syntax.parse_typ (ProofContext.init thy);
haftmann@33940
   338
haftmann@33940
   339
fun expand_signature thy = Type.cert_typ_mode Type.mode_syntax (Sign.tsig_of thy);
haftmann@33940
   340
haftmann@33940
   341
fun lookup_typ thy = Symtab.lookup ((snd o the_signatures o the_exec) thy);
haftmann@33940
   342
haftmann@33940
   343
fun const_typ thy c = case lookup_typ thy c
haftmann@33940
   344
 of SOME ty => ty
haftmann@33940
   345
  | NONE => (Type.strip_sorts o Sign.the_const_type thy) c;
haftmann@33940
   346
haftmann@33940
   347
fun subst_signature thy c ty =
haftmann@33940
   348
  let
haftmann@33940
   349
    fun mk_subst (Type (tyco, tys1)) (ty2 as Type (tyco2, tys2)) =
haftmann@33940
   350
          fold2 mk_subst tys1 tys2
haftmann@33940
   351
      | mk_subst ty (TVar (v, sort)) = Vartab.update (v, ([], ty))
haftmann@33940
   352
  in case lookup_typ thy c
haftmann@33940
   353
   of SOME ty' => Envir.subst_type (mk_subst ty (expand_signature thy ty') Vartab.empty) ty'
haftmann@33940
   354
    | NONE => ty
haftmann@33940
   355
  end;
haftmann@33940
   356
haftmann@33940
   357
fun subst_signatures thy = map_aterms (fn Const (c, ty) => Const (c, subst_signature thy c ty) | t => t);
haftmann@33940
   358
haftmann@33940
   359
fun args_number thy = length o fst o strip_type o const_typ thy;
haftmann@31962
   360
haftmann@31962
   361
haftmann@31962
   362
(* datatypes *)
haftmann@31156
   363
haftmann@31156
   364
fun constrset_of_consts thy cs =
haftmann@31156
   365
  let
haftmann@31156
   366
    val _ = map (fn (c, _) => if (is_some o AxClass.class_of_param thy) c
haftmann@31156
   367
      then error ("Is a class parameter: " ^ string_of_const thy c) else ()) cs;
haftmann@33531
   368
    fun no_constr s (c, ty) = error ("Not a datatype constructor:\n" ^ string_of_const thy c
haftmann@33531
   369
      ^ " :: " ^ string_of_typ thy ty ^ "\n" ^ enclose "(" ")" s);
haftmann@31156
   370
    fun last_typ c_ty ty =
haftmann@31156
   371
      let
haftmann@33531
   372
        val tfrees = Term.add_tfreesT ty [];
haftmann@31156
   373
        val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) ty
haftmann@33531
   374
          handle TYPE _ => no_constr "bad type" c_ty
haftmann@33531
   375
        val _ = if has_duplicates (eq_fst (op =)) vs
haftmann@33531
   376
          then no_constr "duplicate type variables in datatype" c_ty else ();
haftmann@33531
   377
        val _ = if length tfrees <> length vs
haftmann@33531
   378
          then no_constr "type variables missing in datatype" c_ty else ();
haftmann@31156
   379
      in (tyco, vs) end;
haftmann@33940
   380
    fun ty_sorts (c, raw_ty) =
haftmann@31156
   381
      let
haftmann@33940
   382
        val ty = subst_signature thy c raw_ty;
haftmann@33940
   383
        val ty_decl = (Logic.unvarifyT o const_typ thy) c;
haftmann@31156
   384
        val (tyco, _) = last_typ (c, ty) ty_decl;
haftmann@31156
   385
        val (_, vs) = last_typ (c, ty) ty;
haftmann@31156
   386
      in ((tyco, map snd vs), (c, (map fst vs, ty))) end;
haftmann@31156
   387
    fun add ((tyco', sorts'), c) ((tyco, sorts), cs) =
haftmann@31156
   388
      let
haftmann@31998
   389
        val _ = if (tyco' : string) <> tyco
haftmann@31156
   390
          then error "Different type constructors in constructor set"
haftmann@31156
   391
          else ();
haftmann@31156
   392
        val sorts'' = map2 (curry (Sorts.inter_sort (Sign.classes_of thy))) sorts' sorts
haftmann@31156
   393
      in ((tyco, sorts), c :: cs) end;
haftmann@31156
   394
    fun inst vs' (c, (vs, ty)) =
haftmann@31156
   395
      let
haftmann@31156
   396
        val the_v = the o AList.lookup (op =) (vs ~~ vs');
haftmann@31156
   397
        val ty' = map_atyps (fn TFree (v, _) => TFree (the_v v)) ty;
haftmann@31156
   398
      in (c, (fst o strip_type) ty') end;
haftmann@31156
   399
    val c' :: cs' = map ty_sorts cs;
haftmann@31156
   400
    val ((tyco, sorts), cs'') = fold add cs' (apsnd single c');
haftmann@31156
   401
    val vs = Name.names Name.context Name.aT sorts;
haftmann@31156
   402
    val cs''' = map (inst vs) cs'';
haftmann@31156
   403
  in (tyco, (vs, rev cs''')) end;
haftmann@31156
   404
haftmann@31962
   405
fun get_datatype thy tyco =
haftmann@31962
   406
  case these (Symtab.lookup ((the_dtyps o the_exec) thy) tyco)
haftmann@31962
   407
   of (_, spec) :: _ => spec
haftmann@33940
   408
    | [] => arity_number thy tyco
haftmann@31962
   409
        |> Name.invents Name.context Name.aT
haftmann@31962
   410
        |> map (rpair [])
haftmann@31962
   411
        |> rpair [];
haftmann@31962
   412
haftmann@31962
   413
fun get_datatype_of_constr thy c =
haftmann@33940
   414
  case (snd o strip_type o const_typ thy) c
haftmann@31962
   415
   of Type (tyco, _) => if member (op =) ((map fst o snd o get_datatype thy) tyco) c
haftmann@31962
   416
       then SOME tyco else NONE
haftmann@31962
   417
    | _ => NONE;
haftmann@31962
   418
haftmann@31962
   419
fun is_constr thy = is_some o get_datatype_of_constr thy;
haftmann@31962
   420
haftmann@31156
   421
haftmann@34874
   422
(* bare code equations *)
haftmann@31156
   423
haftmann@31156
   424
exception BAD_THM of string;
haftmann@31156
   425
fun bad_thm msg = raise BAD_THM msg;
haftmann@31156
   426
fun error_thm f thm = f thm handle BAD_THM msg => error msg;
haftmann@31642
   427
fun warning_thm f thm = SOME (f thm) handle BAD_THM msg => (warning msg; NONE)
haftmann@31156
   428
fun try_thm f thm = SOME (f thm) handle BAD_THM _ => NONE;
haftmann@31156
   429
haftmann@31156
   430
fun is_linear thm =
haftmann@31156
   431
  let val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm
haftmann@31156
   432
  in not (has_duplicates (op =) ((fold o fold_aterms)
haftmann@31156
   433
    (fn Var (v, _) => cons v | _ => I) args [])) end;
haftmann@31156
   434
haftmann@31962
   435
fun gen_assert_eqn thy is_constr_pat (thm, proper) =
haftmann@31156
   436
  let
haftmann@31156
   437
    val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
wenzelm@32091
   438
      handle TERM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm_global thy thm)
wenzelm@32091
   439
           | THM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm_global thy thm);
haftmann@31156
   440
    fun vars_of t = fold_aterms (fn Var (v, _) => insert (op =) v
haftmann@31156
   441
      | Free _ => bad_thm ("Illegal free variable in equation\n"
wenzelm@32091
   442
          ^ Display.string_of_thm_global thy thm)
haftmann@31156
   443
      | _ => I) t [];
haftmann@31156
   444
    fun tvars_of t = fold_term_types (fn _ =>
haftmann@31156
   445
      fold_atyps (fn TVar (v, _) => insert (op =) v
haftmann@31156
   446
        | TFree _ => bad_thm 
wenzelm@32091
   447
      ("Illegal free type variable in equation\n" ^ Display.string_of_thm_global thy thm))) t [];
haftmann@31156
   448
    val lhs_vs = vars_of lhs;
haftmann@31156
   449
    val rhs_vs = vars_of rhs;
haftmann@31156
   450
    val lhs_tvs = tvars_of lhs;
haftmann@31156
   451
    val rhs_tvs = tvars_of rhs;
haftmann@31156
   452
    val _ = if null (subtract (op =) lhs_vs rhs_vs)
haftmann@31156
   453
      then ()
haftmann@31156
   454
      else bad_thm ("Free variables on right hand side of equation\n"
wenzelm@32091
   455
        ^ Display.string_of_thm_global thy thm);
haftmann@31156
   456
    val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
haftmann@31156
   457
      then ()
haftmann@31156
   458
      else bad_thm ("Free type variables on right hand side of equation\n"
wenzelm@32091
   459
        ^ Display.string_of_thm_global thy thm)
wenzelm@32091
   460
    val (head, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
haftmann@31156
   461
    val (c, ty) = case head
haftmann@31156
   462
     of Const (c_ty as (_, ty)) => (AxClass.unoverload_const thy c_ty, ty)
wenzelm@32091
   463
      | _ => bad_thm ("Equation not headed by constant\n" ^ Display.string_of_thm_global thy thm);
haftmann@31156
   464
    fun check _ (Abs _) = bad_thm
haftmann@31156
   465
          ("Abstraction on left hand side of equation\n"
wenzelm@32091
   466
            ^ Display.string_of_thm_global thy thm)
haftmann@31156
   467
      | check 0 (Var _) = ()
haftmann@31156
   468
      | check _ (Var _) = bad_thm
haftmann@31156
   469
          ("Variable with application on left hand side of equation\n"
wenzelm@32091
   470
            ^ Display.string_of_thm_global thy thm)
haftmann@31156
   471
      | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
haftmann@33940
   472
      | check n (Const (c_ty as (_, ty))) =
haftmann@33940
   473
          let
haftmann@33940
   474
            val c' = AxClass.unoverload_const thy c_ty
haftmann@33940
   475
          in if n = (length o fst o strip_type o subst_signature thy c') ty
haftmann@33940
   476
            then if not proper orelse is_constr_pat c'
haftmann@33940
   477
              then ()
haftmann@33940
   478
              else bad_thm (quote c ^ " is not a constructor, on left hand side of equation\n"
haftmann@33940
   479
                ^ Display.string_of_thm_global thy thm)
haftmann@33940
   480
            else bad_thm
haftmann@33940
   481
              ("Partially applied constant " ^ quote c ^ " on left hand side of equation\n"
haftmann@33940
   482
                 ^ Display.string_of_thm_global thy thm)
haftmann@33940
   483
          end;
haftmann@31156
   484
    val _ = map (check 0) args;
haftmann@31156
   485
    val _ = if not proper orelse is_linear thm then ()
haftmann@31156
   486
      else bad_thm ("Duplicate variables on left hand side of equation\n"
wenzelm@32091
   487
        ^ Display.string_of_thm_global thy thm);
haftmann@31156
   488
    val _ = if (is_none o AxClass.class_of_param thy) c
haftmann@31156
   489
      then ()
haftmann@33940
   490
      else bad_thm ("Overloaded constant as head in equation\n"
wenzelm@32091
   491
        ^ Display.string_of_thm_global thy thm)
haftmann@31962
   492
    val _ = if not (is_constr thy c)
haftmann@31156
   493
      then ()
haftmann@31156
   494
      else bad_thm ("Constructor as head in equation\n"
wenzelm@32091
   495
        ^ Display.string_of_thm_global thy thm)
haftmann@31156
   496
    val ty_decl = Sign.the_const_type thy c;
haftmann@31156
   497
    val _ = if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
haftmann@31156
   498
      then () else bad_thm ("Type\n" ^ string_of_typ thy ty
haftmann@31156
   499
           ^ "\nof equation\n"
wenzelm@32091
   500
           ^ Display.string_of_thm_global thy thm
haftmann@31156
   501
           ^ "\nis incompatible with declared function type\n"
haftmann@31156
   502
           ^ string_of_typ thy ty_decl)
haftmann@31156
   503
  in (thm, proper) end;
haftmann@31156
   504
haftmann@31962
   505
fun assert_eqn thy = error_thm (gen_assert_eqn thy (is_constr thy));
haftmann@31962
   506
haftmann@31962
   507
fun meta_rewrite thy = LocalDefs.meta_rewrite_rule (ProofContext.init thy);
haftmann@31156
   508
haftmann@31962
   509
fun mk_eqn thy = error_thm (gen_assert_eqn thy (K true)) o
haftmann@31962
   510
  apfst (meta_rewrite thy);
haftmann@31962
   511
haftmann@31962
   512
fun mk_eqn_warning thy = Option.map (fn (thm, _) => (thm, is_linear thm))
haftmann@31962
   513
  o warning_thm (gen_assert_eqn thy (K true)) o rpair false o meta_rewrite thy;
haftmann@31962
   514
haftmann@31962
   515
fun mk_eqn_liberal thy = Option.map (fn (thm, _) => (thm, is_linear thm))
haftmann@31962
   516
  o try_thm (gen_assert_eqn thy (K true)) o rpair false o meta_rewrite thy;
haftmann@31156
   517
haftmann@33940
   518
val head_eqn = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
haftmann@31156
   519
haftmann@31957
   520
fun const_typ_eqn thy thm =
haftmann@31156
   521
  let
haftmann@32640
   522
    val (c, ty) = head_eqn thm;
haftmann@31156
   523
    val c' = AxClass.unoverload_const thy (c, ty);
haftmann@33940
   524
      (*permissive wrt. to overloaded constants!*)
haftmann@31156
   525
  in (c', ty) end;
haftmann@33940
   526
haftmann@31957
   527
fun const_eqn thy = fst o const_typ_eqn thy;
haftmann@31156
   528
haftmann@34874
   529
fun logical_typscheme thy (c, ty) =
haftmann@32873
   530
  (map dest_TFree (Sign.const_typargs thy (c, ty)), Type.strip_sorts ty);
haftmann@33940
   531
haftmann@34874
   532
fun typscheme thy (c, ty) = logical_typscheme thy (c, subst_signature thy c ty);
haftmann@33940
   533
haftmann@32873
   534
fun typscheme_eqn thy = typscheme thy o apsnd Logic.unvarifyT o const_typ_eqn thy;
haftmann@33940
   535
haftmann@32873
   536
fun typscheme_eqns thy c [] = 
haftmann@32873
   537
      let
haftmann@33940
   538
        val raw_ty = const_typ thy c;
haftmann@32873
   539
        val tvars = Term.add_tvar_namesT raw_ty [];
haftmann@32873
   540
        val tvars' = case AxClass.class_of_param thy c
haftmann@32873
   541
         of SOME class => [TFree (Name.aT, [class])]
haftmann@32873
   542
          | NONE => Name.invent_list [] Name.aT (length tvars)
haftmann@32873
   543
              |> map (fn v => TFree (v, []));
haftmann@32873
   544
        val ty = typ_subst_TVars (tvars ~~ tvars') raw_ty;
haftmann@34874
   545
      in logical_typscheme thy (c, ty) end
haftmann@33969
   546
  | typscheme_eqns thy c (thm :: _) = typscheme_eqn thy thm;
haftmann@32872
   547
haftmann@31962
   548
fun assert_eqns_const thy c eqns =
haftmann@31962
   549
  let
haftmann@31962
   550
    fun cert (eqn as (thm, _)) = if c = const_eqn thy thm
haftmann@31962
   551
      then eqn else error ("Wrong head of code equation,\nexpected constant "
wenzelm@32091
   552
        ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm_global thy thm)
haftmann@31962
   553
  in map (cert o assert_eqn thy) eqns end;
haftmann@31156
   554
haftmann@34874
   555
haftmann@34874
   556
(* code equation certificates *)
haftmann@34874
   557
haftmann@32929
   558
fun standard_typscheme thy thms =
haftmann@32354
   559
  let
haftmann@32640
   560
    fun tvars_of T = rev (Term.add_tvarsT T []);
haftmann@32640
   561
    val vss = map (tvars_of o snd o head_eqn) thms;
haftmann@32354
   562
    fun inter_sorts vs =
haftmann@32354
   563
      fold (curry (Sorts.inter_sort (Sign.classes_of thy)) o snd) vs [];
haftmann@32354
   564
    val sorts = map_transpose inter_sorts vss;
haftmann@32873
   565
    val vts = Name.names Name.context Name.aT sorts
haftmann@32354
   566
      |> map (fn (v, sort) => TVar ((v, 0), sort));
haftmann@32354
   567
  in map2 (fn vs => Thm.certify_instantiate (vs ~~ vts, [])) vss thms end;
haftmann@31962
   568
haftmann@34874
   569
type cert = thm * bool list;
haftmann@34874
   570
haftmann@34874
   571
fun cert_of_eqns thy [] = (Drule.dummy_thm, [])
haftmann@34874
   572
  | cert_of_eqns thy eqns = 
haftmann@34874
   573
      let
haftmann@34874
   574
        val propers = map snd eqns;
haftmann@34874
   575
        val thms as thm :: _ = (map Thm.freezeT o standard_typscheme thy o map fst) eqns; (*FIXME*)
haftmann@34874
   576
        val (c, ty) = head_eqn thm;
haftmann@34874
   577
        val head_thm = Thm.assume (Thm.cterm_of thy (Logic.mk_equals
haftmann@34874
   578
          (Free ("HEAD", ty), Const (c, ty)))) |> Thm.symmetric;
haftmann@34874
   579
        fun head_conv ct = if can Thm.dest_comb ct
haftmann@34874
   580
          then Conv.fun_conv head_conv ct
haftmann@34874
   581
          else Conv.rewr_conv head_thm ct;
haftmann@34874
   582
        val rewrite_head = Conv.fconv_rule (Conv.arg1_conv head_conv);
haftmann@34874
   583
        val cert = Conjunction.intr_balanced (map rewrite_head thms);
haftmann@34874
   584
      in (cert, propers) end;
haftmann@34874
   585
haftmann@34874
   586
fun head_cert thy cert =
haftmann@34874
   587
  let
haftmann@34874
   588
    val [head] = Thm.hyps_of cert;
haftmann@34874
   589
    val (Free (h, _), Const (c, ty)) = (Logic.dest_equals o the_single o Thm.hyps_of) cert;
haftmann@34874
   590
  in ((c, typscheme thy (AxClass.unoverload_const thy (c, ty), ty)), (head, h)) end;
haftmann@34874
   591
haftmann@34874
   592
fun constrain_cert thy sorts (cert, []) = (cert, [])
haftmann@34874
   593
  | constrain_cert thy sorts (cert, propers) =
haftmann@34874
   594
      let
haftmann@34874
   595
        val ((c, (vs, _)), (head, _)) = head_cert thy cert;
haftmann@34874
   596
        val subst = map2 (fn (v, _) => fn sort => (v, sort)) vs sorts;
haftmann@34874
   597
        val head' = (map_types o map_atyps)
haftmann@34874
   598
          (fn TFree (v, _) => TFree (v, the (AList.lookup (op =) subst v))) head;
haftmann@34874
   599
        val inst = (map2 (fn (v, sort) => fn sort' =>
haftmann@34874
   600
          pairself (Thm.ctyp_of thy) (TVar ((v, 0), sort), TFree (v, sort'))) vs sorts ,[]);
haftmann@34874
   601
        val cert' = cert
haftmann@34874
   602
          |> Thm.implies_intr (Thm.cterm_of thy head)
haftmann@34874
   603
          |> Thm.varifyT
haftmann@34874
   604
          |> Thm.instantiate inst
haftmann@34874
   605
          |> Thm.elim_implies (Thm.assume (Thm.cterm_of thy head'))
haftmann@34874
   606
      in (cert', propers) end;
haftmann@34874
   607
haftmann@34874
   608
fun dest_cert thy (cert, propers) =
haftmann@34874
   609
  let
haftmann@34874
   610
    val (c_vs_ty, (head, h)) = head_cert thy cert;
haftmann@34874
   611
    val equations = cert
haftmann@34874
   612
      |> Thm.prop_of
haftmann@34874
   613
      |> Logic.dest_conjunction_balanced (length propers)
haftmann@34874
   614
      |> map Logic.dest_equals
haftmann@34874
   615
      |> (map o apfst) strip_comb
haftmann@34874
   616
      |> (map o apfst) (fn (Free (h', _), ts) => case h = h' of True => ts)
haftmann@34874
   617
  in (c_vs_ty, equations ~~ propers) end;
haftmann@34874
   618
haftmann@34874
   619
fun eqns_of_cert thy (cert, []) = []
haftmann@34874
   620
  | eqns_of_cert thy (cert, propers) =
haftmann@34874
   621
      let
haftmann@34874
   622
        val (_, (head, _)) = head_cert thy cert;
haftmann@34874
   623
        val thms = cert
haftmann@34874
   624
          |> LocalDefs.expand [Thm.cterm_of thy head]
haftmann@34874
   625
          |> Thm.varifyT
haftmann@34874
   626
          |> Conjunction.elim_balanced (length propers)
haftmann@34874
   627
      in thms ~~ propers end;
haftmann@34874
   628
haftmann@34874
   629
haftmann@34874
   630
(* code equation access *)
haftmann@34874
   631
haftmann@31962
   632
fun these_eqns thy c =
haftmann@34244
   633
  Symtab.lookup ((the_eqns o the_exec) thy) c
haftmann@34244
   634
  |> Option.map (snd o snd o fst)
haftmann@34244
   635
  |> these
haftmann@31962
   636
  |> (map o apfst) (Thm.transfer thy)
haftmann@32929
   637
  |> burrow_fst (standard_typscheme thy);
haftmann@31962
   638
haftmann@34874
   639
fun eqn_cert thy c =
haftmann@34874
   640
  Symtab.lookup ((the_eqns o the_exec) thy) c
haftmann@34874
   641
  |> Option.map (snd o snd o fst)
haftmann@34874
   642
  |> these
haftmann@34874
   643
  |> (map o apfst) (Thm.transfer thy)
haftmann@34874
   644
  |> cert_of_eqns thy;
haftmann@31962
   645
haftmann@31962
   646
haftmann@31962
   647
(* cases *)
haftmann@31156
   648
haftmann@31156
   649
fun case_certificate thm =
haftmann@31156
   650
  let
haftmann@31156
   651
    val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
haftmann@32640
   652
      o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.plain_prop_of) thm;
haftmann@31156
   653
    val _ = case head of Free _ => true
haftmann@31156
   654
      | Var _ => true
haftmann@31156
   655
      | _ => raise TERM ("case_cert", []);
haftmann@31156
   656
    val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
haftmann@31156
   657
    val (Const (case_const, _), raw_params) = strip_comb case_expr;
haftmann@31156
   658
    val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
haftmann@31156
   659
    val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
haftmann@31156
   660
    val params = map (fst o dest_Var) (nth_drop n raw_params);
haftmann@31156
   661
    fun dest_case t =
haftmann@31156
   662
      let
haftmann@31156
   663
        val (head' $ t_co, rhs) = Logic.dest_equals t;
haftmann@31156
   664
        val _ = if head' = head then () else raise TERM ("case_cert", []);
haftmann@31156
   665
        val (Const (co, _), args) = strip_comb t_co;
haftmann@31156
   666
        val (Var (param, _), args') = strip_comb rhs;
haftmann@31156
   667
        val _ = if args' = args then () else raise TERM ("case_cert", []);
haftmann@31156
   668
      in (param, co) end;
haftmann@31156
   669
    fun analyze_cases cases =
haftmann@31156
   670
      let
haftmann@31156
   671
        val co_list = fold (AList.update (op =) o dest_case) cases [];
haftmann@31156
   672
      in map (the o AList.lookup (op =) co_list) params end;
haftmann@31156
   673
    fun analyze_let t =
haftmann@31156
   674
      let
haftmann@31156
   675
        val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
haftmann@31156
   676
        val _ = if head' = head then () else raise TERM ("case_cert", []);
haftmann@31156
   677
        val _ = if arg' = arg then () else raise TERM ("case_cert", []);
haftmann@31156
   678
        val _ = if [param'] = params then () else raise TERM ("case_cert", []);
haftmann@31156
   679
      in [] end;
haftmann@31156
   680
    fun analyze (cases as [let_case]) =
haftmann@31156
   681
          (analyze_cases cases handle Bind => analyze_let let_case)
haftmann@31156
   682
      | analyze cases = analyze_cases cases;
haftmann@31156
   683
  in (case_const, (n, analyze cases)) end;
haftmann@31156
   684
haftmann@31156
   685
fun case_cert thm = case_certificate thm
haftmann@31156
   686
  handle Bind => error "bad case certificate"
haftmann@31156
   687
       | TERM _ => error "bad case certificate";
haftmann@31156
   688
haftmann@31962
   689
fun get_case_scheme thy = Symtab.lookup ((fst o the_cases o the_exec) thy);
haftmann@24219
   690
haftmann@31962
   691
val undefineds = Symtab.keys o snd o the_cases o the_exec;
haftmann@24219
   692
haftmann@24219
   693
haftmann@31962
   694
(* diagnostic *)
haftmann@24219
   695
haftmann@24219
   696
fun print_codesetup thy =
haftmann@24219
   697
  let
haftmann@24219
   698
    val ctxt = ProofContext.init thy;
haftmann@24844
   699
    val exec = the_exec thy;
haftmann@33006
   700
    fun pretty_eqns (s, (_, eqns)) =
haftmann@24219
   701
      (Pretty.block o Pretty.fbreaks) (
haftmann@33006
   702
        Pretty.str s :: map (Display.pretty_thm ctxt o fst) eqns
haftmann@24219
   703
      );
haftmann@24219
   704
    fun pretty_dtyp (s, []) =
haftmann@24219
   705
          Pretty.str s
haftmann@24219
   706
      | pretty_dtyp (s, cos) =
haftmann@24219
   707
          (Pretty.block o Pretty.breaks) (
haftmann@24219
   708
            Pretty.str s
haftmann@24219
   709
            :: Pretty.str "="
haftmann@31156
   710
            :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str (string_of_const thy c)
haftmann@24219
   711
                 | (c, tys) =>
haftmann@24219
   712
                     (Pretty.block o Pretty.breaks)
haftmann@31156
   713
                        (Pretty.str (string_of_const thy c)
wenzelm@26947
   714
                          :: Pretty.str "of"
wenzelm@26947
   715
                          :: map (Pretty.quote o Syntax.pretty_typ_global thy) tys)) cos)
haftmann@24219
   716
          );
haftmann@28368
   717
    val eqns = the_eqns exec
haftmann@24423
   718
      |> Symtab.dest
haftmann@31156
   719
      |> (map o apfst) (string_of_const thy)
haftmann@28695
   720
      |> (map o apsnd) (snd o fst)
haftmann@24219
   721
      |> sort (string_ord o pairself fst);
haftmann@24219
   722
    val dtyps = the_dtyps exec
haftmann@24219
   723
      |> Symtab.dest
haftmann@28695
   724
      |> map (fn (dtco, (_, (vs, cos)) :: _) =>
haftmann@31957
   725
          (string_of_typ thy (Type (dtco, map TFree vs)), cos))
haftmann@24219
   726
      |> sort (string_ord o pairself fst)
haftmann@24219
   727
  in
haftmann@24219
   728
    (Pretty.writeln o Pretty.chunks) [
haftmann@24219
   729
      Pretty.block (
haftmann@30023
   730
        Pretty.str "code equations:"
haftmann@24219
   731
        :: Pretty.fbrk
haftmann@33006
   732
        :: (Pretty.fbreaks o map pretty_eqns) eqns
haftmann@24219
   733
      ),
haftmann@25968
   734
      Pretty.block (
haftmann@24219
   735
        Pretty.str "datatypes:"
haftmann@24219
   736
        :: Pretty.fbrk
haftmann@24219
   737
        :: (Pretty.fbreaks o map pretty_dtyp) dtyps
haftmann@24219
   738
      )
haftmann@24219
   739
    ]
haftmann@24219
   740
  end;
haftmann@24219
   741
haftmann@24219
   742
haftmann@31962
   743
(** declaring executable ingredients **)
haftmann@31962
   744
haftmann@33940
   745
(* constant signatures *)
haftmann@33940
   746
haftmann@33940
   747
fun add_type tyco thy =
haftmann@33940
   748
  case Symtab.lookup ((snd o #types o Type.rep_tsig o Sign.tsig_of) thy) tyco
haftmann@33940
   749
   of SOME (Type.Abbreviation (vs, _, _)) =>
haftmann@34173
   750
          (map_exec_purge o map_signatures o apfst)
haftmann@33940
   751
            (Symtab.update (tyco, length vs)) thy
haftmann@33940
   752
    | _ => error ("No such type abbreviation: " ^ quote tyco);
haftmann@33940
   753
haftmann@33940
   754
fun add_type_cmd s thy = add_type (Sign.intern_type thy s) thy;
haftmann@33940
   755
haftmann@33940
   756
fun gen_add_signature prep_const prep_signature (raw_c, raw_ty) thy =
haftmann@33940
   757
  let
haftmann@33940
   758
    val c = prep_const thy raw_c;
haftmann@33940
   759
    val ty = prep_signature thy raw_ty;
haftmann@33940
   760
    val ty' = expand_signature thy ty;
haftmann@33940
   761
    val ty'' = Sign.the_const_type thy c;
haftmann@33940
   762
    val _ = if typ_equiv (ty', ty'') then () else
haftmann@33940
   763
      error ("Illegal constant signature: " ^ Syntax.string_of_typ_global thy ty);
haftmann@33940
   764
  in
haftmann@33940
   765
    thy
haftmann@34173
   766
    |> (map_exec_purge o map_signatures o apsnd) (Symtab.update (c, ty))
haftmann@33940
   767
  end;
haftmann@33940
   768
haftmann@33940
   769
val add_signature = gen_add_signature (K I) cert_signature;
haftmann@33940
   770
val add_signature_cmd = gen_add_signature read_const read_signature;
haftmann@33940
   771
haftmann@33940
   772
haftmann@31962
   773
(* code equations *)
haftmann@31962
   774
haftmann@33075
   775
fun gen_add_eqn default (thm, proper) thy =
haftmann@33075
   776
  let
haftmann@33075
   777
    val thm' = Thm.close_derivation thm;
haftmann@33075
   778
    val c = const_eqn thy thm';
haftmann@33075
   779
  in change_eqns false c (add_thm thy default (thm', proper)) thy end;
haftmann@31962
   780
haftmann@31962
   781
fun add_eqn thm thy =
haftmann@31962
   782
  gen_add_eqn false (mk_eqn thy (thm, true)) thy;
haftmann@31962
   783
haftmann@31962
   784
fun add_warning_eqn thm thy =
haftmann@31962
   785
  case mk_eqn_warning thy thm
haftmann@31962
   786
   of SOME eqn => gen_add_eqn false eqn thy
haftmann@31962
   787
    | NONE => thy;
haftmann@31962
   788
haftmann@31962
   789
fun add_default_eqn thm thy =
haftmann@31962
   790
  case mk_eqn_liberal thy thm
haftmann@31962
   791
   of SOME eqn => gen_add_eqn true eqn thy
haftmann@31962
   792
    | NONE => thy;
haftmann@31962
   793
haftmann@31962
   794
fun add_nbe_eqn thm thy =
haftmann@31962
   795
  gen_add_eqn false (mk_eqn thy (thm, false)) thy;
haftmann@31962
   796
haftmann@31962
   797
val add_default_eqn_attribute = Thm.declaration_attribute
haftmann@31962
   798
  (fn thm => Context.mapping (add_default_eqn thm) I);
haftmann@31962
   799
val add_default_eqn_attrib = Attrib.internal (K add_default_eqn_attribute);
haftmann@31962
   800
haftmann@31962
   801
fun del_eqn thm thy = case mk_eqn_liberal thy thm
haftmann@31962
   802
 of SOME (thm, _) => change_eqns true (const_eqn thy thm) (del_thm thm) thy
haftmann@31962
   803
  | NONE => thy;
haftmann@31962
   804
haftmann@34244
   805
fun del_eqns c = change_eqns true c (K (false, []));
haftmann@34244
   806
haftmann@34244
   807
haftmann@34244
   808
(* cases *)
haftmann@34244
   809
haftmann@34244
   810
fun add_case thm thy =
haftmann@34244
   811
  let
haftmann@34244
   812
    val (c, (k, case_pats)) = case_cert thm;
haftmann@34244
   813
    val _ = case filter_out (is_constr thy) case_pats
haftmann@34244
   814
     of [] => ()
haftmann@34244
   815
      | cs => error ("Non-constructor(s) in case certificate: " ^ commas (map quote cs));
haftmann@34244
   816
    val entry = (1 + Int.max (1, length case_pats), (k, case_pats))
haftmann@34244
   817
  in (map_exec_purge o map_cases o apfst) (Symtab.update (c, entry)) thy end;
haftmann@34244
   818
haftmann@34244
   819
fun add_undefined c thy =
haftmann@34244
   820
  (map_exec_purge o map_cases o apsnd) (Symtab.update (c, ())) thy;
haftmann@34244
   821
haftmann@34244
   822
haftmann@34244
   823
(* datatypes *)
haftmann@34244
   824
haftmann@34244
   825
structure Type_Interpretation =
haftmann@34244
   826
  Interpretation(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
haftmann@34244
   827
haftmann@34244
   828
fun add_datatype raw_cs thy =
haftmann@34244
   829
  let
haftmann@34244
   830
    val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
haftmann@34244
   831
    val (tyco, vs_cos) = constrset_of_consts thy cs;
haftmann@34244
   832
    val old_cs = (map fst o snd o get_datatype thy) tyco;
haftmann@34244
   833
    fun drop_outdated_cases cases = fold Symtab.delete_safe
haftmann@34244
   834
      (Symtab.fold (fn (c, (_, (_, cos))) =>
haftmann@34244
   835
        if exists (member (op =) old_cs) cos
haftmann@34244
   836
          then insert (op =) c else I) cases []) cases;
haftmann@34244
   837
  in
haftmann@34244
   838
    thy
haftmann@34244
   839
    |> fold (del_eqns o fst) cs
haftmann@34244
   840
    |> map_exec_purge
haftmann@34244
   841
        ((map_dtyps o Symtab.map_default (tyco, [])) (cons (serial (), vs_cos))
haftmann@34244
   842
        #> (map_cases o apfst) drop_outdated_cases)
haftmann@34244
   843
    |> Type_Interpretation.data (tyco, serial ())
haftmann@34244
   844
  end;
haftmann@34244
   845
haftmann@34244
   846
fun type_interpretation f =  Type_Interpretation.interpretation
haftmann@34244
   847
  (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
haftmann@34244
   848
haftmann@34244
   849
fun add_datatype_cmd raw_cs thy =
haftmann@34244
   850
  let
haftmann@34244
   851
    val cs = map (read_bare_const thy) raw_cs;
haftmann@34244
   852
  in add_datatype cs thy end;
haftmann@34244
   853
haftmann@34244
   854
haftmann@32070
   855
(* c.f. src/HOL/Tools/recfun_codegen.ML *)
haftmann@32070
   856
wenzelm@33522
   857
structure Code_Target_Attr = Theory_Data
wenzelm@33522
   858
(
haftmann@31998
   859
  type T = (string -> thm -> theory -> theory) option;
haftmann@31998
   860
  val empty = NONE;
haftmann@31998
   861
  val extend = I;
wenzelm@33522
   862
  fun merge (f1, f2) = if is_some f1 then f1 else f2;
haftmann@31998
   863
);
haftmann@31998
   864
haftmann@32070
   865
fun set_code_target_attr f = Code_Target_Attr.map (K (SOME f));
haftmann@32070
   866
haftmann@32070
   867
fun code_target_attr prefix thm thy =
haftmann@32070
   868
  let
haftmann@32070
   869
    val attr = the_default ((K o K) I) (Code_Target_Attr.get thy);
haftmann@32070
   870
  in thy |> add_warning_eqn thm |> attr prefix thm end;
haftmann@32070
   871
(* setup *)
haftmann@31998
   872
haftmann@31962
   873
val _ = Context.>> (Context.map_theory
haftmann@31962
   874
  (let
haftmann@31962
   875
    fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
haftmann@31998
   876
    val code_attribute_parser =
haftmann@31998
   877
      Args.del |-- Scan.succeed (mk_attribute del_eqn)
haftmann@31998
   878
      || Args.$$$ "nbe" |-- Scan.succeed (mk_attribute add_nbe_eqn)
haftmann@31998
   879
      || (Args.$$$ "target" |-- Args.colon |-- Args.name >>
haftmann@32070
   880
           (mk_attribute o code_target_attr))
haftmann@31998
   881
      || Scan.succeed (mk_attribute add_warning_eqn);
haftmann@31962
   882
  in
haftmann@31962
   883
    Type_Interpretation.init
haftmann@31998
   884
    #> Attrib.setup (Binding.name "code") (Scan.lift code_attribute_parser)
haftmann@31998
   885
        "declare theorems for code generation"
haftmann@31962
   886
  end));
haftmann@31962
   887
haftmann@24219
   888
end; (*struct*)
haftmann@24219
   889
haftmann@24219
   890
bulwahn@32661
   891
(** type-safe interfaces for data dependent on executable code **)
haftmann@24219
   892
haftmann@34173
   893
functor Code_Data(Data: CODE_DATA_ARGS): CODE_DATA =
haftmann@24219
   894
struct
haftmann@24219
   895
haftmann@24219
   896
type T = Data.T;
haftmann@24219
   897
exception Data of T;
haftmann@24219
   898
fun dest (Data x) = x
haftmann@24219
   899
haftmann@34173
   900
val kind = Code.declare_data (Data Data.empty);
haftmann@24219
   901
haftmann@24219
   902
val data_op = (kind, Data, dest);
haftmann@24219
   903
haftmann@24219
   904
val change = Code.change_data data_op;
haftmann@24219
   905
fun change_yield thy = Code.change_yield_data data_op thy;
haftmann@24219
   906
haftmann@24219
   907
end;
haftmann@24219
   908
haftmann@28143
   909
structure Code : CODE = struct open Code; end;