src/HOL/Tools/datatype_package.ML
author wenzelm
Thu Mar 27 14:41:09 2008 +0100 (2008-03-27)
changeset 26424 a6cad32a27b0
parent 26343 0dd2eab7b296
child 26496 49ae9456eba9
permissions -rw-r--r--
eliminated theory ProtoPure;
berghofe@5177
     1
(*  Title:      HOL/Tools/datatype_package.ML
berghofe@5177
     2
    ID:         $Id$
wenzelm@11539
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@5177
     4
wenzelm@6360
     5
Datatype package for Isabelle/HOL.
berghofe@5177
     6
*)
berghofe@5177
     7
wenzelm@6360
     8
signature BASIC_DATATYPE_PACKAGE =
wenzelm@6360
     9
sig
wenzelm@6360
    10
  val induct_tac : string -> int -> tactic
nipkow@9747
    11
  val induct_thm_tac : thm -> string -> int -> tactic
wenzelm@8437
    12
  val case_tac : string -> int -> tactic
berghofe@7015
    13
  val distinct_simproc : simproc
wenzelm@6360
    14
end;
wenzelm@6360
    15
berghofe@5177
    16
signature DATATYPE_PACKAGE =
berghofe@5177
    17
sig
wenzelm@6360
    18
  include BASIC_DATATYPE_PACKAGE
berghofe@5661
    19
  val quiet_mode : bool ref
haftmann@24699
    20
  val add_datatype_i : bool -> bool -> string list -> (string list * bstring * mixfix *
haftmann@24699
    21
    (bstring * typ list * mixfix) list) list -> theory ->
haftmann@24699
    22
      {distinct : thm list list,
haftmann@24699
    23
       inject : thm list list,
haftmann@24699
    24
       exhaustion : thm list,
haftmann@24699
    25
       rec_thms : thm list,
haftmann@24699
    26
       case_thms : thm list list,
haftmann@24699
    27
       split_thms : (thm * thm) list,
haftmann@24699
    28
       induction : thm,
haftmann@24699
    29
       simps : thm list} * theory
berghofe@5661
    30
  val add_datatype : bool -> string list -> (string list * bstring * mixfix *
haftmann@18008
    31
    (bstring * string list * mixfix) list) list -> theory ->
berghofe@5177
    32
      {distinct : thm list list,
berghofe@5177
    33
       inject : thm list list,
berghofe@5177
    34
       exhaustion : thm list,
berghofe@5177
    35
       rec_thms : thm list,
berghofe@5177
    36
       case_thms : thm list list,
berghofe@5177
    37
       split_thms : (thm * thm) list,
berghofe@5177
    38
       induction : thm,
haftmann@18008
    39
       simps : thm list} * theory
wenzelm@18728
    40
  val rep_datatype_i : string list option -> (thm list * attribute list) list list ->
wenzelm@18728
    41
    (thm list * attribute list) list list -> (thm list * attribute list) ->
haftmann@18008
    42
    theory ->
wenzelm@6385
    43
      {distinct : thm list list,
wenzelm@6385
    44
       inject : thm list list,
wenzelm@6385
    45
       exhaustion : thm list,
wenzelm@6385
    46
       rec_thms : thm list,
wenzelm@6385
    47
       case_thms : thm list list,
wenzelm@6385
    48
       split_thms : (thm * thm) list,
wenzelm@6385
    49
       induction : thm,
haftmann@18008
    50
       simps : thm list} * theory
wenzelm@26336
    51
  val rep_datatype : string list option -> (Facts.ref * Attrib.src list) list list ->
wenzelm@26336
    52
    (Facts.ref * Attrib.src list) list list -> Facts.ref * Attrib.src list -> theory ->
berghofe@5177
    53
      {distinct : thm list list,
berghofe@5177
    54
       inject : thm list list,
berghofe@5177
    55
       exhaustion : thm list,
berghofe@5177
    56
       rec_thms : thm list,
berghofe@5177
    57
       case_thms : thm list list,
berghofe@5177
    58
       split_thms : (thm * thm) list,
berghofe@5177
    59
       induction : thm,
haftmann@18008
    60
       simps : thm list} * theory
berghofe@5177
    61
  val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
haftmann@19346
    62
  val get_datatype : theory -> string -> DatatypeAux.datatype_info option
haftmann@19346
    63
  val the_datatype : theory -> string -> DatatypeAux.datatype_info
haftmann@25537
    64
  val the_datatype_spec : theory -> string -> (string * sort) list * (string * typ list) list
berghofe@22777
    65
  val datatype_of_constr : theory -> string -> DatatypeAux.datatype_info option
berghofe@22777
    66
  val datatype_of_case : theory -> string -> DatatypeAux.datatype_info option
haftmann@19346
    67
  val get_datatype_constrs : theory -> string -> (string * typ) list option
haftmann@26267
    68
  val construction_interpretation: theory
haftmann@26267
    69
    -> { atom: typ -> 'a, dtyp: string -> 'a, rtyp: string -> 'a list -> 'a }
haftmann@26267
    70
    -> (string * Term.sort) list -> string list
