src/Pure/Isar/code.ML
author haftmann
Tue Jul 07 17:21:27 2009 +0200 (2009-07-07 ago)
changeset 31957 a9742afd403e
parent 31890 e943b039f0ac
child 31962 baa8dce5bc45
permissions -rw-r--r--
tuned interface of structure Code
haftmann@24219
     1
(*  Title:      Pure/Isar/code.ML
haftmann@24219
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@24219
     3
haftmann@24219
     4
Abstract executable content of theory.  Management of data dependent on
haftmann@25485
     5
executable content.  Cache assumes non-concurrent processing of a single theory.
haftmann@24219
     6
*)
haftmann@24219
     7
haftmann@24219
     8
signature CODE =
haftmann@24219
     9
sig
haftmann@31957
    10
  (*constants*)
haftmann@31957
    11
  val string_of_const: theory -> string -> string
haftmann@31957
    12
  val args_number: theory -> string -> int
haftmann@31957
    13
  val check_const: theory -> term -> string
haftmann@31957
    14
  val read_bare_const: theory -> string -> string * typ
haftmann@31957
    15
  val read_const: theory -> string -> string
haftmann@31957
    16
  val typscheme: theory -> string * typ -> (string * sort) list * typ
haftmann@31957
    17
haftmann@31156
    18
  (*constructor sets*)
haftmann@31156
    19
  val constrset_of_consts: theory -> (string * typ) list
haftmann@31156
    20
    -> string * ((string * sort) list * (string * typ list) list)
haftmann@31156
    21
haftmann@31156
    22
  (*constant aliasses*)
haftmann@31156
    23
  val add_const_alias: thm -> theory -> theory
haftmann@31156
    24
  val triv_classes: theory -> class list
haftmann@31156
    25
  val resubst_alias: theory -> string -> string
haftmann@31156
    26
haftmann@31156
    27
  (*code equations*)
haftmann@31156
    28
  val mk_eqn: theory -> (string -> bool) -> thm * bool -> thm * bool
haftmann@31642
    29
  val mk_eqn_warning: theory -> (string -> bool) -> thm -> (thm * bool) option
haftmann@31156
    30
  val mk_eqn_liberal: theory -> (string -> bool) -> thm -> (thm * bool) option
haftmann@31156
    31
  val assert_eqn: theory -> thm * bool -> thm * bool
haftmann@31156
    32
  val assert_eqns_const: theory -> string
haftmann@31156
    33
    -> (thm * bool) list -> (thm * bool) list
haftmann@31957
    34
  val const_typ_eqn: theory -> thm -> string * typ
haftmann@31156
    35
  val typscheme_eqn: theory -> thm -> (string * sort) list * typ
haftmann@31156
    36
  val expand_eta: theory -> int -> thm -> thm
haftmann@31156
    37
  val norm_args: theory -> thm list -> thm list 
haftmann@31156
    38
  val norm_varnames: theory -> thm list -> thm list
haftmann@31156
    39
haftmann@31156
    40
  (*executable content*)
haftmann@31156
    41
  val add_datatype: (string * typ) list -> theory -> theory
haftmann@31156
    42
  val add_datatype_cmd: string list -> theory -> theory
haftmann@31156
    43
  val type_interpretation:
haftmann@31156
    44
    (string * ((string * sort) list * (string * typ list) list)
haftmann@31156
    45
      -> theory -> theory) -> theory -> theory
haftmann@28368
    46
  val add_eqn: thm -> theory -> theory
haftmann@31957
    47
  val add_eqnl: string * (thm * bool) list lazy -> theory -> theory
haftmann@31088
    48
  val add_nbe_eqn: thm -> theory -> theory
haftmann@28368
    49
  val add_default_eqn: thm -> theory -> theory
haftmann@28703
    50
  val add_default_eqn_attribute: attribute
haftmann@28703
    51
  val add_default_eqn_attrib: Attrib.src
haftmann@28368
    52
  val del_eqn: thm -> theory -> theory
haftmann@28368
    53
  val del_eqns: string -> theory -> theory
haftmann@24844
    54
  val add_case: thm -> theory -> theory
haftmann@24844
    55
  val add_undefined: string -> theory -> theory
haftmann@24219
    56
  val get_datatype: theory -> string -> ((string * sort) list * (string * typ list) list)
haftmann@24423
    57
  val get_datatype_of_constr: theory -> string -> string option
haftmann@31156
    58
  val these_eqns: theory -> string -> (thm * bool) list
haftmann@31642
    59
  val all_eqns: theory -> (thm * bool) list
haftmann@30023
    60
  val get_case_scheme: theory -> string -> (int * (int * string list)) option
haftmann@31890
    61
  val undefineds: theory -> string list
haftmann@24219
    62
  val print_codesetup: theory -> unit
haftmann@31957
    63
haftmann@31957
    64
  (*infrastructure*)
haftmann@31957
    65
  val add_attribute: string * attribute parser -> theory -> theory
haftmann@31957
    66
  val purge_data: theory -> theory
haftmann@24219
    67
end;
haftmann@24219
    68
haftmann@24219
    69
signature CODE_DATA_ARGS =
haftmann@24219
    70
sig
haftmann@24219
    71
  type T
haftmann@24219
    72
  val empty: T
haftmann@27609
    73
  val purge: theory -> string list -> T -> T
haftmann@24219
    74
end;
haftmann@24219
    75
haftmann@24219
    76
signature CODE_DATA =
haftmann@24219
    77
sig
haftmann@24219
    78
  type T
haftmann@24219
    79
  val get: theory -> T
haftmann@24219
    80
  val change: theory -> (T -> T) -> T
