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