haftmann@26267
    71
    -> (string * (string * 'a list) list) list
wenzelm@24711
    72
  val interpretation: (string list -> theory -> theory) -> theory -> theory
wenzelm@6441
    73
  val print_datatypes : theory -> unit
berghofe@22777
    74
  val make_case :  Proof.context -> bool -> string list -> term ->
berghofe@22777
    75
    (term * term) list -> term * (term * (int * bool)) list
berghofe@22777
    76
  val strip_case: Proof.context -> bool ->
berghofe@22777
    77
    term -> (term * (term * term) list) option
wenzelm@18708
    78
  val setup: theory -> theory
berghofe@5177
    79
end;
berghofe@5177
    80
berghofe@5177
    81
structure DatatypePackage : DATATYPE_PACKAGE =
berghofe@5177
    82
struct
berghofe@5177
    83
berghofe@5177
    84
open DatatypeAux;
berghofe@5177
    85
berghofe@5661
    86
val quiet_mode = quiet_mode;
berghofe@5661
    87
wenzelm@6360
    88
wenzelm@22846
    89
(* theory data *)
berghofe@5177
    90
wenzelm@16430
    91
structure DatatypesData = TheoryDataFun
wenzelm@22846
    92
(
berghofe@22777
    93
  type T =
berghofe@22777
    94
    {types: datatype_info Symtab.table,
berghofe@22777
    95
     constrs: datatype_info Symtab.table,
berghofe@22777
    96
     cases: datatype_info Symtab.table};
berghofe@5177
    97
berghofe@22777
    98
  val empty =
berghofe@22777
    99
    {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
wenzelm@6556
   100
  val copy = I;
wenzelm@16430
   101
  val extend = I;
berghofe@22777
   102
  fun merge _
berghofe@22777
   103
    ({types = types1, constrs = constrs1, cases = cases1},
berghofe@22777
   104
     {types = types2, constrs = constrs2, cases = cases2}) =
berghofe@22777
   105
    {types = Symtab.merge (K true) (types1, types2),
berghofe@22777
   106
     constrs = Symtab.merge (K true) (constrs1, constrs2),
berghofe@22777
   107
     cases = Symtab.merge (K true) (cases1, cases2)};
wenzelm@22846
   108
);
berghofe@5177
   109
berghofe@22777
   110
val get_datatypes = #types o DatatypesData.get;
berghofe@22777
   111
val map_datatypes = DatatypesData.map;
wenzelm@22846
   112
wenzelm@22846
   113
fun print_datatypes thy =
wenzelm@22846
   114
  Pretty.writeln (Pretty.strs ("datatypes:" ::
wenzelm@22846
   115
    map #1 (NameSpace.extern_table (Sign.type_space thy, get_datatypes thy))));
berghofe@5177
   116
berghofe@5177
   117
berghofe@5177
   118
(** theory information about datatypes **)
berghofe@5177
   119
berghofe@22777
   120
fun put_dt_infos (dt_infos : (string * datatype_info) list) =
berghofe@22777
   121
  map_datatypes (fn {types, constrs, cases} =>
berghofe@22777
   122
    {types = fold Symtab.update dt_infos types,
berghofe@22777
   123
     constrs = fold Symtab.update
berghofe@22777
   124
       (maps (fn (_, info as {descr, index, ...}) => map (rpair info o fst)
berghofe@22777
   125
          (#3 (the (AList.lookup op = descr index)))) dt_infos) constrs,
berghofe@22777
   126
     cases = fold Symtab.update
berghofe@22777
   127
       (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)
berghofe@22777
   128
       cases});
berghofe@22777
   129
haftmann@19346
   130
val get_datatype = Symtab.lookup o get_datatypes;
berghofe@5177
   131
haftmann@19346
   132
fun the_datatype thy name = (case get_datatype thy name of
skalberg@15531
   133
      SOME info => info
skalberg@15531
   134
    | NONE => error ("Unknown datatype " ^ quote name));
berghofe@5177
   135
berghofe@22777
   136
val datatype_of_constr = Symtab.lookup o #constrs o DatatypesData.get;
berghofe@22777
   137
val datatype_of_case = Symtab.lookup o #cases o DatatypesData.get;
berghofe@22777
   138
haftmann@19346
   139
fun get_datatype_descr thy dtco =
haftmann@19346
   140
  get_datatype thy dtco
wenzelm@24711
   141
  |> Option.map (fn info as { descr, index, ... } =>
haftmann@19346
   142
       (info, (((fn SOME (_, dtys, cos) => (dtys, cos)) o AList.lookup (op =) descr) index)));
berghofe@7015
   143
haftmann@25537
   144
fun the_datatype_spec thy dtco =
haftmann@18518
   145
  let
haftmann@26093
   146
    val info as { descr, index, sorts = raw_sorts, ... } = the_datatype thy dtco;
haftmann@26093
   147
    val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr index;
haftmann@26093
   148
    val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
haftmann@26093
   149
      o DatatypeAux.dest_DtTFree) dtys;
haftmann@26093
   150
    val cos = map
haftmann@26093
   151
      (fn (co, tys) => (co, map (DatatypeAux.typ_of_dtyp descr sorts) tys)) raw_cos;
haftmann@26093
   152
  in (sorts, cos) end;
haftmann@18518
   153
haftmann@19346
   154
fun get_datatype_constrs thy dtco =
haftmann@25537
   155
  case try (the_datatype_spec thy) dtco
haftmann@19346
   156
   of SOME (sorts, cos) =>
haftmann@19346
   157
        let
haftmann@19346
   158
          fun subst (v, sort) = TVar ((v, 0), sort);
haftmann@19346
   159
          fun subst_ty (TFree v) = subst v
haftmann@19346
   160
            | subst_ty ty = ty;
haftmann@19346
   161
          val dty = Type (dtco, map subst sorts);
haftmann@19346
   162
          fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
haftmann@19346
   163
        in SOME (map mk_co cos) end
haftmann@19346
   164
    | NONE => NONE;
haftmann@18518
   165
haftmann@26267
   166
fun construction_interpretation thy { atom, dtyp, rtyp } sorts tycos =
haftmann@26267
   167
  let
haftmann@26267
   168
    val descr = (#descr o the_datatype thy o hd) tycos;
haftmann@26267
   169
    val k = length tycos;
haftmann@26267
   170
    val descr_of = the o AList.lookup (op =) descr;
haftmann@26267
   171
    fun interpT (T as DtTFree _) = atom (typ_of_dtyp descr sorts T)
haftmann@26267
   172
      | interpT (T as DtType (tyco, Ts)) = if is_rec_type T
haftmann@26267
   173
          then rtyp tyco (map interpT Ts)
haftmann@26267
   174
          else atom (typ_of_dtyp descr sorts T)
haftmann@26267
   175
      | interpT (DtRec l) = if l < k then (dtyp o #1 o descr_of) l
haftmann@26267
   176
          else let val (tyco, Ts, _) = descr_of l
haftmann@26267
   177
          in rtyp tyco (map interpT Ts) end;
haftmann@26267
   178
    fun interpC (c, Ts) = (c, map interpT Ts);
haftmann@26267
   179
    fun interpK (_, (tyco, _, cs)) = (tyco, map interpC cs);
haftmann@26267
   180
  in map interpK (Library.take (k, descr)) end;
haftmann@26267
   181
berghofe@5177
   182
fun find_tname var Bi =
berghofe@5177
   183
  let val frees = map dest_Free (term_frees Bi)
berghofe@14412
   184
      val params = rename_wrt_term Bi (Logic.strip_params Bi);
haftmann@17521
   185
  in case AList.lookup (op =) (frees @ params) var of
skalberg@15531
   186
       NONE => error ("No such variable in subgoal: " ^ quote var)
skalberg@15531
   187
     | SOME(Type (tn, _)) => tn
berghofe@5177
   188
     | _ => error ("Cannot determine type of " ^ quote var)
berghofe@5177
   189
  end;
berghofe@5177
   190
wenzelm@8279
   191
fun infer_tname state i aterm =
berghofe@5177
   192
  let
wenzelm@22578
   193
    val sign = Thm.theory_of_thm state;
wenzelm@8279
   194
    val (_, _, Bi, _) = Thm.dest_state (state, i)
berghofe@5177
   195
    val params = Logic.strip_params Bi;   (*params of subgoal i*)
berghofe@5177
   196
    val params = rev (rename_wrt_term Bi params);   (*as they are printed*)
berghofe@5177
   197
    val (types, sorts) = types_sorts state;
haftmann@17521
   198
    fun types' (a, ~1) = (case AList.lookup (op =) params a of NONE => types(a, ~1) | sm => sm)
berghofe@5177
   199
      | types' ixn = types ixn;
wenzelm@22709
   200
    val ([ct], _) = Thm.read_def_cterms (sign, types', sorts) [] false [(aterm, dummyT)];
berghofe@5177
   201
  in case #T (rep_cterm ct) of
berghofe@5177
   202
       Type (tn, _) => tn
berghofe@5177
   203
     | _ => error ("Cannot determine type of " ^ quote aterm)
berghofe@5177
   204
  end;
berghofe@5177
   205
berghofe@5177
   206
(*Warn if the (induction) variable occurs Free among the premises, which
berghofe@5177
   207
  usually signals a mistake.  But calls the tactic either way!*)
wenzelm@8405
   208
fun occs_in_prems tacf vars =
berghofe@5177
   209
  SUBGOAL (fn (Bi, i) =>
haftmann@21045
   210
           (if exists (fn (a, _) => member (op =) vars a)
haftmann@21045
   211
                      (fold Term.add_frees (#2 (strip_context Bi)) [])
wenzelm@8405
   212
             then warning "Induction variable occurs also among premises!"
wenzelm@8405
   213
             else ();
wenzelm@8405
   214
            tacf i));
berghofe@5177
   215
wenzelm@8689
   216
berghofe@5177
   217
(* generic induction tactic for datatypes *)
berghofe@5177
   218
wenzelm@8689
   219
local
wenzelm@8689
   220
skalberg@15531
   221
fun prep_var (Var (ixn, _), SOME x) = SOME (ixn, x)
skalberg@15531
   222
  | prep_var _ = NONE;
wenzelm@8689
   223
haftmann@21045
   224
fun prep_inst (concl, xs) = (*exception Library.UnequalLengths*)
wenzelm@24830
   225
  let val vs = Induct.vars_of concl
haftmann@21045
   226
  in map_filter prep_var (Library.drop (length vs - length xs, vs) ~~ xs) end;
wenzelm@8689
   227
wenzelm@8689
   228
in
wenzelm@8689
   229
wenzelm@24711
   230
fun gen_induct_tac inst_tac (varss, opt_rule) i state =
paulson@18751
   231
  SUBGOAL (fn (Bi,_) =>
berghofe@5177
   232
  let
wenzelm@8672
   233
    val (rule, rule_name) =
paulson@18751
   234
      case opt_rule of
haftmann@21045
   235
          SOME r => (r, "Induction rule")
haftmann@21045
   236
        | NONE =>
haftmann@21045
   237
            let val tn = find_tname (hd (map_filter I (flat varss))) Bi
wenzelm@22598
   238
                val thy = Thm.theory_of_thm state
wenzelm@24711
   239
            in (#induction (the_datatype thy tn), "Induction rule for type " ^ tn)
haftmann@21045
   240
            end
wenzelm@11725
   241
    val concls = HOLogic.dest_concls (Thm.concl_of rule);
haftmann@21045
   242
    val insts = maps prep_inst (concls ~~ varss) handle Library.UnequalLengths =>
wenzelm@8689
   243
      error (rule_name ^ " has different numbers of variables");
paulson@18751
   244
  in occs_in_prems (inst_tac insts rule) (map #2 insts) i end)
paulson@18751
   245
  i state;
wenzelm@8689
   246
ballarin@14174
   247
fun induct_tac s =
berghofe@15444
   248
  gen_induct_tac Tactic.res_inst_tac'
haftmann@21045
   249
    (map (single o SOME) (Syntax.read_idents s), NONE);
wenzelm@8689
   250
nipkow@9747
   251
fun induct_thm_tac th s =
berghofe@15444
   252
  gen_induct_tac Tactic.res_inst_tac'
skalberg@15531
   253
    ([map SOME (Syntax.read_idents s)], SOME th);
nipkow@9747
   254
wenzelm@8689
   255
end;
berghofe@5177
   256
wenzelm@8279
   257
wenzelm@8437
   258
(* generic case tactic for datatypes *)
berghofe@5177
   259
ballarin@14174
   260
fun case_inst_tac inst_tac t rule i state =
wenzelm@8672
   261
  let
wenzelm@8672
   262
    val _ $ Var (ixn, _) $ _ = HOLogic.dest_Trueprop
wenzelm@8672
   263
      (hd (Logic.strip_assums_hyp (hd (Thm.prems_of rule))));
berghofe@15444
   264
  in inst_tac [(ixn, t)] rule i state end;
wenzelm@8672
   265
skalberg@15531
   266
fun gen_case_tac inst_tac (t, SOME rule) i state =
ballarin@14174
   267
      case_inst_tac inst_tac t rule i state
skalberg@15531
   268
  | gen_case_tac inst_tac (t, NONE) i state =
wenzelm@8672
   269
      let val tn = infer_tname state i t in
berghofe@15444
   270
        if tn = HOLogic.boolN then inst_tac [(("P", 0), t)] case_split_thm i state
ballarin@14174
   271
        else case_inst_tac inst_tac t
wenzelm@22578
   272
               (#exhaustion (the_datatype (Thm.theory_of_thm state) tn))
ballarin@14174
   273
               i state
berghofe@14471
   274
      end handle THM _ => Seq.empty;
wenzelm@8672
   275
skalberg@15531
   276
fun case_tac t = gen_case_tac Tactic.res_inst_tac' (t, NONE);
wenzelm@8672
   277
wenzelm@8279
   278
wenzelm@8279
   279
wenzelm@8541
   280
(** Isar tactic emulations **)
wenzelm@8541
   281
wenzelm@8672
   282
local
wenzelm@8672
   283
wenzelm@8689
   284
val rule_spec = Scan.lift (Args.$$$ "rule" -- Args.$$$ ":");
wenzelm@18988
   285
val opt_rule = Scan.option (rule_spec |-- Attrib.thm);
wenzelm@8689
   286
wenzelm@15703
   287
val varss =
wenzelm@15703
   288
  Args.and_list (Scan.repeat (Scan.unless rule_spec (Scan.lift (Args.maybe Args.name))));
wenzelm@8672
   289
wenzelm@20328
   290
val inst_tac = RuleInsts.bires_inst_tac false;
ballarin@14174
   291
ballarin@14174
   292
fun induct_meth ctxt (varss, opt_rule) =
ballarin@14174
   293
  gen_induct_tac (inst_tac ctxt) (varss, opt_rule);
ballarin@14174
   294
fun case_meth ctxt (varss, opt_rule) =
ballarin@14174
   295
  gen_case_tac (inst_tac ctxt) (varss, opt_rule);
ballarin@14174
   296
wenzelm@8672
   297
in
wenzelm@8541
   298
wenzelm@8541
   299
val tactic_emulations =
ballarin@14174
   300
 [("induct_tac", Method.goal_args_ctxt' (varss -- opt_rule) induct_meth,
ballarin@14174
   301
    "induct_tac emulation (dynamic instantiation)"),
ballarin@14174
   302
  ("case_tac", Method.goal_args_ctxt' (Scan.lift Args.name -- opt_rule) case_meth,
ballarin@14174
   303
    "case_tac emulation (dynamic instantiation)")];
wenzelm@8672
   304
wenzelm@8672
   305
end;
wenzelm@8541
   306
wenzelm@8541
   307
berghofe@5177
   308
wenzelm@8437
   309
(** induct method setup **)
wenzelm@8437
   310
wenzelm@8437
   311
(* case names *)
wenzelm@8437
   312
wenzelm@8437
   313
local
wenzelm@8437
   314
wenzelm@8437
   315
fun dt_recs (DtTFree _) = []
haftmann@21045
   316
  | dt_recs (DtType (_, dts)) = maps dt_recs dts
wenzelm@8437
   317
  | dt_recs (DtRec i) = [i];
wenzelm@8437
   318
wenzelm@8437
   319
fun dt_cases (descr: descr) (_, args, constrs) =
wenzelm@8437
   320
  let
haftmann@21045
   321
    fun the_bname i = Sign.base_name (#1 (the (AList.lookup (op =) descr i)));
haftmann@21045
   322
    val bnames = map the_bname (distinct (op =) (maps dt_recs args));
wenzelm@8437
   323
  in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
wenzelm@8437
   324
wenzelm@8437
   325
wenzelm@8437
   326
fun induct_cases descr =
haftmann@21045
   327
  DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
wenzelm@8437
   328
haftmann@21045
   329
fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
wenzelm@8437
   330
wenzelm@8437
   331
in
wenzelm@8437
   332
wenzelm@8437
   333
fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
wenzelm@8437
   334
wenzelm@8437
   335
fun mk_case_names_exhausts descr new =
wenzelm@8437
   336
  map (RuleCases.case_names o exhaust_cases descr o #1)
haftmann@21045
   337
    (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
wenzelm@8437
   338
wenzelm@8437
   339
end;
wenzelm@8437
   340
haftmann@24699
   341
fun add_rules simps case_thms rec_thms inject distinct
oheimb@11345
   342
                  weak_case_congs cong_att =
haftmann@21127
   343
  PureThy.add_thmss [(("simps", simps), []),
haftmann@24699
   344
    (("", flat case_thms @
haftmann@21045
   345
          flat distinct @ rec_thms), [Simplifier.simp_add]),
haftmann@24699
   346
    (("", rec_thms), [RecfunCodegen.add_default]),
haftmann@21127
   347
    (("", flat inject), [iff_add]),
paulson@21689
   348
    (("", map (fn th => th RS notE) (flat distinct)), [Classical.safe_elim NONE]),
haftmann@21127
   349
    (("", weak_case_congs), [cong_att])]
haftmann@21127
   350
  #> snd;
oheimb@11345
   351
wenzelm@8437
   352
wenzelm@8437
   353
(* add_cases_induct *)
wenzelm@8306
   354
wenzelm@19874
   355
fun add_cases_induct infos induction thy =
wenzelm@8306
   356
  let
wenzelm@19874
   357
    val inducts = ProjectRule.projections (ProofContext.init thy) induction;
wenzelm@8405
   358
wenzelm@11805
   359
    fun named_rules (name, {index, exhaustion, ...}: datatype_info) =
wenzelm@24830
   360
      [(("", nth inducts index), [Induct.induct_type name]),
wenzelm@24830
   361
       (("", exhaustion), [Induct.cases_type name])];
wenzelm@11805
   362
    fun unnamed_rule i =
wenzelm@24830
   363
      (("", nth inducts i), [PureThy.kind_internal, Induct.induct_type ""]);
wenzelm@18462
   364
  in
wenzelm@19874
   365
    thy |> PureThy.add_thms
haftmann@21045
   366
      (maps named_rules infos @
wenzelm@19874
   367
        map unnamed_rule (length infos upto length inducts - 1)) |> snd
wenzelm@19874
   368
    |> PureThy.add_thmss [(("inducts", inducts), [])] |> snd
wenzelm@18462
   369
  end;
wenzelm@8306
   370
berghofe@5177
   371
wenzelm@8405
   372
berghofe@7015
   373
(**** simplification procedure for showing distinctness of constructors ****)
berghofe@7015
   374
berghofe@7060
   375
fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
berghofe@7060
   376
  | stripT p = p;
berghofe@7060
   377
berghofe@7060
   378
fun stripC (i, f $ x) = stripC (i + 1, f)
berghofe@7060
   379
  | stripC p = p;
berghofe@7060
   380
berghofe@7015
   381
val distinctN = "constr_distinct";
berghofe@7015
   382
berghofe@7015
   383
exception ConstrDistinct of term;
berghofe@7015
   384
haftmann@25537
   385
fun distinct_rule thy ss tname eq_t = case #distinct (the_datatype thy tname) of
haftmann@25537
   386
    QuickAndDirty => Thm.invoke_oracle
haftmann@25537
   387
      (ThyInfo.the_theory "Datatype" thy) distinctN (thy, ConstrDistinct eq_t)
haftmann@25537
   388
  | FewConstrs thms => Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
haftmann@25537
   389
      (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
haftmann@25537
   390
        atac 2, resolve_tac thms 1, etac FalseE 1]))
haftmann@25537
   391
  | ManyConstrs (thm, simpset) =>
haftmann@25537
   392
      let
haftmann@25537
   393
        val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
wenzelm@26343
   394
          map (PureThy.get_thm (ThyInfo.the_theory "Datatype" thy))
haftmann@25537
   395
            ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"];
haftmann@25537
   396
      in
haftmann@25537
   397
        Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
haftmann@25537
   398
        (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
haftmann@25537
   399
          full_simp_tac (Simplifier.inherit_context ss simpset) 1,
haftmann@25537
   400
          REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
haftmann@25537
   401
          eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
haftmann@25537
   402
          etac FalseE 1]))
haftmann@25537
   403
      end;
haftmann@25537
   404
wenzelm@19539
   405
fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
berghofe@7060
   406
  (case (stripC (0, t1), stripC (0, t2)) of
berghofe@7060
   407
     ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
berghofe@7060
   408
         (case (stripT (0, T1), stripT (0, T2)) of
berghofe@7060
   409
            ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
berghofe@7060
   410
                if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
wenzelm@19539
   411
                   (case (get_datatype_descr thy) tname1 of
haftmann@19346
   412
                      SOME (_, (_, constrs)) => let val cnames = map fst constrs
berghofe@7015
   413
                        in if cname1 mem cnames andalso cname2 mem cnames then
haftmann@25537
   414
                             SOME (distinct_rule thy ss tname1
haftmann@25537
   415
                               (Logic.mk_equals (t, Const ("False", HOLogic.boolT))))
skalberg@15531
   416
                           else NONE
berghofe@7015
   417
                        end
skalberg@15531
   418
                    | NONE => NONE)
skalberg@15531
   419
                else NONE
skalberg@15531
   420
          | _ => NONE)
skalberg@15531
   421
   | _ => NONE)
wenzelm@20054
   422
  | distinct_proc _ _ _ = NONE;
berghofe@7015
   423
wenzelm@13462
   424
val distinct_simproc =
wenzelm@16430
   425
  Simplifier.simproc HOL.thy distinctN ["s = t"] distinct_proc;
berghofe@7015
   426
berghofe@7015
   427
val dist_ss = HOL_ss addsimprocs [distinct_simproc];
berghofe@7015
   428
berghofe@7015
   429
val simproc_setup =
wenzelm@18708
   430
  Theory.add_oracle (distinctN, fn (_, ConstrDistinct t) => t) #>
wenzelm@18708
   431
  (fn thy => ((change_simpset_of thy) (fn ss => ss addsimprocs [distinct_simproc]); thy));
berghofe@7015
   432
berghofe@7015
   433
berghofe@14799
   434
(**** translation rules for case ****)
berghofe@14799
   435
berghofe@22777
   436
fun make_case ctxt = DatatypeCase.make_case
berghofe@22777
   437
  (datatype_of_constr (ProofContext.theory_of ctxt)) ctxt;
berghofe@22777
   438
berghofe@22777
   439
fun strip_case ctxt = DatatypeCase.strip_case
berghofe@22777
   440
  (datatype_of_case (ProofContext.theory_of ctxt));
berghofe@14799
   441
berghofe@22777
   442
fun add_case_tr' case_names thy =
wenzelm@24712
   443
  Sign.add_advanced_trfuns ([], [],
wenzelm@24711
   444
    map (fn case_name =>
berghofe@22777
   445
      let val case_name' = Sign.const_syntax_name thy case_name
berghofe@22777
   446
      in (case_name', DatatypeCase.case_tr' datatype_of_case case_name')
berghofe@22777
   447
      end) case_names, []) thy;
berghofe@14799
   448
berghofe@14799
   449
val trfun_setup =
wenzelm@24712
   450
  Sign.add_advanced_trfuns ([],
nipkow@24349
   451
    [("_case_syntax", DatatypeCase.case_tr true datatype_of_constr)],
berghofe@22777
   452
    [], []);
berghofe@14799
   453
berghofe@14799
   454
berghofe@5177
   455
(* prepare types *)
berghofe@5177
   456
berghofe@5177
   457
fun read_typ sign ((Ts, sorts), str) =
berghofe@5177
   458
  let
wenzelm@22675
   459
    val T = Type.no_tvars (Sign.read_def_typ (sign, AList.lookup (op =)
berghofe@5177
   460
      (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
berghofe@5177
   461
  in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
berghofe@5177
   462
berghofe@5177
   463
fun cert_typ sign ((Ts, sorts), raw_T) =
berghofe@5177
   464
  let
berghofe@5177
   465
    val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
berghofe@5177
   466
      TYPE (msg, _, _) => error msg;
berghofe@5177
   467
    val sorts' = add_typ_tfrees (T, sorts)
berghofe@5177
   468
  in (Ts @ [T],
wenzelm@18964
   469
      case duplicates (op =) (map fst sorts') of
berghofe@5177
   470
         [] => sorts'
berghofe@5177
   471
       | dups => error ("Inconsistent sort constraints for " ^ commas dups))
berghofe@5177
   472
  end;
berghofe@5177
   473
berghofe@5177
   474
berghofe@5177
   475
(**** make datatype info ****)
berghofe@5177
   476
berghofe@25677
   477
fun make_dt_info alt_names descr sorts induct reccomb_names rec_thms
wenzelm@10121
   478
    (((((((((i, (_, (tname, _, _))), case_name), case_thms),
wenzelm@10121
   479
      exhaustion_thm), distinct_thm), inject), nchotomy), case_cong), weak_case_cong) =
wenzelm@10121
   480
  (tname,
wenzelm@10121
   481
   {index = i,
berghofe@25677
   482
    alt_names = alt_names,
wenzelm@10121
   483
    descr = descr,
berghofe@18319
   484
    sorts = sorts,
wenzelm@10121
   485
    rec_names = reccomb_names,
wenzelm@10121
   486
    rec_rewrites = rec_thms,
wenzelm@10121
   487
    case_name = case_name,
wenzelm@10121
   488
    case_rewrites = case_thms,
wenzelm@10121
   489
    induction = induct,
wenzelm@10121
   490
    exhaustion = exhaustion_thm,
wenzelm@10121
   491
    distinct = distinct_thm,
wenzelm@10121
   492
    inject = inject,
wenzelm@10121
   493
    nchotomy = nchotomy,
wenzelm@10121
   494
    case_cong = case_cong,
wenzelm@10121
   495
    weak_case_cong = weak_case_cong});
berghofe@5177
   496
berghofe@5177
   497
berghofe@5177
   498
(********************* axiomatic introduction of datatypes ********************)
berghofe@5177
   499
haftmann@20597
   500
fun add_axiom label t atts thy =
haftmann@20597
   501
  thy
haftmann@20597
   502
  |> PureThy.add_axioms_i [((label, t), atts)];
haftmann@20597
   503
haftmann@20597
   504
fun add_axioms label ts atts thy =
haftmann@20597
   505
  thy
haftmann@20597
   506
  |> PureThy.add_axiomss_i [((label, ts), atts)];
wenzelm@8437
   507
haftmann@20597
   508
fun add_and_get_axioms_atts label tnames ts attss =
haftmann@20597
   509
  fold_map (fn (tname, (atts, t)) => fn thy =>
haftmann@20597
   510
    thy
wenzelm@24712
   511
    |> Sign.add_path tname
haftmann@20597
   512
    |> add_axiom label t atts
wenzelm@24712
   513
    ||> Sign.parent_path
haftmann@20597
   514
    |-> (fn [ax] => pair ax)) (tnames ~~ (attss ~~ ts));
berghofe@5177
   515
haftmann@20597
   516
fun add_and_get_axioms label tnames ts =
haftmann@20597
   517
  add_and_get_axioms_atts label tnames ts (replicate (length tnames) []);
haftmann@20597
   518
haftmann@20597
   519
fun add_and_get_axiomss label tnames tss =
haftmann@20597
   520
  fold_map (fn (tname, ts) => fn thy =>
haftmann@20597
   521
    thy
wenzelm@24712
   522
    |> Sign.add_path tname
haftmann@20597
   523
    |> add_axioms label ts []
wenzelm@24712
   524
    ||> Sign.parent_path
haftmann@20597
   525
    |-> (fn [ax] => pair ax)) (tnames ~~ tss);
berghofe@5177
   526
berghofe@22777
   527
fun gen_specify_consts add args thy =
haftmann@20597
   528
  let
haftmann@20597
   529
    val specs = map (fn (c, T, mx) =>
haftmann@20597
   530
      Const (Sign.full_name thy (Syntax.const_name c mx), T)) args;
haftmann@20597
   531
  in
haftmann@20597
   532
    thy
berghofe@22777
   533
    |> add args
haftmann@20597
   534
    |> Theory.add_finals_i false specs
haftmann@20597
   535
  end;
wenzelm@19716
   536
berghofe@22777
   537
val specify_consts = gen_specify_consts Sign.add_consts_i;
wenzelm@24959
   538
val specify_consts_authentic = gen_specify_consts (fold (snd oo Sign.declare_const []));
berghofe@22777
   539
wenzelm@24711
   540
structure DatatypeInterpretation = InterpretationFun(type T = string list val eq = op =);
wenzelm@24711
   541
val interpretation = DatatypeInterpretation.interpretation;
haftmann@24626
   542
wenzelm@8437
   543
fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   544
    case_names_induct case_names_exhausts thy =
berghofe@5177
   545
  let
haftmann@21045
   546
    val descr' = flat descr;
berghofe@5177
   547
    val recTs = get_rec_types descr' sorts;
haftmann@21045
   548
    val used = map fst (fold Term.add_tfreesT recTs []);
skalberg@15570
   549
    val newTs = Library.take (length (hd descr), recTs);
berghofe@5177
   550
berghofe@5177
   551
    (**** declare new types and constants ****)
berghofe@5177
   552
berghofe@5177
   553
    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
berghofe@5177
   554
berghofe@5177
   555
    val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
berghofe@5177
   556
      map (fn ((_, cargs), (cname, mx)) =>
berghofe@5177
   557
        (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
berghofe@5177
   558
          (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
berghofe@5177
   559
berghofe@15457
   560
    val (rec_result_Ts, reccomb_fn_Ts) = DatatypeProp.make_primrec_Ts descr sorts used;
berghofe@5177
   561
berghofe@5177
   562
    val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
berghofe@5177
   563
    val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
berghofe@5177
   564
      (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
berghofe@5177
   565
        (1 upto (length descr')));
berghofe@5177
   566
wenzelm@20071
   567
    val freeT = TFree (Name.variant used "'t", HOLogic.typeS);
berghofe@5177
   568
    val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
berghofe@5177
   569
      map (fn (_, cargs) =>
berghofe@5177
   570
        let val Ts = map (typ_of_dtyp descr' sorts) cargs
berghofe@5177
   571
        in Ts ---> freeT end) constrs) (hd descr);
berghofe@5177
   572
berghofe@5177
   573
    val case_names = map (fn s => (s ^ "_case")) new_type_names;
berghofe@5177
   574
haftmann@21045
   575
    val thy2' = thy
berghofe@5177
   576
berghofe@5177
   577
      (** new types **)
wenzelm@25495
   578
      |> fold2 (fn (name, mx) => fn tvs => ObjectLogic.typedecl (name, tvs, mx) #> snd)
haftmann@21419
   579
           types_syntax tyvars
haftmann@21045
   580
      |> add_path flat_names (space_implode "_" new_type_names)
berghofe@5177
   581
berghofe@5177
   582
      (** primrec combinators **)
berghofe@5177
   583
haftmann@21045
   584
      |> specify_consts (map (fn ((name, T), T') =>
haftmann@21045
   585
           (name, reccomb_fn_Ts @ [T] ---> T', NoSyn)) (reccomb_names ~~ recTs ~~ rec_result_Ts))
berghofe@5177
   586
berghofe@5177
   587
      (** case combinators **)
berghofe@5177
   588
berghofe@22777
   589
      |> specify_consts_authentic (map (fn ((name, T), Ts) =>
haftmann@21045
   590
           (name, Ts @ [T] ---> freeT, NoSyn)) (case_names ~~ newTs ~~ case_fn_Ts));
berghofe@6305
   591
wenzelm@19716
   592
    val reccomb_names' = map (Sign.full_name thy2') reccomb_names;
wenzelm@19716
   593
    val case_names' = map (Sign.full_name thy2') case_names;
berghofe@6305
   594
haftmann@21045
   595
    val thy2 = thy2'
berghofe@5177
   596
berghofe@5661
   597
      (** constructors **)
berghofe@5661
   598
haftmann@21045
   599
      |> parent_path flat_names
haftmann@21045
   600
      |> fold (fn ((((_, (_, _, constrs)), T), tname),
haftmann@21045
   601
        constr_syntax') =>
haftmann@21045
   602
          add_path flat_names tname #>
wenzelm@19716
   603
            specify_consts (map (fn ((_, cargs), (cname, mx)) =>
berghofe@5661
   604
              (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
haftmann@21045
   605
                (constrs ~~ constr_syntax')) #>
haftmann@21045
   606
          parent_path flat_names)
berghofe@5661
   607
            (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
berghofe@5177
   608
berghofe@5177
   609
    (**** introduction of axioms ****)
berghofe@5177
   610
berghofe@5661
   611
    val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
berghofe@5661
   612
haftmann@18377
   613
    val ((([induct], [rec_thms]), inject), thy3) =
haftmann@18377
   614
      thy2
wenzelm@24712
   615
      |> Sign.add_path (space_implode "_" new_type_names)
haftmann@20597
   616
      |> add_axiom "induct" (DatatypeProp.make_ind descr sorts) [case_names_induct]
haftmann@20597
   617
      ||>> add_axioms "recs" rec_axs []
wenzelm@24712
   618
      ||> Sign.parent_path
haftmann@18377
   619
      ||>> add_and_get_axiomss "inject" new_type_names
haftmann@18377
   620
            (DatatypeProp.make_injs descr sorts);
haftmann@18377
   621
    val (distinct, thy4) = add_and_get_axiomss "distinct" new_type_names
berghofe@5177
   622
      (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
wenzelm@8437
   623
wenzelm@8437
   624
    val exhaust_ts = DatatypeProp.make_casedists descr sorts;
haftmann@18377
   625
    val (exhaustion, thy5) = add_and_get_axioms_atts "exhaust" new_type_names
haftmann@20597
   626
      exhaust_ts (map single case_names_exhausts) thy4;
haftmann@18377
   627
    val (case_thms, thy6) = add_and_get_axiomss "cases" new_type_names
berghofe@5177
   628
      (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
berghofe@5177
   629
    val (split_ts, split_asm_ts) = ListPair.unzip
berghofe@5177
   630
      (DatatypeProp.make_splits new_type_names descr sorts thy6);
haftmann@18377
   631
    val (split, thy7) = add_and_get_axioms "split" new_type_names split_ts thy6;
haftmann@18377
   632
    val (split_asm, thy8) = add_and_get_axioms "split_asm" new_type_names
berghofe@5177
   633
      split_asm_ts thy7;
haftmann@18377
   634
    val (nchotomys, thy9) = add_and_get_axioms "nchotomy" new_type_names
berghofe@5177
   635
      (DatatypeProp.make_nchotomys descr sorts) thy8;
haftmann@18377
   636
    val (case_congs, thy10) = add_and_get_axioms "case_cong" new_type_names
berghofe@5177
   637
      (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
haftmann@18377
   638
    val (weak_case_congs, thy11) = add_and_get_axioms "weak_case_cong" new_type_names
nipkow@8601
   639
      (DatatypeProp.make_weak_case_congs new_type_names descr sorts thy10) thy10;
wenzelm@8405
   640
berghofe@25677
   641
    val dt_infos = map (make_dt_info NONE descr' sorts induct reccomb_names' rec_thms)
berghofe@6305
   642
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
berghofe@7015
   643
        exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
wenzelm@10121
   644
          nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   645
haftmann@24699
   646
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
wenzelm@9386
   647
    val split_thms = split ~~ split_asm;
berghofe@5177
   648
haftmann@18518
   649
    val thy12 =
haftmann@18518
   650
      thy11
berghofe@22777
   651
      |> add_case_tr' case_names'
wenzelm@24712
   652
      |> Sign.add_path (space_implode "_" new_type_names)
haftmann@24699
   653
      |> add_rules simps case_thms rec_thms inject distinct
wenzelm@18728
   654
          weak_case_congs Simplifier.cong_add
berghofe@22777
   655
      |> put_dt_infos dt_infos
haftmann@18518
   656
      |> add_cases_induct dt_infos induct
wenzelm@24712
   657
      |> Sign.parent_path
haftmann@19599
   658
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
haftmann@19599
   659
      |> snd
wenzelm@24711
   660
      |> DatatypeInterpretation.data (map fst dt_infos);
berghofe@5177
   661
  in
haftmann@18008
   662
    ({distinct = distinct,
berghofe@5177
   663
      inject = inject,
berghofe@5177
   664
      exhaustion = exhaustion,
berghofe@5177
   665
      rec_thms = rec_thms,
berghofe@5177
   666
      case_thms = case_thms,
wenzelm@9386
   667
      split_thms = split_thms,
berghofe@5177
   668
      induction = induct,
haftmann@18008
   669
      simps = simps}, thy12)
berghofe@5177
   670
  end;
berghofe@5177
   671
berghofe@5177
   672
berghofe@5177
   673
(******************* definitional introduction of datatypes *******************)
berghofe@5177
   674
wenzelm@8437
   675
fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   676
    case_names_induct case_names_exhausts thy =
berghofe@5177
   677
  let
wenzelm@6360
   678
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   679
haftmann@18314
   680
    val ((inject, distinct, dist_rewrites, simproc_dists, induct), thy2) = thy |>
berghofe@5661
   681
      DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
wenzelm@8437
   682
        types_syntax constr_syntax case_names_induct;
berghofe@5177
   683
haftmann@18314
   684
    val (casedist_thms, thy3) = DatatypeAbsProofs.prove_casedist_thms new_type_names descr
wenzelm@8437
   685
      sorts induct case_names_exhausts thy2;
haftmann@18314
   686
    val ((reccomb_names, rec_thms), thy4) = DatatypeAbsProofs.prove_primrec_thms
wenzelm@20054
   687
      flat_names new_type_names descr sorts dt_info inject dist_rewrites
wenzelm@20054
   688
      (Simplifier.theory_context thy3 dist_ss) induct thy3;
haftmann@18314
   689
    val ((case_thms, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
berghofe@5661
   690
      flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
haftmann@18314
   691
    val (split_thms, thy7) = DatatypeAbsProofs.prove_split_thms new_type_names
berghofe@5177
   692
      descr sorts inject dist_rewrites casedist_thms case_thms thy6;
haftmann@18314
   693
    val (nchotomys, thy8) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   694
      descr sorts casedist_thms thy7;
haftmann@18314
   695
    val (case_congs, thy9) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   696
      descr sorts nchotomys case_thms thy8;
haftmann@18314
   697
    val (weak_case_congs, thy10) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   698
      descr sorts thy9;
berghofe@5177
   699
berghofe@25677
   700
    val dt_infos = map (make_dt_info NONE (flat descr) sorts induct reccomb_names rec_thms)
berghofe@5177
   701
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
wenzelm@10121
   702
        casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   703
haftmann@24699
   704
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
berghofe@5177
   705
haftmann@18518
   706
    val thy12 =
haftmann@24699
   707
      thy10
berghofe@22777
   708
      |> add_case_tr' case_names
wenzelm@24712
   709
      |> Sign.add_path (space_implode "_" new_type_names)
haftmann@24699
   710
      |> add_rules simps case_thms rec_thms inject distinct
wenzelm@18728
   711
          weak_case_congs (Simplifier.attrib (op addcongs))
berghofe@22777
   712
      |> put_dt_infos dt_infos
haftmann@18518
   713
      |> add_cases_induct dt_infos induct
wenzelm@24712
   714
      |> Sign.parent_path
haftmann@18518
   715
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
wenzelm@24711
   716
      |> DatatypeInterpretation.data (map fst dt_infos);
berghofe@5177
   717
  in
haftmann@18008
   718
    ({distinct = distinct,
berghofe@5177
   719
      inject = inject,
berghofe@5177
   720
      exhaustion = casedist_thms,
berghofe@5177
   721
      rec_thms = rec_thms,
berghofe@5177
   722
      case_thms = case_thms,
berghofe@5177
   723
      split_thms = split_thms,
berghofe@5177
   724
      induction = induct,
haftmann@18008
   725
      simps = simps}, thy12)
berghofe@5177
   726
  end;
berghofe@5177
   727
berghofe@5177
   728
wenzelm@6385
   729
(*********************** declare existing type as datatype *********************)
berghofe@5177
   730
wenzelm@6385
   731
fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
berghofe@5177
   732
  let
haftmann@18418
   733
    val (((distinct, inject), [induction]), thy1) =
haftmann@18418
   734
      thy0
haftmann@18418
   735
      |> fold_map apply_theorems raw_distinct
haftmann@18418
   736
      ||>> fold_map apply_theorems raw_inject
haftmann@18418
   737
      ||>> apply_theorems [raw_induction];
berghofe@5177
   738
wenzelm@22598
   739
    val ((_, [induction']), _) =
wenzelm@22598
   740
      Variable.importT_thms [induction] (Variable.thm_context induction);
berghofe@5177
   741
berghofe@5177
   742
    fun err t = error ("Ill-formed predicate in induction rule: " ^
haftmann@20715
   743
      Sign.string_of_term thy1 t);
berghofe@5177
   744
berghofe@5177
   745
    fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
berghofe@25888
   746
          ((tname, map (fst o dest_TFree) Ts) handle TERM _ => err t)
berghofe@5177
   747
      | get_typ t = err t;
berghofe@5177
   748
wenzelm@8437
   749
    val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induction')));
skalberg@15570
   750
    val new_type_names = getOpt (alt_names, map fst dtnames);
berghofe@5177
   751
berghofe@5177
   752
    fun get_constr t = (case Logic.strip_assums_concl t of
berghofe@5177
   753
        _ $ (_ $ t') => (case head_of t' of
berghofe@5177
   754
            Const (cname, cT) => (case strip_type cT of
berghofe@5177
   755
                (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
berghofe@5177
   756
              | _ => err t)
berghofe@5177
   757
          | _ => err t)
berghofe@5177
   758
      | _ => err t);
berghofe@5177
   759
berghofe@5177
   760
    fun make_dt_spec [] _ _ = []
berghofe@5177
   761
      | make_dt_spec ((tname, tvs)::dtnames') i constrs =
berghofe@5177
   762
          let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
berghofe@5177
   763
          in (i, (tname, map DtTFree tvs, map snd constrs'))::
berghofe@5177
   764
            (make_dt_spec dtnames' (i + 1) constrs'')
berghofe@5177
   765
          end;
berghofe@5177
   766
berghofe@5177
   767
    val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
berghofe@5177
   768
    val sorts = add_term_tfrees (concl_of induction', []);
wenzelm@6385
   769
    val dt_info = get_datatypes thy1;
berghofe@5177
   770
haftmann@21419
   771
    val (case_names_induct, case_names_exhausts) =
haftmann@21419
   772
      (mk_case_names_induct descr, mk_case_names_exhausts descr (map #1 dtnames));
wenzelm@8437
   773
wenzelm@6427
   774
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   775
haftmann@18314
   776
    val (casedist_thms, thy2) = thy1 |>
wenzelm@8437
   777
      DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction
wenzelm@8437
   778
        case_names_exhausts;
haftmann@18314
   779
    val ((reccomb_names, rec_thms), thy3) = DatatypeAbsProofs.prove_primrec_thms
wenzelm@20054
   780
      false new_type_names [descr] sorts dt_info inject distinct
wenzelm@20054
   781
      (Simplifier.theory_context thy2 dist_ss) induction thy2;
haftmann@18314
   782
    val ((case_thms, case_names), thy4) = DatatypeAbsProofs.prove_case_thms false
berghofe@5177
   783
      new_type_names [descr] sorts reccomb_names rec_thms thy3;
haftmann@18314
   784
    val (split_thms, thy5) = DatatypeAbsProofs.prove_split_thms
berghofe@5177
   785
      new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
haftmann@18314
   786
    val (nchotomys, thy6) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   787
      [descr] sorts casedist_thms thy5;
haftmann@18314
   788
    val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   789
      [descr] sorts nchotomys case_thms thy6;
haftmann@18314
   790
    val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   791
      [descr] sorts thy7;
berghofe@5177
   792
haftmann@18377
   793
    val ((_, [induction']), thy10) =
haftmann@24699
   794
      thy8
haftmann@18377
   795
      |> store_thmss "inject" new_type_names inject
haftmann@18377
   796
      ||>> store_thmss "distinct" new_type_names distinct
wenzelm@24712
   797
      ||> Sign.add_path (space_implode "_" new_type_names)
haftmann@18377
   798
      ||>> PureThy.add_thms [(("induct", induction), [case_names_induct])];
wenzelm@9149
   799
berghofe@25677
   800
    val dt_infos = map (make_dt_info alt_names descr sorts induction' reccomb_names rec_thms)
wenzelm@10121
   801
      ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
wenzelm@10121
   802
        map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   803
haftmann@24699
   804
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
berghofe@5177
   805
haftmann@19599
   806
    val thy11 =
haftmann@19599
   807
      thy10
berghofe@22777
   808
      |> add_case_tr' case_names
haftmann@24699
   809
      |> add_rules simps case_thms rec_thms inject distinct
haftmann@19599
   810
           weak_case_congs (Simplifier.attrib (op addcongs))
berghofe@22777
   811
      |> put_dt_infos dt_infos
haftmann@19599
   812
      |> add_cases_induct dt_infos induction'
wenzelm@24712
   813
      |> Sign.parent_path
haftmann@19599
   814
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
haftmann@19599
   815
      |> snd
wenzelm@24711
   816
      |> DatatypeInterpretation.data (map fst dt_infos);
berghofe@5177
   817
  in
haftmann@18008
   818
    ({distinct = distinct,
berghofe@5177
   819
      inject = inject,
berghofe@5177
   820
      exhaustion = casedist_thms,
berghofe@5177
   821
      rec_thms = rec_thms,
berghofe@5177
   822
      case_thms = case_thms,
berghofe@5177
   823
      split_thms = split_thms,
wenzelm@8437
   824
      induction = induction',
haftmann@18008
   825
      simps = simps}, thy11)
berghofe@5177
   826
  end;
berghofe@5177
   827
wenzelm@21350
   828
val rep_datatype = gen_rep_datatype IsarCmd.apply_theorems;
wenzelm@21350
   829
val rep_datatype_i = gen_rep_datatype IsarCmd.apply_theorems_i;
wenzelm@6385
   830
berghofe@5177
   831
wenzelm@11958
   832
berghofe@5177
   833
(******************************** add datatype ********************************)
berghofe@5177
   834
berghofe@14887
   835
fun gen_add_datatype prep_typ err flat_names new_type_names dts thy =
berghofe@5177
   836
  let
wenzelm@20820
   837
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   838
berghofe@5177
   839
    (* this theory is used just for parsing *)
berghofe@5177
   840
berghofe@5177
   841
    val tmp_thy = thy |>
wenzelm@5892
   842
      Theory.copy |>
wenzelm@24712
   843
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   844
        (tname, length tvs, mx)) dts);
berghofe@5177
   845
berghofe@5661
   846
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   847
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
haftmann@20597
   848
      let val full_tname = Sign.full_name tmp_thy (Syntax.type_name tname mx)
wenzelm@18964
   849
      in (case duplicates (op =) tvs of
berghofe@5661
   850
            [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
berghofe@5661
   851
                  else error ("Mutually recursive datatypes must have same type parameters")
berghofe@5177
   852
          | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
berghofe@5177
   853
              " : " ^ commas dups))
berghofe@5177
   854
      end) dts);
berghofe@5177
   855
wenzelm@18964
   856
    val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
berghofe@5177
   857
      [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   858
haftmann@21045
   859
    fun prep_dt_spec (tvs, tname, mx, constrs) (dts', constr_syntax, sorts, i) =
berghofe@5177
   860
      let
haftmann@21045
   861
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
berghofe@5279
   862
          let
haftmann@20597
   863
            val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
haftmann@21045
   864
            val _ = (case fold (curry add_typ_tfree_names) cargs' [] \\ tvs of
berghofe@5279
   865
                [] => ()
berghofe@5279
   866
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@20597
   867
          in (constrs @ [((if flat_names then Sign.full_name tmp_thy else
haftmann@20597
   868
                Sign.full_name_path tmp_thy tname) (Syntax.const_name cname mx'),
berghofe@5177
   869
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   870
              constr_syntax' @ [(cname, mx')], sorts'')
wenzelm@18678
   871
          end handle ERROR msg =>
wenzelm@18678
   872
            cat_error msg ("The error above occured in constructor " ^ cname ^
berghofe@5177
   873
              " of datatype " ^ tname);
berghofe@5177
   874
berghofe@5177
   875
        val (constrs', constr_syntax', sorts') =
haftmann@21045
   876
          fold prep_constr constrs ([], [], sorts)
berghofe@5177
   877
wenzelm@8405
   878
      in
wenzelm@18964
   879
        case duplicates (op =) (map fst constrs') of
berghofe@5177
   880
           [] =>
haftmann@20597
   881
             (dts' @ [(i, (Sign.full_name tmp_thy (Syntax.type_name tname mx),
berghofe@5177
   882
                map DtTFree tvs, constrs'))],
berghofe@5177
   883
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   884
         | dups => error ("Duplicate constructors " ^ commas dups ^
berghofe@5177
   885
             " in datatype " ^ tname)
berghofe@5177
   886
      end;
berghofe@5177
   887
haftmann@21045
   888
    val (dts', constr_syntax, sorts', i) = fold prep_dt_spec dts ([], [], [], 0);
haftmann@20597
   889
    val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
berghofe@5177
   890
    val dt_info = get_datatypes thy;
haftmann@20597
   891
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
berghofe@14887
   892
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
wenzelm@15661
   893
      if err then error ("Nonemptiness check failed for datatype " ^ s)
berghofe@14887
   894
      else raise exn;
berghofe@5177
   895
haftmann@21045
   896
    val descr' = flat descr;
wenzelm@8437
   897
    val case_names_induct = mk_case_names_induct descr';
wenzelm@8437
   898
    val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
berghofe@5177
   899
  in
berghofe@5177
   900
    (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
wenzelm@8437
   901
      flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   902
      case_names_induct case_names_exhausts thy
berghofe@5177
   903
  end;
berghofe@5177
   904
berghofe@5177
   905
val add_datatype_i = gen_add_datatype cert_typ;
berghofe@14887
   906
val add_datatype = gen_add_datatype read_typ true;
berghofe@5177
   907
wenzelm@6360
   908
haftmann@26111
   909
(** a datatype antiquotation **)
haftmann@26111
   910
haftmann@26111
   911
local
haftmann@26111
   912
haftmann@26111
   913
val sym_datatype = Pretty.str "\\isacommand{datatype}";
haftmann@26111
   914
val sym_binder = Pretty.str "{\\isacharequal}";
haftmann@26111
   915
val sym_of = Pretty.str "of";
haftmann@26111
   916
val sym_sep = Pretty.str "{\\isacharbar}";
haftmann@26111
   917
haftmann@26111
   918
in
haftmann@26111
   919
haftmann@26111
   920
fun args_datatype (ctxt, args) =
haftmann@26111
   921
  let
haftmann@26111
   922
    val (tyco, (ctxt', args')) = Args.tyname (ctxt, args);
haftmann@26111
   923
    val thy = Context.theory_of ctxt';
haftmann@26111
   924
    val spec = the_datatype_spec thy tyco;
haftmann@26111
   925
  in ((tyco, spec), (ctxt', args')) end;
haftmann@26111
   926
haftmann@26111
   927
fun pretty_datatype ctxt (dtco, (vs, cos)) =
haftmann@26111
   928
  let
haftmann@26111
   929
    val ty = Type (dtco, map TFree vs);
haftmann@26111
   930
    fun pretty_typ_br ty =
haftmann@26111
   931
      let
haftmann@26111
   932
        val p = Syntax.pretty_typ ctxt ty;
haftmann@26111
   933
        val s = explode (Pretty.str_of p);
haftmann@26111
   934
      in if member (op =) s " " then Pretty.enclose "(" ")" [p]
haftmann@26111
   935
        else p
haftmann@26111
   936
      end;
haftmann@26111
   937
    fun pretty_constr (co, []) =
haftmann@26111
   938
          Syntax.pretty_term ctxt (Const (co, ty))
haftmann@26111
   939
      | pretty_constr (co, [ty']) =
haftmann@26111
   940
          (Pretty.block o Pretty.breaks)
haftmann@26111
   941
            [Syntax.pretty_term ctxt (Const (co, ty' --> ty)),
haftmann@26111
   942
              sym_of, Syntax.pretty_typ ctxt ty']
haftmann@26111
   943
      | pretty_constr (co, tys) =
haftmann@26111
   944
          (Pretty.block o Pretty.breaks)
haftmann@26111
   945
            (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
haftmann@26111
   946
              sym_of :: map pretty_typ_br tys);
haftmann@26111
   947
  in (Pretty.block o Pretty.breaks) (
haftmann@26111
   948
    sym_datatype
haftmann@26111
   949
    :: Syntax.pretty_typ ctxt ty
haftmann@26111
   950
    :: sym_binder
haftmann@26111
   951
    :: separate sym_sep (map pretty_constr cos)
haftmann@26111
   952
  ) end
haftmann@26111
   953
haftmann@26111
   954
end;
haftmann@18451
   955
wenzelm@6360
   956
(** package setup **)
wenzelm@6360
   957
wenzelm@6360
   958
(* setup theory *)
wenzelm@6360
   959
wenzelm@18708
   960
val setup =
wenzelm@24098
   961
  DatatypeProp.distinctness_limit_setup #>
wenzelm@24098
   962
  Method.add_methods tactic_emulations #>
wenzelm@24098
   963
  simproc_setup #>
haftmann@24626
   964
  trfun_setup #>
wenzelm@24711
   965
  DatatypeInterpretation.init;
wenzelm@6360
   966
wenzelm@6360
   967
wenzelm@6360
   968
(* outer syntax *)
wenzelm@6360
   969
wenzelm@17057
   970
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6360
   971
wenzelm@24867
   972
val _ = OuterSyntax.keywords ["distinct", "inject", "induction"];
wenzelm@24867
   973
wenzelm@6360
   974
val datatype_decl =
wenzelm@6723
   975
  Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
wenzelm@12876
   976
    (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
wenzelm@6360
   977
wenzelm@6360
   978
fun mk_datatype args =
wenzelm@6360
   979
  let
skalberg@15531
   980
    val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
wenzelm@12876
   981
    val specs = map (fn ((((_, vs), t), mx), cons) =>
wenzelm@12876
   982
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@18008
   983
  in snd o add_datatype false names specs end;
wenzelm@6360
   984
wenzelm@24867
   985
val _ =
wenzelm@6723
   986
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
wenzelm@6723
   987
    (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
wenzelm@6360
   988
wenzelm@6385
   989
wenzelm@6385
   990
val rep_datatype_decl =
wenzelm@6723
   991
  Scan.option (Scan.repeat1 P.name) --
wenzelm@22101
   992
    Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 SpecParse.xthms1)) [[]] --
wenzelm@22101
   993
    Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 SpecParse.xthms1)) [[]] --
wenzelm@22101
   994
    (P.$$$ "induction" |-- P.!!! SpecParse.xthm);
wenzelm@6385
   995
haftmann@18008
   996
fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #2 o rep_datatype opt_ts dss iss ind;
wenzelm@6385
   997
wenzelm@24867
   998
val _ =
wenzelm@6723
   999
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
wenzelm@6385
  1000
    (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
wenzelm@6385
  1001
haftmann@26111
  1002
val _ =
haftmann@26111
  1003
  ThyOutput.add_commands [("datatype",
haftmann@26111
  1004
    ThyOutput.args args_datatype (ThyOutput.output pretty_datatype))];
haftmann@26111
  1005
wenzelm@6385
  1006
end;
wenzelm@6385
  1007
wenzelm@6360
  1008
berghofe@5177
  1009
end;
berghofe@5177
  1010
wenzelm@6360
  1011
structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
wenzelm@6360
  1012
open BasicDatatypePackage;
wenzelm@15704
  1013