haftmann@24219
    81
  val change_yield: theory -> (T -> 'a * T) -> 'a * T
haftmann@24219
    82
end;
haftmann@24219
    83
haftmann@24219
    84
signature PRIVATE_CODE =
haftmann@24219
    85
sig
haftmann@24219
    86
  include CODE
haftmann@27609
    87
  val declare_data: Object.T -> (theory -> string list -> Object.T -> Object.T)
haftmann@27609
    88
    -> serial
haftmann@24219
    89
  val get_data: serial * ('a -> Object.T) * (Object.T -> 'a)
haftmann@24219
    90
    -> theory -> 'a
haftmann@24219
    91
  val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
haftmann@24219
    92
    -> theory -> ('a -> 'a) -> 'a
haftmann@24219
    93
  val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
haftmann@24219
    94
    -> theory -> ('a -> 'b * 'a) -> 'b * 'a
haftmann@24219
    95
end;
haftmann@24219
    96
haftmann@24219
    97
structure Code : PRIVATE_CODE =
haftmann@24219
    98
struct
haftmann@24219
    99
haftmann@31156
   100
(* auxiliary *)
haftmann@31156
   101
haftmann@31156
   102
fun string_of_typ thy = setmp show_sorts true (Syntax.string_of_typ_global thy);
haftmann@31156
   103
fun string_of_const thy c = case AxClass.inst_of_param thy c
haftmann@31156
   104
 of SOME (c, tyco) => Sign.extern_const thy c ^ " " ^ enclose "[" "]" (Sign.extern_type thy tyco)
haftmann@31156
   105
  | NONE => Sign.extern_const thy c;
haftmann@31156
   106
haftmann@31957
   107
fun args_number thy = length o fst o strip_type o Sign.the_const_type thy;
haftmann@31156
   108
haftmann@31156
   109
haftmann@31156
   110
(* utilities *)
haftmann@31156
   111
haftmann@31156
   112
fun typscheme thy (c, ty) =
haftmann@31156
   113
  let
haftmann@31156
   114
    val ty' = Logic.unvarifyT ty;
haftmann@31957
   115
  in (map dest_TFree (Sign.const_typargs thy (c, ty')), Type.strip_sorts ty') end;
haftmann@31156
   116
haftmann@31156
   117
fun expand_eta thy k thm =
haftmann@31156
   118
  let
haftmann@31156
   119
    val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm;
haftmann@31156
   120
    val (head, args) = strip_comb lhs;
haftmann@31156
   121
    val l = if k = ~1
haftmann@31156
   122
      then (length o fst o strip_abs) rhs
haftmann@31156
   123
      else Int.max (0, k - length args);
haftmann@31156
   124
    val used = Name.make_context (map (fst o fst) (Term.add_vars lhs []));
haftmann@31156
   125
    fun get_name _ 0 = pair []
haftmann@31156
   126
      | get_name (Abs (v, ty, t)) k =
haftmann@31156
   127
          Name.variants [v]
haftmann@31156
   128
          ##>> get_name t (k - 1)
haftmann@31156
   129
          #>> (fn ([v'], vs') => (v', ty) :: vs')
haftmann@31156
   130
      | get_name t k = 
haftmann@31156
   131
          let
haftmann@31156
   132
            val (tys, _) = (strip_type o fastype_of) t
haftmann@31156
   133
          in case tys
haftmann@31156
   134
           of [] => raise TERM ("expand_eta", [t])
haftmann@31156
   135
            | ty :: _ =>
haftmann@31156
   136
                Name.variants [""]
haftmann@31156
   137
                #-> (fn [v] => get_name (t $ Var ((v, 0), ty)) (k - 1)
haftmann@31156
   138
                #>> (fn vs' => (v, ty) :: vs'))
haftmann@31156
   139
          end;
haftmann@31156
   140
    val (vs, _) = get_name rhs l used;
haftmann@31156
   141
    fun expand (v, ty) thm = Drule.fun_cong_rule thm
haftmann@31156
   142
      (Thm.cterm_of thy (Var ((v, 0), ty)));
haftmann@31156
   143
  in
haftmann@31156
   144
    thm
haftmann@31156
   145
    |> fold expand vs
haftmann@31156
   146
    |> Conv.fconv_rule Drule.beta_eta_conversion
haftmann@31156
   147
  end;
haftmann@31156
   148
haftmann@31156
   149
fun norm_args thy thms =
haftmann@31156
   150
  let
haftmann@31156
   151
    val num_args_of = length o snd o strip_comb o fst o Logic.dest_equals;
haftmann@31156
   152
    val k = fold (curry Int.max o num_args_of o Thm.prop_of) thms 0;
haftmann@31156
   153
  in
haftmann@31156
   154
    thms
haftmann@31156
   155
    |> map (expand_eta thy k)
haftmann@31156
   156
    |> map (Conv.fconv_rule Drule.beta_eta_conversion)
haftmann@31156
   157
  end;
haftmann@31156
   158
haftmann@31156
   159
fun canonical_tvars thy thm =
haftmann@31156
   160
  let
haftmann@31156
   161
    val ctyp = Thm.ctyp_of thy;
haftmann@31156
   162
    val purify_tvar = unprefix "'" #> Name.desymbolize false #> prefix "'";
haftmann@31156
   163
    fun tvars_subst_for thm = (fold_types o fold_atyps)
haftmann@31156
   164
      (fn TVar (v_i as (v, _), sort) => let
haftmann@31156
   165
            val v' = purify_tvar v
haftmann@31156
   166
          in if v = v' then I
haftmann@31156
   167
          else insert (op =) (v_i, (v', sort)) end
haftmann@31156
   168
        | _ => I) (prop_of thm) [];
haftmann@31156
   169
    fun mk_inst (v_i, (v', sort)) (maxidx, acc) =
haftmann@31156
   170
      let
haftmann@31156
   171
        val ty = TVar (v_i, sort)
haftmann@31156
   172
      in
haftmann@31156
   173
        (maxidx + 1, (ctyp ty, ctyp (TVar ((v', maxidx), sort))) :: acc)
haftmann@31156
   174
      end;
haftmann@31156
   175
    val maxidx = Thm.maxidx_of thm + 1;
haftmann@31156
   176
    val (_, inst) = fold mk_inst (tvars_subst_for thm) (maxidx + 1, []);
haftmann@31156
   177
  in Thm.instantiate (inst, []) thm end;
haftmann@31156
   178
haftmann@31156
   179
fun canonical_vars thy thm =
haftmann@31156
   180
  let
haftmann@31156
   181
    val cterm = Thm.cterm_of thy;
haftmann@31156
   182
    val purify_var = Name.desymbolize false;
haftmann@31156
   183
    fun vars_subst_for thm = fold_aterms
haftmann@31156
   184
      (fn Var (v_i as (v, _), ty) => let
haftmann@31156
   185
            val v' = purify_var v
haftmann@31156
   186
          in if v = v' then I
haftmann@31156
   187
          else insert (op =) (v_i, (v', ty)) end
haftmann@31156
   188
        | _ => I) (prop_of thm) [];
haftmann@31156
   189
    fun mk_inst (v_i as (v, i), (v', ty)) (maxidx, acc) =
haftmann@31156
   190
      let
haftmann@31156
   191
        val t = Var (v_i, ty)
haftmann@31156
   192
      in
haftmann@31156
   193
        (maxidx + 1, (cterm t, cterm (Var ((v', maxidx), ty))) :: acc)
haftmann@31156
   194
      end;
haftmann@31156
   195
    val maxidx = Thm.maxidx_of thm + 1;
haftmann@31156
   196
    val (_, inst) = fold mk_inst (vars_subst_for thm) (maxidx + 1, []);
haftmann@31156
   197
  in Thm.instantiate ([], inst) thm end;
haftmann@31156
   198
haftmann@31156
   199
fun canonical_absvars thm =
haftmann@31156
   200
  let
haftmann@31156
   201
    val t = Thm.plain_prop_of thm;
haftmann@31156
   202
    val purify_var = Name.desymbolize false;
haftmann@31156
   203
    val t' = Term.map_abs_vars purify_var t;
haftmann@31156
   204
  in Thm.rename_boundvars t t' thm end;
haftmann@31156
   205
haftmann@31156
   206
fun norm_varnames thy thms =
haftmann@31156
   207
  let
haftmann@31156
   208
    fun burrow_thms f [] = []
haftmann@31156
   209
      | burrow_thms f thms =
haftmann@31156
   210
          thms
haftmann@31156
   211
          |> Conjunction.intr_balanced
haftmann@31156
   212
          |> f
haftmann@31156
   213
          |> Conjunction.elim_balanced (length thms)
haftmann@31156
   214
  in
haftmann@31156
   215
    thms
haftmann@31156
   216
    |> map (canonical_vars thy)
haftmann@31156
   217
    |> map canonical_absvars
haftmann@31156
   218
    |> map Drule.zero_var_indexes
haftmann@31156
   219
    |> burrow_thms (canonical_tvars thy)
haftmann@31156
   220
    |> Drule.zero_var_indexes_list
haftmann@31156
   221
  end;
haftmann@31156
   222
haftmann@31156
   223
haftmann@31957
   224
(* reading constants as terms *)
haftmann@31957
   225
haftmann@31957
   226
fun check_bare_const thy t = case try dest_Const t
haftmann@31957
   227
 of SOME c_ty => c_ty
haftmann@31957
   228
  | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
haftmann@31957
   229
haftmann@31957
   230
fun check_const thy = AxClass.unoverload_const thy o check_bare_const thy;
haftmann@31957
   231
haftmann@31957
   232
fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
haftmann@31957
   233
haftmann@31957
   234
fun read_const thy = AxClass.unoverload_const thy o read_bare_const thy;
haftmann@31957
   235
haftmann@31957
   236
haftmann@31156
   237
(* const aliasses *)
haftmann@31156
   238
haftmann@31156
   239
structure ConstAlias = TheoryDataFun
haftmann@31156
   240
(
haftmann@31156
   241
  type T = ((string * string) * thm) list * class list;
haftmann@31156
   242
  val empty = ([], []);
haftmann@31156
   243
  val copy = I;
haftmann@31156
   244
  val extend = I;
haftmann@31156
   245
  fun merge _ ((alias1, classes1), (alias2, classes2)) : T =
haftmann@31156
   246
    (Library.merge (eq_snd Thm.eq_thm_prop) (alias1, alias2),
haftmann@31156
   247
      Library.merge (op =) (classes1, classes2));
haftmann@31156
   248
);
haftmann@31156
   249
haftmann@31156
   250
fun add_const_alias thm thy =
haftmann@31156
   251
  let
haftmann@31957
   252
    val (ofclass, eqn) = case try Logic.dest_equals (Thm.prop_of thm)
haftmann@31957
   253
     of SOME ofclass_eq => ofclass_eq
haftmann@31957
   254
      | _ => error ("Bad certificate: " ^ Display.string_of_thm thm);
haftmann@31957
   255
    val (T, class) = case try Logic.dest_of_class ofclass
haftmann@31957
   256
     of SOME T_class => T_class
haftmann@31957
   257
      | _ => error ("Bad certificate: " ^ Display.string_of_thm thm);
haftmann@31957
   258
    val tvar = case try Term.dest_TVar T
haftmann@31957
   259
     of SOME tvar => tvar
haftmann@31957
   260
      | _ => error ("Bad type: " ^ Display.string_of_thm thm);
haftmann@31957
   261
    val _ = if Term.add_tvars eqn [] = [tvar] then ()
haftmann@31957
   262
      else error ("Inconsistent type: " ^ Display.string_of_thm thm);
haftmann@31957
   263
    val lhs_rhs = case try Logic.dest_equals eqn
haftmann@31156
   264
     of SOME lhs_rhs => lhs_rhs
haftmann@31957
   265
      | _ => error ("Not an equation: " ^ Syntax.string_of_term_global thy eqn);
haftmann@31957
   266
    val c_c' = case try (pairself (check_const thy)) lhs_rhs
haftmann@31156
   267
     of SOME c_c' => c_c'
haftmann@31957
   268
      | _ => error ("Not an equation with two constants: "
haftmann@31957
   269
          ^ Syntax.string_of_term_global thy eqn);
haftmann@31957
   270
    val _ = if the_list (AxClass.class_of_param thy (snd c_c')) = [class] then ()
haftmann@31957
   271
      else error ("Inconsistent class: " ^ Display.string_of_thm thm);
haftmann@31156
   272
  in thy |>
haftmann@31156
   273
    ConstAlias.map (fn (alias, classes) =>
haftmann@31957
   274
      ((c_c', thm) :: alias, insert (op =) class classes))
haftmann@31156
   275
  end;
haftmann@31156
   276
haftmann@31156
   277
fun resubst_alias thy =
haftmann@31156
   278
  let
haftmann@31156
   279
    val alias = fst (ConstAlias.get thy);
haftmann@31156
   280
    val subst_inst_param = Option.map fst o AxClass.inst_of_param thy;
haftmann@31156
   281
    fun subst_alias c =
haftmann@31156
   282
      get_first (fn ((c', c''), _) => if c = c'' then SOME c' else NONE) alias;
haftmann@31156
   283
  in
haftmann@31156
   284
    perhaps subst_inst_param
haftmann@31156
   285
    #> perhaps subst_alias
haftmann@31156
   286
  end;
haftmann@31156
   287
haftmann@31156
   288
val triv_classes = snd o ConstAlias.get;
haftmann@31156
   289
haftmann@31156
   290
haftmann@31156
   291
(* constructor sets *)
haftmann@31156
   292
haftmann@31156
   293
fun constrset_of_consts thy cs =
haftmann@31156
   294
  let
haftmann@31156
   295
    val _ = map (fn (c, _) => if (is_some o AxClass.class_of_param thy) c
haftmann@31156
   296
      then error ("Is a class parameter: " ^ string_of_const thy c) else ()) cs;
haftmann@31156
   297
    fun no_constr (c, ty) = error ("Not a datatype constructor: " ^ string_of_const thy c
haftmann@31156
   298
      ^ " :: " ^ string_of_typ thy ty);
haftmann@31156
   299
    fun last_typ c_ty ty =
haftmann@31156
   300
      let
haftmann@31156
   301
        val frees = OldTerm.typ_tfrees ty;
haftmann@31156
   302
        val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) ty
haftmann@31156
   303
          handle TYPE _ => no_constr c_ty
haftmann@31156
   304
        val _ = if has_duplicates (eq_fst (op =)) vs then no_constr c_ty else ();
haftmann@31156
   305
        val _ = if length frees <> length vs then no_constr c_ty else ();
haftmann@31156
   306
      in (tyco, vs) end;
haftmann@31156
   307
    fun ty_sorts (c, ty) =
haftmann@31156
   308
      let
haftmann@31156
   309
        val ty_decl = (Logic.unvarifyT o Sign.the_const_type thy) c;
haftmann@31156
   310
        val (tyco, _) = last_typ (c, ty) ty_decl;
haftmann@31156
   311
        val (_, vs) = last_typ (c, ty) ty;
haftmann@31156
   312
      in ((tyco, map snd vs), (c, (map fst vs, ty))) end;
haftmann@31156
   313
    fun add ((tyco', sorts'), c) ((tyco, sorts), cs) =
haftmann@31156
   314
      let
haftmann@31156
   315
        val _ = if tyco' <> tyco
haftmann@31156
   316
          then error "Different type constructors in constructor set"
haftmann@31156
   317
          else ();
haftmann@31156
   318
        val sorts'' = map2 (curry (Sorts.inter_sort (Sign.classes_of thy))) sorts' sorts
haftmann@31156
   319
      in ((tyco, sorts), c :: cs) end;
haftmann@31156
   320
    fun inst vs' (c, (vs, ty)) =
haftmann@31156
   321
      let
haftmann@31156
   322
        val the_v = the o AList.lookup (op =) (vs ~~ vs');
haftmann@31156
   323
        val ty' = map_atyps (fn TFree (v, _) => TFree (the_v v)) ty;
haftmann@31156
   324
      in (c, (fst o strip_type) ty') end;
haftmann@31156
   325
    val c' :: cs' = map ty_sorts cs;
haftmann@31156
   326
    val ((tyco, sorts), cs'') = fold add cs' (apsnd single c');
haftmann@31156
   327
    val vs = Name.names Name.context Name.aT sorts;
haftmann@31156
   328
    val cs''' = map (inst vs) cs'';
haftmann@31156
   329
  in (tyco, (vs, rev cs''')) end;
haftmann@31156
   330
haftmann@31156
   331
haftmann@31156
   332
(* code equations *)
haftmann@31156
   333
haftmann@31156
   334
exception BAD_THM of string;
haftmann@31156
   335
fun bad_thm msg = raise BAD_THM msg;
haftmann@31156
   336
fun error_thm f thm = f thm handle BAD_THM msg => error msg;
haftmann@31642
   337
fun warning_thm f thm = SOME (f thm) handle BAD_THM msg => (warning msg; NONE)
haftmann@31156
   338
fun try_thm f thm = SOME (f thm) handle BAD_THM _ => NONE;
haftmann@31156
   339
haftmann@31156
   340
fun is_linear thm =
haftmann@31156
   341
  let val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm
haftmann@31156
   342
  in not (has_duplicates (op =) ((fold o fold_aterms)
haftmann@31156
   343
    (fn Var (v, _) => cons v | _ => I) args [])) end;
haftmann@31156
   344
haftmann@31156
   345
fun gen_assert_eqn thy is_constr_head is_constr_pat (thm, proper) =
haftmann@31156
   346
  let
haftmann@31156
   347
    val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
haftmann@31156
   348
      handle TERM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm)
haftmann@31156
   349
           | THM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm);
haftmann@31156
   350
    fun vars_of t = fold_aterms (fn Var (v, _) => insert (op =) v
haftmann@31156
   351
      | Free _ => bad_thm ("Illegal free variable in equation\n"
haftmann@31156
   352
          ^ Display.string_of_thm thm)
haftmann@31156
   353
      | _ => I) t [];
haftmann@31156
   354
    fun tvars_of t = fold_term_types (fn _ =>
haftmann@31156
   355
      fold_atyps (fn TVar (v, _) => insert (op =) v
haftmann@31156
   356
        | TFree _ => bad_thm 
haftmann@31156
   357
      ("Illegal free type variable in equation\n" ^ Display.string_of_thm thm))) t [];
haftmann@31156
   358
    val lhs_vs = vars_of lhs;
haftmann@31156
   359
    val rhs_vs = vars_of rhs;
haftmann@31156
   360
    val lhs_tvs = tvars_of lhs;
haftmann@31156
   361
    val rhs_tvs = tvars_of rhs;
haftmann@31156
   362
    val _ = if null (subtract (op =) lhs_vs rhs_vs)
haftmann@31156
   363
      then ()
haftmann@31156
   364
      else bad_thm ("Free variables on right hand side of equation\n"
haftmann@31156
   365
        ^ Display.string_of_thm thm);
haftmann@31156
   366
    val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
haftmann@31156
   367
      then ()
haftmann@31156
   368
      else bad_thm ("Free type variables on right hand side of equation\n"
haftmann@31156
   369
        ^ Display.string_of_thm thm)    val (head, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
haftmann@31156
   370
    val (c, ty) = case head
haftmann@31156
   371
     of Const (c_ty as (_, ty)) => (AxClass.unoverload_const thy c_ty, ty)
haftmann@31156
   372
      | _ => bad_thm ("Equation not headed by constant\n" ^ Display.string_of_thm thm);
haftmann@31156
   373
    fun check _ (Abs _) = bad_thm
haftmann@31156
   374
          ("Abstraction on left hand side of equation\n"
haftmann@31156
   375
            ^ Display.string_of_thm thm)
haftmann@31156
   376
      | check 0 (Var _) = ()
haftmann@31156
   377
      | check _ (Var _) = bad_thm
haftmann@31156
   378
          ("Variable with application on left hand side of equation\n"
haftmann@31156
   379
            ^ Display.string_of_thm thm)
haftmann@31156
   380
      | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
haftmann@31156
   381
      | check n (Const (c_ty as (c, ty))) = if n = (length o fst o strip_type) ty
haftmann@31156
   382
          then if not proper orelse is_constr_pat (AxClass.unoverload_const thy c_ty)
haftmann@31156
   383
            then ()
haftmann@31156
   384
            else bad_thm (quote c ^ " is not a constructor, on left hand side of equation\n"
haftmann@31156
   385
              ^ Display.string_of_thm thm)
haftmann@31156
   386
          else bad_thm
haftmann@31156
   387
            ("Partially applied constant " ^ quote c ^ " on left hand side of equation\n"
haftmann@31156
   388
               ^ Display.string_of_thm thm);
haftmann@31156
   389
    val _ = map (check 0) args;
haftmann@31156
   390
    val _ = if not proper orelse is_linear thm then ()
haftmann@31156
   391
      else bad_thm ("Duplicate variables on left hand side of equation\n"
haftmann@31156
   392
        ^ Display.string_of_thm thm);
haftmann@31156
   393
    val _ = if (is_none o AxClass.class_of_param thy) c
haftmann@31156
   394
      then ()
haftmann@31156
   395
      else bad_thm ("Polymorphic constant as head in equation\n"
haftmann@31156
   396
        ^ Display.string_of_thm thm)
haftmann@31156
   397
    val _ = if not (is_constr_head c)
haftmann@31156
   398
      then ()
haftmann@31156
   399
      else bad_thm ("Constructor as head in equation\n"
haftmann@31156
   400
        ^ Display.string_of_thm thm)
haftmann@31156
   401
    val ty_decl = Sign.the_const_type thy c;
haftmann@31156
   402
    val _ = if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
haftmann@31156
   403
      then () else bad_thm ("Type\n" ^ string_of_typ thy ty
haftmann@31156
   404
           ^ "\nof equation\n"
haftmann@31156
   405
           ^ Display.string_of_thm thm
haftmann@31156
   406
           ^ "\nis incompatible with declared function type\n"
haftmann@31156
   407
           ^ string_of_typ thy ty_decl)
haftmann@31156
   408
  in (thm, proper) end;
haftmann@31156
   409
haftmann@31156
   410
fun assert_eqn thy is_constr = error_thm (gen_assert_eqn thy is_constr is_constr);
haftmann@31156
   411
haftmann@31156
   412
haftmann@31156
   413
(*those following are permissive wrt. to overloaded constants!*)
haftmann@31156
   414
haftmann@31156
   415
fun mk_eqn thy is_constr_head = error_thm (gen_assert_eqn thy is_constr_head (K true)) o
haftmann@31156
   416
  apfst (LocalDefs.meta_rewrite_rule (ProofContext.init thy));
haftmann@31156
   417
haftmann@31642
   418
fun mk_eqn_warning thy is_constr_head = Option.map (fn (thm, _) => (thm, is_linear thm))
haftmann@31642
   419
  o warning_thm (gen_assert_eqn thy is_constr_head (K true))
haftmann@31642
   420
  o rpair false o LocalDefs.meta_rewrite_rule (ProofContext.init thy);
haftmann@31642
   421
haftmann@31156
   422
fun mk_eqn_liberal thy is_constr_head = Option.map (fn (thm, _) => (thm, is_linear thm))
haftmann@31156
   423
  o try_thm (gen_assert_eqn thy is_constr_head (K true))
haftmann@31156
   424
  o rpair false o LocalDefs.meta_rewrite_rule (ProofContext.init thy);
haftmann@31156
   425
haftmann@31957
   426
fun const_typ_eqn thy thm =
haftmann@31156
   427
  let
haftmann@31957
   428
    val (c, ty) = (dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
haftmann@31156
   429
    val c' = AxClass.unoverload_const thy (c, ty);
haftmann@31156
   430
  in (c', ty) end;
haftmann@31156
   431
haftmann@31957
   432
fun typscheme_eqn thy = typscheme thy o const_typ_eqn thy;
haftmann@31957
   433
fun const_eqn thy = fst o const_typ_eqn thy;
haftmann@31156
   434
haftmann@31156
   435
haftmann@31156
   436
(* case cerificates *)
haftmann@31156
   437
haftmann@31156
   438
fun case_certificate thm =
haftmann@31156
   439
  let
haftmann@31156
   440
    val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
haftmann@31156
   441
      o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.prop_of) thm;
haftmann@31156
   442
    val _ = case head of Free _ => true
haftmann@31156
   443
      | Var _ => true
haftmann@31156
   444
      | _ => raise TERM ("case_cert", []);
haftmann@31156
   445
    val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
haftmann@31156
   446
    val (Const (case_const, _), raw_params) = strip_comb case_expr;
haftmann@31156
   447
    val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
haftmann@31156
   448
    val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
haftmann@31156
   449
    val params = map (fst o dest_Var) (nth_drop n raw_params);
haftmann@31156
   450
    fun dest_case t =
haftmann@31156
   451
      let
haftmann@31156
   452
        val (head' $ t_co, rhs) = Logic.dest_equals t;
haftmann@31156
   453
        val _ = if head' = head then () else raise TERM ("case_cert", []);
haftmann@31156
   454
        val (Const (co, _), args) = strip_comb t_co;
haftmann@31156
   455
        val (Var (param, _), args') = strip_comb rhs;
haftmann@31156
   456
        val _ = if args' = args then () else raise TERM ("case_cert", []);
haftmann@31156
   457
      in (param, co) end;
haftmann@31156
   458
    fun analyze_cases cases =
haftmann@31156
   459
      let
haftmann@31156
   460
        val co_list = fold (AList.update (op =) o dest_case) cases [];
haftmann@31156
   461
      in map (the o AList.lookup (op =) co_list) params end;
haftmann@31156
   462
    fun analyze_let t =
haftmann@31156
   463
      let
haftmann@31156
   464
        val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
haftmann@31156
   465
        val _ = if head' = head then () else raise TERM ("case_cert", []);
haftmann@31156
   466
        val _ = if arg' = arg then () else raise TERM ("case_cert", []);
haftmann@31156
   467
        val _ = if [param'] = params then () else raise TERM ("case_cert", []);
haftmann@31156
   468
      in [] end;
haftmann@31156
   469
    fun analyze (cases as [let_case]) =
haftmann@31156
   470
          (analyze_cases cases handle Bind => analyze_let let_case)
haftmann@31156
   471
      | analyze cases = analyze_cases cases;
haftmann@31156
   472
  in (case_const, (n, analyze cases)) end;
haftmann@31156
   473
haftmann@31156
   474
fun case_cert thm = case_certificate thm
haftmann@31156
   475
  handle Bind => error "bad case certificate"
haftmann@31156
   476
       | TERM _ => error "bad case certificate";
haftmann@31156
   477
haftmann@31156
   478
haftmann@25312
   479
(** code attributes **)
haftmann@25312
   480
haftmann@25312
   481
structure CodeAttr = TheoryDataFun (
wenzelm@30513
   482
  type T = (string * attribute parser) list;
haftmann@25312
   483
  val empty = [];
haftmann@25312
   484
  val copy = I;
haftmann@25312
   485
  val extend = I;
haftmann@26970
   486
  fun merge _ = AList.merge (op = : string * string -> bool) (K true);
haftmann@25312
   487
);
haftmann@24219
   488
haftmann@25312
   489
fun add_attribute (attr as (name, _)) =
haftmann@25312
   490
  let
haftmann@28562
   491
    fun add_parser ("", parser) attrs = attrs |> rev |> AList.update (op =) ("", parser) |> rev
haftmann@25312
   492
      | add_parser (name, parser) attrs = (name, Args.$$$ name |-- parser) :: attrs;
haftmann@28562
   493
  in CodeAttr.map (fn attrs => if not (name = "") andalso AList.defined (op =) attrs name
haftmann@28562
   494
    then error ("Code attribute " ^ name ^ " already declared") else add_parser attr attrs)
haftmann@25312
   495
  end;
haftmann@25312
   496
wenzelm@30722
   497
val _ = Context.>> (Context.map_theory
wenzelm@30722
   498
  (Attrib.setup (Binding.name "code")
wenzelm@30722
   499
    (Scan.peek (fn context =>
wenzelm@30722
   500
      List.foldr op || Scan.fail (map snd (CodeAttr.get (Context.theory_of context)))))
wenzelm@30722
   501
    "declare theorems for code generation"));
wenzelm@30722
   502
haftmann@25312
   503
haftmann@25312
   504
haftmann@28143
   505
(** logical and syntactical specification of executable code **)
haftmann@24219
   506
haftmann@30023
   507
(* code equations *)
haftmann@28695
   508
wenzelm@28971
   509
type eqns = bool * (thm * bool) list lazy;
haftmann@31088
   510
  (*default flag, theorems with proper flag (perhaps lazy)*)
haftmann@24219
   511
wenzelm@28673
   512
fun pretty_lthms ctxt r = case Lazy.peek r
wenzelm@28672
   513
 of SOME thms => map (ProofContext.pretty_thm ctxt o fst) (Exn.release thms)
haftmann@24219
   514
  | NONE => [Pretty.str "[...]"];
haftmann@24219
   515
haftmann@24219
   516
fun certificate thy f r =
wenzelm@28673
   517
  case Lazy.peek r
wenzelm@28673
   518
   of SOME thms => (Lazy.value o f thy) (Exn.release thms)
haftmann@24844
   519
    | NONE => let
haftmann@24844
   520
        val thy_ref = Theory.check_thy thy;
wenzelm@28673
   521
      in Lazy.lazy (fn () => (f (Theory.deref thy_ref) o Lazy.force) r) end;
haftmann@24219
   522
haftmann@31088
   523
fun add_drop_redundant thy (thm, proper) thms =
haftmann@24219
   524
  let
haftmann@31152
   525
    val args_of = snd o strip_comb o map_types Type.strip_sorts
haftmann@31152
   526
      o fst o Logic.dest_equals o Thm.plain_prop_of;
haftmann@24219
   527
    val args = args_of thm;
haftmann@28403
   528
    val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
haftmann@28350
   529
    fun matches_args args' = length args <= length args' andalso
haftmann@28403
   530
      Pattern.matchess thy (args, (map incr_idx o curry Library.take (length args)) args');
haftmann@31088
   531
    fun drop (thm', proper') = if (proper orelse not proper')
haftmann@28359
   532
      andalso matches_args (args_of thm') then 
haftmann@30023
   533
        (warning ("Code generator: dropping redundant code equation\n" ^ Display.string_of_thm thm'); true)
haftmann@28350
   534
      else false;
haftmann@31088
   535
  in (thm, proper) :: filter_out drop thms end;
haftmann@24219
   536
wenzelm@28673
   537
fun add_thm thy _ thm (false, thms) = (false, Lazy.map_force (add_drop_redundant thy thm) thms)
wenzelm@28673
   538
  | add_thm thy true thm (true, thms) = (true, Lazy.map_force (fn thms => thms @ [thm]) thms)
wenzelm@28673
   539
  | add_thm thy false thm (true, thms) = (false, Lazy.value [thm]);
haftmann@24219
   540
haftmann@28143
   541
fun add_lthms lthms _ = (false, lthms);
haftmann@25312
   542
wenzelm@28673
   543
fun del_thm thm = (apsnd o Lazy.map_force) (remove (eq_fst Thm.eq_thm_prop) (thm, true));
haftmann@25312
   544
haftmann@28143
   545
haftmann@28143
   546
(* specification data *)
haftmann@28143
   547
haftmann@24219
   548
datatype spec = Spec of {
haftmann@28695
   549
  concluded_history: bool,
haftmann@28695
   550
  eqns: ((bool * eqns) * (serial * eqns) list) Symtab.table
haftmann@28695
   551
    (*with explicit history*),
haftmann@28695
   552
  dtyps: ((serial * ((string * sort) list * (string * typ list) list)) list) Symtab.table
haftmann@28695
   553
    (*with explicit history*),
haftmann@30076
   554
  cases: (int * (int * string list)) Symtab.table * unit Symtab.table
haftmann@24219
   555
};
haftmann@24219
   556
haftmann@31599
   557
fun make_spec ((concluded_history, eqns), (dtyps, cases)) =
haftmann@28695
   558
  Spec { concluded_history = concluded_history, eqns = eqns, dtyps = dtyps, cases = cases };
haftmann@28695
   559
fun map_spec f (Spec { concluded_history = concluded_history, eqns = eqns,
haftmann@28695
   560
  dtyps = dtyps, cases = cases }) =
haftmann@31599
   561
  make_spec (f ((concluded_history, eqns), (dtyps, cases)));
haftmann@28695
   562
fun merge_spec (Spec { concluded_history = _, eqns = eqns1, dtyps = dtyps1, cases = (cases1, undefs1) },
haftmann@28695
   563
  Spec { concluded_history = _, eqns = eqns2, dtyps = dtyps2, cases = (cases2, undefs2) }) =
haftmann@24219
   564
  let
haftmann@28695
   565
    fun merge_eqns ((_, history1), (_, history2)) =
haftmann@28695
   566
      let
haftmann@31125
   567
        val raw_history = AList.merge (op = : serial * serial -> bool)
haftmann@31125
   568
          (K true) (history1, history2)
haftmann@28695
   569
        val filtered_history = filter_out (fst o snd) raw_history
haftmann@28695
   570
        val history = if null filtered_history
haftmann@28695
   571
          then raw_history else filtered_history;
haftmann@28695
   572
      in ((false, (snd o hd) history), history) end;
haftmann@28695
   573
    val eqns = Symtab.join (K merge_eqns) (eqns1, eqns2);
haftmann@28695
   574
    val dtyps = Symtab.join (K (AList.merge (op =) (K true))) (dtyps1, dtyps2);
haftmann@27609
   575
    val cases = (Symtab.merge (K true) (cases1, cases2),
haftmann@27609
   576
      Symtab.merge (K true) (undefs1, undefs2));
haftmann@31599
   577
  in make_spec ((false, eqns), (dtyps, cases)) end;
haftmann@24219
   578
haftmann@25312
   579
haftmann@28143
   580
(* code setup data *)
haftmann@28143
   581
haftmann@31125
   582
fun the_spec (Spec x) = x;
haftmann@31599
   583
fun the_eqns (Spec { eqns, ... }) = eqns;
haftmann@31599
   584
fun the_dtyps (Spec { dtyps, ... }) = dtyps;
haftmann@31599
   585
fun the_cases (Spec { cases, ... }) = cases;
haftmann@31599
   586
fun history_concluded (Spec { concluded_history, ... }) = concluded_history;
haftmann@31125
   587
val map_concluded_history = map_spec o apfst o apfst;
haftmann@31125
   588
val map_eqns = map_spec o apfst o apsnd;
haftmann@31125
   589
val map_dtyps = map_spec o apsnd o apfst;
haftmann@31125
   590
val map_cases = map_spec o apsnd o apsnd;
haftmann@24219
   591
haftmann@24219
   592
haftmann@24219
   593
(* data slots dependent on executable content *)
haftmann@24219
   594
haftmann@24219
   595
(*private copy avoids potential conflict of table exceptions*)
haftmann@24219
   596
structure Datatab = TableFun(type key = int val ord = int_ord);
haftmann@24219
   597
haftmann@24219
   598
local
haftmann@24219
   599
haftmann@24219
   600
type kind = {
haftmann@24219
   601
  empty: Object.T,
haftmann@27609
   602
  purge: theory -> string list -> Object.T -> Object.T
haftmann@24219
   603
};
haftmann@24219
   604
haftmann@24219
   605
val kinds = ref (Datatab.empty: kind Datatab.table);
haftmann@24219
   606
val kind_keys = ref ([]: serial list);
haftmann@24219
   607
haftmann@24219
   608
fun invoke f k = case Datatab.lookup (! kinds) k
haftmann@24219
   609
 of SOME kind => f kind
haftmann@24219
   610
  | NONE => sys_error "Invalid code data identifier";
haftmann@24219
   611
haftmann@24219
   612
in
haftmann@24219
   613
haftmann@27609
   614
fun declare_data empty purge =
haftmann@24219
   615
  let
haftmann@24219
   616
    val k = serial ();
haftmann@27609
   617
    val kind = {empty = empty, purge = purge};
haftmann@24219
   618
    val _ = change kinds (Datatab.update (k, kind));
haftmann@24219
   619
    val _ = change kind_keys (cons k);
haftmann@24219
   620
  in k end;
haftmann@24219
   621
haftmann@27609
   622
fun invoke_init k = invoke (fn kind => #empty kind) k;
haftmann@24219
   623
haftmann@27609
   624
fun invoke_purge_all thy cs =
haftmann@24219
   625
  fold (fn k => Datatab.map_entry k
haftmann@27609
   626
    (invoke (fn kind => #purge kind thy cs) k)) (! kind_keys);
haftmann@24219
   627
haftmann@24219
   628
end; (*local*)
haftmann@24219
   629
haftmann@24219
   630
haftmann@25312
   631
(** theory store **)
haftmann@24219
   632
haftmann@24219
   633
local
haftmann@24219
   634
haftmann@24219
   635
type data = Object.T Datatab.table;
haftmann@27609
   636
val empty_data = Datatab.empty : data;
haftmann@24219
   637
haftmann@31125
   638
structure Code_Data = TheoryDataFun
haftmann@24219
   639
(
haftmann@31125
   640
  type T = spec * data ref;
haftmann@31599
   641
  val empty = (make_spec ((false, Symtab.empty),
haftmann@31599
   642
    (Symtab.empty, (Symtab.empty, Symtab.empty))), ref empty_data);
haftmann@31125
   643
  fun copy (spec, data) = (spec, ref (! data));
haftmann@24219
   644
  val extend = copy;
haftmann@31125
   645
  fun merge pp ((spec1, data1), (spec2, data2)) =
haftmann@31125
   646
    (merge_spec (spec1, spec2), ref empty_data);
haftmann@24219
   647
);
haftmann@24219
   648
haftmann@31125
   649
fun thy_data f thy = f ((snd o Code_Data.get) thy);
haftmann@24219
   650
haftmann@24219
   651
fun get_ensure_init kind data_ref =
haftmann@24219
   652
  case Datatab.lookup (! data_ref) kind
haftmann@24219
   653
   of SOME x => x
haftmann@27609
   654
    | NONE => let val y = invoke_init kind
haftmann@24219
   655
        in (change data_ref (Datatab.update (kind, y)); y) end;
haftmann@24219
   656
haftmann@24219
   657
in
haftmann@24219
   658
haftmann@24219
   659
(* access to executable content *)
haftmann@24219
   660
haftmann@31125
   661
val the_exec = fst o Code_Data.get;
haftmann@24219
   662
haftmann@27983
   663
fun complete_class_params thy cs =
haftmann@27983
   664
  fold (fn c => case AxClass.inst_of_param thy c
haftmann@27983
   665
   of NONE => insert (op =) c
haftmann@27983
   666
    | SOME (c', _) => insert (op =) c' #> insert (op =) c) cs [];
haftmann@27983
   667
haftmann@24219
   668
fun map_exec_purge touched f thy =
haftmann@31125
   669
  Code_Data.map (fn (exec, data) => (f exec, ref (case touched
haftmann@27983
   670
   of SOME cs => invoke_purge_all thy (complete_class_params thy cs) (! data)
haftmann@27609
   671
    | NONE => empty_data))) thy;
haftmann@24219
   672
haftmann@31125
   673
val purge_data = (Code_Data.map o apsnd) (K (ref empty_data));
haftmann@27675
   674
haftmann@24219
   675
haftmann@28695
   676
(* tackling equation history *)
haftmann@28695
   677
haftmann@28695
   678
fun get_eqns thy c =
haftmann@28695
   679
  Symtab.lookup ((the_eqns o the_exec) thy) c
haftmann@28695
   680
  |> Option.map (Lazy.force o snd o snd o fst)
haftmann@28695
   681
  |> these;
haftmann@28695
   682
haftmann@31599
   683
fun continue_history thy = if (history_concluded o the_exec) thy
haftmann@28695
   684
  then thy
haftmann@31125
   685
    |> (Code_Data.map o apfst o map_concluded_history) (K false)
haftmann@28695
   686
    |> SOME
haftmann@28695
   687
  else NONE;
haftmann@28695
   688
haftmann@31599
   689
fun conclude_history thy = if (history_concluded o the_exec) thy
haftmann@28695
   690
  then NONE
haftmann@28695
   691
  else thy
haftmann@31125
   692
    |> (Code_Data.map o apfst)
haftmann@28695
   693
        ((map_eqns o Symtab.map) (fn ((changed, current), history) =>
haftmann@28695
   694
          ((false, current),
haftmann@28695
   695
            if changed then (serial (), current) :: history else history))
haftmann@28695
   696
        #> map_concluded_history (K true))
haftmann@28695
   697
    |> SOME;
haftmann@28695
   698
haftmann@31125
   699
val _ = Context.>> (Context.map_theory (Code_Data.init
haftmann@28695
   700
  #> Theory.at_begin continue_history
haftmann@28695
   701
  #> Theory.at_end conclude_history));
haftmann@28695
   702
haftmann@28695
   703
haftmann@24219
   704
(* access to data dependent on abstract executable content *)
haftmann@24219
   705
haftmann@24219
   706
fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
haftmann@24219
   707
haftmann@24219
   708
fun change_data (kind, mk, dest) =
haftmann@24219
   709
  let
haftmann@24219
   710
    fun chnge data_ref f =
haftmann@24219
   711
      let
haftmann@24219
   712
        val data = get_ensure_init kind data_ref;
haftmann@24219
   713
        val data' = f (dest data);
haftmann@24219
   714
      in (change data_ref (Datatab.update (kind, mk data')); data') end;
haftmann@24219
   715
  in thy_data chnge end;
haftmann@24219
   716
haftmann@24219
   717
fun change_yield_data (kind, mk, dest) =
haftmann@24219
   718
  let
haftmann@24219
   719
    fun chnge data_ref f =
haftmann@24219
   720
      let
haftmann@24219
   721
        val data = get_ensure_init kind data_ref;
haftmann@24219
   722
        val (x, data') = f (dest data);
haftmann@24219
   723
      in (x, (change data_ref (Datatab.update (kind, mk data')); data')) end;
haftmann@24219
   724
  in thy_data chnge end;
haftmann@24219
   725
haftmann@24219
   726
end; (*local*)
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@28368
   732
    fun pretty_eqn (s, (_, lthms)) =
haftmann@24219
   733
      (Pretty.block o Pretty.fbreaks) (
haftmann@28143
   734
        Pretty.str s :: pretty_lthms ctxt lthms
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@28368
   764
        :: (Pretty.fbreaks o map pretty_eqn) 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@24219
   775
(** theorem transformation and certification **)
haftmann@24219
   776
haftmann@28423
   777
fun common_typ_eqns thy [] = []
haftmann@28423
   778
  | common_typ_eqns thy [thm] = [thm]
haftmann@28423
   779
  | common_typ_eqns thy (thms as thm :: _) = (*FIXME is too general*)
haftmann@24219
   780
      let
haftmann@24219
   781
        fun incr_thm thm max =
haftmann@24219
   782
          let
haftmann@24219
   783
            val thm' = incr_indexes max thm;
haftmann@24219
   784
            val max' = Thm.maxidx_of thm' + 1;
haftmann@24219
   785
          in (thm', max') end;
haftmann@24219
   786
        val (thms', maxidx) = fold_map incr_thm thms 0;
haftmann@31957
   787
        val ty1 :: tys = map (snd o const_typ_eqn thy) thms';
haftmann@24219
   788
        fun unify ty env = Sign.typ_unify thy (ty1, ty) env
haftmann@24219
   789
          handle Type.TUNIFY =>
haftmann@30023
   790
            error ("Type unificaton failed, while unifying code equations\n"
haftmann@24219
   791
            ^ (cat_lines o map Display.string_of_thm) thms
haftmann@24219
   792
            ^ "\nwith types\n"
haftmann@31156
   793
            ^ (cat_lines o map (string_of_typ thy)) (ty1 :: tys));
haftmann@24219
   794
        val (env, _) = fold unify tys (Vartab.empty, maxidx)
haftmann@24219
   795
        val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
haftmann@24219
   796
          cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
haftmann@24219
   797
      in map (Thm.instantiate (instT, [])) thms' end;
haftmann@24219
   798
haftmann@24219
   799
haftmann@24219
   800
(** interfaces and attributes **)
haftmann@24219
   801
haftmann@24423
   802
fun get_datatype thy tyco =
haftmann@28695
   803
  case these (Symtab.lookup ((the_dtyps o the_exec) thy) tyco)
haftmann@28695
   804
   of (_, spec) :: _ => spec
haftmann@28695
   805
    | [] => Sign.arity_number thy tyco
wenzelm@24848
   806
        |> Name.invents Name.context Name.aT
haftmann@24423
   807
        |> map (rpair [])
haftmann@24423
   808
        |> rpair [];
haftmann@24423
   809
haftmann@24423
   810
fun get_datatype_of_constr thy c =
haftmann@24423
   811
  case (snd o strip_type o Sign.the_const_type thy) c
haftmann@28695
   812
   of Type (tyco, _) => if member (op =) ((map fst o snd o get_datatype thy) tyco) c
haftmann@24423
   813
       then SOME tyco else NONE
haftmann@24423
   814
    | _ => NONE;
haftmann@24423
   815
haftmann@31088
   816
fun is_constr thy = is_some o get_datatype_of_constr thy;
haftmann@31088
   817
haftmann@31156
   818
val assert_eqn = fn thy => assert_eqn thy (is_constr thy);
haftmann@28708
   819
haftmann@31090
   820
fun assert_eqns_const thy c eqns =
haftmann@28708
   821
  let
haftmann@31156
   822
    fun cert (eqn as (thm, _)) = if c = const_eqn thy thm
haftmann@30023
   823
      then eqn else error ("Wrong head of code equation,\nexpected constant "
haftmann@31156
   824
        ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm thm)
haftmann@31090
   825
  in map (cert o assert_eqn thy) eqns end;
haftmann@28708
   826
haftmann@28695
   827
fun change_eqns delete c f = (map_exec_purge (SOME [c]) o map_eqns
haftmann@28695
   828
  o (if delete then Symtab.map_entry c else Symtab.map_default (c, ((false, (true, Lazy.value [])), [])))
haftmann@28695
   829
    o apfst) (fn (_, eqns) => (true, f eqns));
haftmann@24844
   830
haftmann@31090
   831
fun gen_add_eqn default (eqn as (thm, _)) thy =
haftmann@31156
   832
  let val c = const_eqn thy thm
haftmann@31090
   833
  in change_eqns false c (add_thm thy default eqn) thy end;
haftmann@31090
   834
haftmann@31090
   835
fun add_eqn thm thy =
haftmann@31156
   836
  gen_add_eqn false (mk_eqn thy (is_constr thy) (thm, true)) thy;
haftmann@31090
   837
haftmann@31642
   838
fun add_warning_eqn thm thy =
haftmann@31642
   839
  case mk_eqn_warning thy (is_constr thy) thm
haftmann@31642
   840
   of SOME eqn => gen_add_eqn false eqn thy
haftmann@31642
   841
    | NONE => thy;
haftmann@31642
   842
haftmann@31090
   843
fun add_default_eqn thm thy =
haftmann@31156
   844
  case mk_eqn_liberal thy (is_constr thy) thm
haftmann@31090
   845
   of SOME eqn => gen_add_eqn true eqn thy
haftmann@24624
   846
    | NONE => thy;
haftmann@24624
   847
haftmann@31090
   848
fun add_nbe_eqn thm thy =
haftmann@31156
   849
  gen_add_eqn false (mk_eqn thy (is_constr thy) (thm, false)) thy;
haftmann@26021
   850
haftmann@28368
   851
fun add_eqnl (c, lthms) thy =
haftmann@24219
   852
  let
haftmann@31090
   853
    val lthms' = certificate thy (fn thy => assert_eqns_const thy c) lthms;
haftmann@28695
   854
  in change_eqns false c (add_lthms lthms') thy end;
haftmann@24219
   855
haftmann@28703
   856
val add_default_eqn_attribute = Thm.declaration_attribute
haftmann@28703
   857
  (fn thm => Context.mapping (add_default_eqn thm) I);
haftmann@28703
   858
val add_default_eqn_attrib = Attrib.internal (K add_default_eqn_attribute);
haftmann@24219
   859
haftmann@31156
   860
fun del_eqn thm thy = case mk_eqn_liberal thy (is_constr thy) thm
haftmann@31156
   861
 of SOME (thm, _) => change_eqns true (const_eqn thy thm) (del_thm thm) thy
haftmann@28695
   862
  | NONE => thy;
haftmann@28695
   863
haftmann@28695
   864
fun del_eqns c = change_eqns true c (K (false, Lazy.value []));
haftmann@28695
   865
haftmann@30076
   866
fun get_case_scheme thy = Symtab.lookup ((fst o the_cases o the_exec) thy);
haftmann@28695
   867
haftmann@31890
   868
val undefineds = Symtab.keys o snd o the_cases o the_exec;
haftmann@28695
   869
haftmann@25485
   870
structure TypeInterpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
haftmann@25462
   871
haftmann@24423
   872
fun add_datatype raw_cs thy =
haftmann@24219
   873
  let
haftmann@25597
   874
    val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
haftmann@31156
   875
    val (tyco, vs_cos) = constrset_of_consts thy cs;
haftmann@30076
   876
    val old_cs = (map fst o snd o get_datatype thy) tyco;
haftmann@30076
   877
    fun drop_outdated_cases cases = fold Symtab.delete_safe
haftmann@30076
   878
      (Symtab.fold (fn (c, (_, (_, cos))) =>
haftmann@30076
   879
        if exists (member (op =) old_cs) cos
haftmann@30076
   880
          then insert (op =) c else I) cases []) cases;
haftmann@24219
   881
  in
haftmann@24219
   882
    thy
haftmann@31091
   883
    |> fold (del_eqns o fst) cs
haftmann@28703
   884
    |> map_exec_purge NONE
haftmann@28695
   885
        ((map_dtyps o Symtab.map_default (tyco, [])) (cons (serial (), vs_cos))
haftmann@30076
   886
        #> (map_cases o apfst) drop_outdated_cases)
haftmann@25485
   887
    |> TypeInterpretation.data (tyco, serial ())
haftmann@24219
   888
  end;
haftmann@24219
   889
haftmann@25485
   890
fun type_interpretation f =  TypeInterpretation.interpretation
haftmann@25485
   891
  (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
haftmann@25485
   892
haftmann@24423
   893
fun add_datatype_cmd raw_cs thy =
haftmann@24423
   894
  let
haftmann@31156
   895
    val cs = map (read_bare_const thy) raw_cs;
haftmann@24423
   896
  in add_datatype cs thy end;
haftmann@24219
   897
haftmann@24844
   898
fun add_case thm thy =
haftmann@24844
   899
  let
haftmann@31156
   900
    val (c, (k, case_pats)) = case_cert thm;
haftmann@31088
   901
    val _ = case filter_out (is_constr thy) case_pats
haftmann@30076
   902
     of [] => ()
haftmann@30076
   903
      | cs => error ("Non-constructor(s) in case certificate: " ^ commas (map quote cs));
haftmann@30076
   904
    val entry = (1 + Int.max (1, length case_pats), (k, case_pats))
haftmann@30076
   905
  in (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update (c, entry)) thy end;
haftmann@24844
   906
haftmann@24844
   907
fun add_undefined c thy =
haftmann@24844
   908
  (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
haftmann@24844
   909
wenzelm@26463
   910
val _ = Context.>> (Context.map_theory
haftmann@24219
   911
  (let
haftmann@24219
   912
    fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
haftmann@24219
   913
    fun add_simple_attribute (name, f) =
haftmann@24219
   914
      add_attribute (name, Scan.succeed (mk_attribute f));
haftmann@24219
   915
    fun add_del_attribute (name, (add, del)) =
haftmann@24219
   916
      add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
haftmann@24219
   917
        || Scan.succeed (mk_attribute add))
haftmann@24219
   918
  in
haftmann@25462
   919
    TypeInterpretation.init
haftmann@31642
   920
    #> add_del_attribute ("", (add_warning_eqn, del_eqn))
haftmann@31088
   921
    #> add_simple_attribute ("nbe", add_nbe_eqn)
wenzelm@26463
   922
  end));
haftmann@24219
   923
haftmann@28423
   924
fun these_eqns thy c =
haftmann@31088
   925
  get_eqns thy c
haftmann@31088
   926
  |> (map o apfst) (Thm.transfer thy)
haftmann@31125
   927
  |> burrow_fst (common_typ_eqns thy);
haftmann@24219
   928
haftmann@31642
   929
fun all_eqns thy =
haftmann@31642
   930
  Symtab.dest ((the_eqns o the_exec) thy)
haftmann@31642
   931
  |> maps (Lazy.force o snd o snd o fst o snd);
haftmann@31642
   932
haftmann@24219
   933
end; (*struct*)
haftmann@24219
   934
haftmann@24219
   935
haftmann@24219
   936
(** type-safe interfaces for data depedent on executable content **)
haftmann@24219
   937
haftmann@24219
   938
functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
haftmann@24219
   939
struct
haftmann@24219
   940
haftmann@24219
   941
type T = Data.T;
haftmann@24219
   942
exception Data of T;
haftmann@24219
   943
fun dest (Data x) = x
haftmann@24219
   944
haftmann@24219
   945
val kind = Code.declare_data (Data Data.empty)
haftmann@27609
   946
  (fn thy => fn cs => fn Data x => Data (Data.purge thy cs x));
haftmann@24219
   947
haftmann@24219
   948
val data_op = (kind, Data, dest);
haftmann@24219
   949
haftmann@24219
   950
val get = Code.get_data data_op;
haftmann@24219
   951
val change = Code.change_data data_op;
haftmann@24219
   952
fun change_yield thy = Code.change_yield_data data_op thy;
haftmann@24219
   953
haftmann@24219
   954
end;
haftmann@24219
   955
haftmann@28143
   956
structure Code : CODE = struct open Code; end;