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