src/HOL/Tools/datatype_package.ML
author berghofe
Thu Apr 03 17:52:51 2008 +0200 (2008-04-03)
changeset 26533 aeef55a3d1d5
parent 26496 49ae9456eba9
child 26939 1035c89b4c02
permissions -rw-r--r--
Deleted code for axiomatic introduction of datatypes. Instead, the package
now uses SkipProof.prove rather than Goal.prove to do proofs.
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
haftmann@25537
   383
fun distinct_rule thy ss tname eq_t = case #distinct (the_datatype thy tname) of
berghofe@26533
   384
    FewConstrs thms => Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
haftmann@25537
   385
      (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
haftmann@25537
   386
        atac 2, resolve_tac thms 1, etac FalseE 1]))
haftmann@25537
   387
  | ManyConstrs (thm, simpset) =>
haftmann@25537
   388
      let
haftmann@25537
   389
        val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
wenzelm@26343
   390
          map (PureThy.get_thm (ThyInfo.the_theory "Datatype" thy))
haftmann@25537
   391
            ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"];
haftmann@25537
   392
      in
haftmann@25537
   393
        Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
haftmann@25537
   394
        (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
haftmann@25537
   395
          full_simp_tac (Simplifier.inherit_context ss simpset) 1,
haftmann@25537
   396
          REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
haftmann@25537
   397
          eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
haftmann@25537
   398
          etac FalseE 1]))
haftmann@25537
   399
      end;
haftmann@25537
   400
wenzelm@19539
   401
fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
berghofe@7060
   402
  (case (stripC (0, t1), stripC (0, t2)) of
berghofe@7060
   403
     ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
berghofe@7060
   404
         (case (stripT (0, T1), stripT (0, T2)) of
berghofe@7060
   405
            ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
berghofe@7060
   406
                if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
wenzelm@19539
   407
                   (case (get_datatype_descr thy) tname1 of
haftmann@19346
   408
                      SOME (_, (_, constrs)) => let val cnames = map fst constrs
berghofe@7015
   409
                        in if cname1 mem cnames andalso cname2 mem cnames then
haftmann@25537
   410
                             SOME (distinct_rule thy ss tname1
haftmann@25537
   411
                               (Logic.mk_equals (t, Const ("False", HOLogic.boolT))))
skalberg@15531
   412
                           else NONE
berghofe@7015
   413
                        end
skalberg@15531
   414
                    | NONE => NONE)
skalberg@15531
   415
                else NONE
skalberg@15531
   416
          | _ => NONE)
skalberg@15531
   417
   | _ => NONE)
wenzelm@20054
   418
  | distinct_proc _ _ _ = NONE;
berghofe@7015
   419
wenzelm@13462
   420
val distinct_simproc =
wenzelm@16430
   421
  Simplifier.simproc HOL.thy distinctN ["s = t"] distinct_proc;
berghofe@7015
   422
berghofe@7015
   423
val dist_ss = HOL_ss addsimprocs [distinct_simproc];
berghofe@7015
   424
berghofe@7015
   425
val simproc_setup =
wenzelm@26496
   426
  Simplifier.map_simpset (fn ss => ss addsimprocs [distinct_simproc]);
berghofe@7015
   427
berghofe@7015
   428
berghofe@14799
   429
(**** translation rules for case ****)
berghofe@14799
   430
berghofe@22777
   431
fun make_case ctxt = DatatypeCase.make_case
berghofe@22777
   432
  (datatype_of_constr (ProofContext.theory_of ctxt)) ctxt;
berghofe@22777
   433
berghofe@22777
   434
fun strip_case ctxt = DatatypeCase.strip_case
berghofe@22777
   435
  (datatype_of_case (ProofContext.theory_of ctxt));
berghofe@14799
   436
berghofe@22777
   437
fun add_case_tr' case_names thy =
wenzelm@24712
   438
  Sign.add_advanced_trfuns ([], [],
wenzelm@24711
   439
    map (fn case_name =>
berghofe@22777
   440
      let val case_name' = Sign.const_syntax_name thy case_name
berghofe@22777
   441
      in (case_name', DatatypeCase.case_tr' datatype_of_case case_name')
berghofe@22777
   442
      end) case_names, []) thy;
berghofe@14799
   443
berghofe@14799
   444
val trfun_setup =
wenzelm@24712
   445
  Sign.add_advanced_trfuns ([],
nipkow@24349
   446
    [("_case_syntax", DatatypeCase.case_tr true datatype_of_constr)],
berghofe@22777
   447
    [], []);
berghofe@14799
   448
berghofe@14799
   449
berghofe@5177
   450
(* prepare types *)
berghofe@5177
   451
berghofe@5177
   452
fun read_typ sign ((Ts, sorts), str) =
berghofe@5177
   453
  let
wenzelm@22675
   454
    val T = Type.no_tvars (Sign.read_def_typ (sign, AList.lookup (op =)
berghofe@5177
   455
      (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
berghofe@5177
   456
  in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
berghofe@5177
   457
berghofe@5177
   458
fun cert_typ sign ((Ts, sorts), raw_T) =
berghofe@5177
   459
  let
berghofe@5177
   460
    val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
berghofe@5177
   461
      TYPE (msg, _, _) => error msg;
berghofe@5177
   462
    val sorts' = add_typ_tfrees (T, sorts)
berghofe@5177
   463
  in (Ts @ [T],
wenzelm@18964
   464
      case duplicates (op =) (map fst sorts') of
berghofe@5177
   465
         [] => sorts'
berghofe@5177
   466
       | dups => error ("Inconsistent sort constraints for " ^ commas dups))
berghofe@5177
   467
  end;
berghofe@5177
   468
berghofe@5177
   469
berghofe@5177
   470
(**** make datatype info ****)
berghofe@5177
   471
berghofe@25677
   472
fun make_dt_info alt_names descr sorts induct reccomb_names rec_thms
wenzelm@10121
   473
    (((((((((i, (_, (tname, _, _))), case_name), case_thms),
wenzelm@10121
   474
      exhaustion_thm), distinct_thm), inject), nchotomy), case_cong), weak_case_cong) =
wenzelm@10121
   475
  (tname,
wenzelm@10121
   476
   {index = i,
berghofe@25677
   477
    alt_names = alt_names,
wenzelm@10121
   478
    descr = descr,
berghofe@18319
   479
    sorts = sorts,
wenzelm@10121
   480
    rec_names = reccomb_names,
wenzelm@10121
   481
    rec_rewrites = rec_thms,
wenzelm@10121
   482
    case_name = case_name,
wenzelm@10121
   483
    case_rewrites = case_thms,
wenzelm@10121
   484
    induction = induct,
wenzelm@10121
   485
    exhaustion = exhaustion_thm,
wenzelm@10121
   486
    distinct = distinct_thm,
wenzelm@10121
   487
    inject = inject,
wenzelm@10121
   488
    nchotomy = nchotomy,
wenzelm@10121
   489
    case_cong = case_cong,
wenzelm@10121
   490
    weak_case_cong = weak_case_cong});
berghofe@5177
   491
wenzelm@24711
   492
structure DatatypeInterpretation = InterpretationFun(type T = string list val eq = op =);
wenzelm@24711
   493
val interpretation = DatatypeInterpretation.interpretation;
haftmann@24626
   494
berghofe@5177
   495
berghofe@5177
   496
(******************* definitional introduction of datatypes *******************)
berghofe@5177
   497
wenzelm@8437
   498
fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   499
    case_names_induct case_names_exhausts thy =
berghofe@5177
   500
  let
wenzelm@6360
   501
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   502
haftmann@18314
   503
    val ((inject, distinct, dist_rewrites, simproc_dists, induct), thy2) = thy |>
berghofe@5661
   504
      DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
wenzelm@8437
   505
        types_syntax constr_syntax case_names_induct;
berghofe@5177
   506
haftmann@18314
   507
    val (casedist_thms, thy3) = DatatypeAbsProofs.prove_casedist_thms new_type_names descr
wenzelm@8437
   508
      sorts induct case_names_exhausts thy2;
haftmann@18314
   509
    val ((reccomb_names, rec_thms), thy4) = DatatypeAbsProofs.prove_primrec_thms
wenzelm@20054
   510
      flat_names new_type_names descr sorts dt_info inject dist_rewrites
wenzelm@20054
   511
      (Simplifier.theory_context thy3 dist_ss) induct thy3;
haftmann@18314
   512
    val ((case_thms, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
berghofe@5661
   513
      flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
haftmann@18314
   514
    val (split_thms, thy7) = DatatypeAbsProofs.prove_split_thms new_type_names
berghofe@5177
   515
      descr sorts inject dist_rewrites casedist_thms case_thms thy6;
haftmann@18314
   516
    val (nchotomys, thy8) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   517
      descr sorts casedist_thms thy7;
haftmann@18314
   518
    val (case_congs, thy9) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   519
      descr sorts nchotomys case_thms thy8;
haftmann@18314
   520
    val (weak_case_congs, thy10) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   521
      descr sorts thy9;
berghofe@5177
   522
berghofe@25677
   523
    val dt_infos = map (make_dt_info NONE (flat descr) sorts induct reccomb_names rec_thms)
berghofe@5177
   524
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
wenzelm@10121
   525
        casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   526
haftmann@24699
   527
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
berghofe@5177
   528
haftmann@18518
   529
    val thy12 =
haftmann@24699
   530
      thy10
berghofe@22777
   531
      |> add_case_tr' case_names
wenzelm@24712
   532
      |> Sign.add_path (space_implode "_" new_type_names)
haftmann@24699
   533
      |> add_rules simps case_thms rec_thms inject distinct
wenzelm@18728
   534
          weak_case_congs (Simplifier.attrib (op addcongs))
berghofe@22777
   535
      |> put_dt_infos dt_infos
haftmann@18518
   536
      |> add_cases_induct dt_infos induct
wenzelm@24712
   537
      |> Sign.parent_path
haftmann@18518
   538
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
wenzelm@24711
   539
      |> DatatypeInterpretation.data (map fst dt_infos);
berghofe@5177
   540
  in
haftmann@18008
   541
    ({distinct = distinct,
berghofe@5177
   542
      inject = inject,
berghofe@5177
   543
      exhaustion = casedist_thms,
berghofe@5177
   544
      rec_thms = rec_thms,
berghofe@5177
   545
      case_thms = case_thms,
berghofe@5177
   546
      split_thms = split_thms,
berghofe@5177
   547
      induction = induct,
haftmann@18008
   548
      simps = simps}, thy12)
berghofe@5177
   549
  end;
berghofe@5177
   550
berghofe@5177
   551
wenzelm@6385
   552
(*********************** declare existing type as datatype *********************)
berghofe@5177
   553
wenzelm@6385
   554
fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
berghofe@5177
   555
  let
haftmann@18418
   556
    val (((distinct, inject), [induction]), thy1) =
haftmann@18418
   557
      thy0
haftmann@18418
   558
      |> fold_map apply_theorems raw_distinct
haftmann@18418
   559
      ||>> fold_map apply_theorems raw_inject
haftmann@18418
   560
      ||>> apply_theorems [raw_induction];
berghofe@5177
   561
wenzelm@22598
   562
    val ((_, [induction']), _) =
wenzelm@22598
   563
      Variable.importT_thms [induction] (Variable.thm_context induction);
berghofe@5177
   564
berghofe@5177
   565
    fun err t = error ("Ill-formed predicate in induction rule: " ^
haftmann@20715
   566
      Sign.string_of_term thy1 t);
berghofe@5177
   567
berghofe@5177
   568
    fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
berghofe@25888
   569
          ((tname, map (fst o dest_TFree) Ts) handle TERM _ => err t)
berghofe@5177
   570
      | get_typ t = err t;
berghofe@5177
   571
wenzelm@8437
   572
    val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induction')));
skalberg@15570
   573
    val new_type_names = getOpt (alt_names, map fst dtnames);
berghofe@5177
   574
berghofe@5177
   575
    fun get_constr t = (case Logic.strip_assums_concl t of
berghofe@5177
   576
        _ $ (_ $ t') => (case head_of t' of
berghofe@5177
   577
            Const (cname, cT) => (case strip_type cT of
berghofe@5177
   578
                (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
berghofe@5177
   579
              | _ => err t)
berghofe@5177
   580
          | _ => err t)
berghofe@5177
   581
      | _ => err t);
berghofe@5177
   582
berghofe@5177
   583
    fun make_dt_spec [] _ _ = []
berghofe@5177
   584
      | make_dt_spec ((tname, tvs)::dtnames') i constrs =
berghofe@5177
   585
          let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
berghofe@5177
   586
          in (i, (tname, map DtTFree tvs, map snd constrs'))::
berghofe@5177
   587
            (make_dt_spec dtnames' (i + 1) constrs'')
berghofe@5177
   588
          end;
berghofe@5177
   589
berghofe@5177
   590
    val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
berghofe@5177
   591
    val sorts = add_term_tfrees (concl_of induction', []);
wenzelm@6385
   592
    val dt_info = get_datatypes thy1;
berghofe@5177
   593
haftmann@21419
   594
    val (case_names_induct, case_names_exhausts) =
haftmann@21419
   595
      (mk_case_names_induct descr, mk_case_names_exhausts descr (map #1 dtnames));
wenzelm@8437
   596
wenzelm@6427
   597
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   598
haftmann@18314
   599
    val (casedist_thms, thy2) = thy1 |>
wenzelm@8437
   600
      DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction
wenzelm@8437
   601
        case_names_exhausts;
haftmann@18314
   602
    val ((reccomb_names, rec_thms), thy3) = DatatypeAbsProofs.prove_primrec_thms
wenzelm@20054
   603
      false new_type_names [descr] sorts dt_info inject distinct
wenzelm@20054
   604
      (Simplifier.theory_context thy2 dist_ss) induction thy2;
haftmann@18314
   605
    val ((case_thms, case_names), thy4) = DatatypeAbsProofs.prove_case_thms false
berghofe@5177
   606
      new_type_names [descr] sorts reccomb_names rec_thms thy3;
haftmann@18314
   607
    val (split_thms, thy5) = DatatypeAbsProofs.prove_split_thms
berghofe@5177
   608
      new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
haftmann@18314
   609
    val (nchotomys, thy6) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   610
      [descr] sorts casedist_thms thy5;
haftmann@18314
   611
    val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   612
      [descr] sorts nchotomys case_thms thy6;
haftmann@18314
   613
    val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   614
      [descr] sorts thy7;
berghofe@5177
   615
haftmann@18377
   616
    val ((_, [induction']), thy10) =
haftmann@24699
   617
      thy8
haftmann@18377
   618
      |> store_thmss "inject" new_type_names inject
haftmann@18377
   619
      ||>> store_thmss "distinct" new_type_names distinct
wenzelm@24712
   620
      ||> Sign.add_path (space_implode "_" new_type_names)
haftmann@18377
   621
      ||>> PureThy.add_thms [(("induct", induction), [case_names_induct])];
wenzelm@9149
   622
berghofe@25677
   623
    val dt_infos = map (make_dt_info alt_names descr sorts induction' reccomb_names rec_thms)
wenzelm@10121
   624
      ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
wenzelm@10121
   625
        map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   626
haftmann@24699
   627
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
berghofe@5177
   628
haftmann@19599
   629
    val thy11 =
haftmann@19599
   630
      thy10
berghofe@22777
   631
      |> add_case_tr' case_names
haftmann@24699
   632
      |> add_rules simps case_thms rec_thms inject distinct
haftmann@19599
   633
           weak_case_congs (Simplifier.attrib (op addcongs))
berghofe@22777
   634
      |> put_dt_infos dt_infos
haftmann@19599
   635
      |> add_cases_induct dt_infos induction'
wenzelm@24712
   636
      |> Sign.parent_path
haftmann@19599
   637
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
haftmann@19599
   638
      |> snd
wenzelm@24711
   639
      |> DatatypeInterpretation.data (map fst dt_infos);
berghofe@5177
   640
  in
haftmann@18008
   641
    ({distinct = distinct,
berghofe@5177
   642
      inject = inject,
berghofe@5177
   643
      exhaustion = casedist_thms,
berghofe@5177
   644
      rec_thms = rec_thms,
berghofe@5177
   645
      case_thms = case_thms,
berghofe@5177
   646
      split_thms = split_thms,
wenzelm@8437
   647
      induction = induction',
haftmann@18008
   648
      simps = simps}, thy11)
berghofe@5177
   649
  end;
berghofe@5177
   650
wenzelm@21350
   651
val rep_datatype = gen_rep_datatype IsarCmd.apply_theorems;
wenzelm@21350
   652
val rep_datatype_i = gen_rep_datatype IsarCmd.apply_theorems_i;
wenzelm@6385
   653
berghofe@5177
   654
wenzelm@11958
   655
berghofe@5177
   656
(******************************** add datatype ********************************)
berghofe@5177
   657
berghofe@14887
   658
fun gen_add_datatype prep_typ err flat_names new_type_names dts thy =
berghofe@5177
   659
  let
wenzelm@20820
   660
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   661
berghofe@5177
   662
    (* this theory is used just for parsing *)
berghofe@5177
   663
berghofe@5177
   664
    val tmp_thy = thy |>
wenzelm@5892
   665
      Theory.copy |>
wenzelm@24712
   666
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   667
        (tname, length tvs, mx)) dts);
berghofe@5177
   668
berghofe@5661
   669
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   670
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
haftmann@20597
   671
      let val full_tname = Sign.full_name tmp_thy (Syntax.type_name tname mx)
wenzelm@18964
   672
      in (case duplicates (op =) tvs of
berghofe@5661
   673
            [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
berghofe@5661
   674
                  else error ("Mutually recursive datatypes must have same type parameters")
berghofe@5177
   675
          | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
berghofe@5177
   676
              " : " ^ commas dups))
berghofe@5177
   677
      end) dts);
berghofe@5177
   678
wenzelm@18964
   679
    val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
berghofe@5177
   680
      [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   681
haftmann@21045
   682
    fun prep_dt_spec (tvs, tname, mx, constrs) (dts', constr_syntax, sorts, i) =
berghofe@5177
   683
      let
haftmann@21045
   684
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
berghofe@5279
   685
          let
haftmann@20597
   686
            val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
haftmann@21045
   687
            val _ = (case fold (curry add_typ_tfree_names) cargs' [] \\ tvs of
berghofe@5279
   688
                [] => ()
berghofe@5279
   689
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@20597
   690
          in (constrs @ [((if flat_names then Sign.full_name tmp_thy else
haftmann@20597
   691
                Sign.full_name_path tmp_thy tname) (Syntax.const_name cname mx'),
berghofe@5177
   692
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   693
              constr_syntax' @ [(cname, mx')], sorts'')
wenzelm@18678
   694
          end handle ERROR msg =>
wenzelm@18678
   695
            cat_error msg ("The error above occured in constructor " ^ cname ^
berghofe@5177
   696
              " of datatype " ^ tname);
berghofe@5177
   697
berghofe@5177
   698
        val (constrs', constr_syntax', sorts') =
haftmann@21045
   699
          fold prep_constr constrs ([], [], sorts)
berghofe@5177
   700
wenzelm@8405
   701
      in
wenzelm@18964
   702
        case duplicates (op =) (map fst constrs') of
berghofe@5177
   703
           [] =>
haftmann@20597
   704
             (dts' @ [(i, (Sign.full_name tmp_thy (Syntax.type_name tname mx),
berghofe@5177
   705
                map DtTFree tvs, constrs'))],
berghofe@5177
   706
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   707
         | dups => error ("Duplicate constructors " ^ commas dups ^
berghofe@5177
   708
             " in datatype " ^ tname)
berghofe@5177
   709
      end;
berghofe@5177
   710
haftmann@21045
   711
    val (dts', constr_syntax, sorts', i) = fold prep_dt_spec dts ([], [], [], 0);
haftmann@20597
   712
    val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
berghofe@5177
   713
    val dt_info = get_datatypes thy;
haftmann@20597
   714
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
berghofe@14887
   715
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
wenzelm@15661
   716
      if err then error ("Nonemptiness check failed for datatype " ^ s)
berghofe@14887
   717
      else raise exn;
berghofe@5177
   718
haftmann@21045
   719
    val descr' = flat descr;
wenzelm@8437
   720
    val case_names_induct = mk_case_names_induct descr';
wenzelm@8437
   721
    val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
berghofe@5177
   722
  in
berghofe@26533
   723
    add_datatype_def
wenzelm@8437
   724
      flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   725
      case_names_induct case_names_exhausts thy
berghofe@5177
   726
  end;
berghofe@5177
   727
berghofe@5177
   728
val add_datatype_i = gen_add_datatype cert_typ;
berghofe@14887
   729
val add_datatype = gen_add_datatype read_typ true;
berghofe@5177
   730
wenzelm@6360
   731
haftmann@26111
   732
(** a datatype antiquotation **)
haftmann@26111
   733
haftmann@26111
   734
local
haftmann@26111
   735
haftmann@26111
   736
val sym_datatype = Pretty.str "\\isacommand{datatype}";
haftmann@26111
   737
val sym_binder = Pretty.str "{\\isacharequal}";
haftmann@26111
   738
val sym_of = Pretty.str "of";
haftmann@26111
   739
val sym_sep = Pretty.str "{\\isacharbar}";
haftmann@26111
   740
haftmann@26111
   741
in
haftmann@26111
   742
haftmann@26111
   743
fun args_datatype (ctxt, args) =
haftmann@26111
   744
  let
haftmann@26111
   745
    val (tyco, (ctxt', args')) = Args.tyname (ctxt, args);
haftmann@26111
   746
    val thy = Context.theory_of ctxt';
haftmann@26111
   747
    val spec = the_datatype_spec thy tyco;
haftmann@26111
   748
  in ((tyco, spec), (ctxt', args')) end;
haftmann@26111
   749
haftmann@26111
   750
fun pretty_datatype ctxt (dtco, (vs, cos)) =
haftmann@26111
   751
  let
haftmann@26111
   752
    val ty = Type (dtco, map TFree vs);
haftmann@26111
   753
    fun pretty_typ_br ty =
haftmann@26111
   754
      let
haftmann@26111
   755
        val p = Syntax.pretty_typ ctxt ty;
haftmann@26111
   756
        val s = explode (Pretty.str_of p);
haftmann@26111
   757
      in if member (op =) s " " then Pretty.enclose "(" ")" [p]
haftmann@26111
   758
        else p
haftmann@26111
   759
      end;
haftmann@26111
   760
    fun pretty_constr (co, []) =
haftmann@26111
   761
          Syntax.pretty_term ctxt (Const (co, ty))
haftmann@26111
   762
      | pretty_constr (co, [ty']) =
haftmann@26111
   763
          (Pretty.block o Pretty.breaks)
haftmann@26111
   764
            [Syntax.pretty_term ctxt (Const (co, ty' --> ty)),
haftmann@26111
   765
              sym_of, Syntax.pretty_typ ctxt ty']
haftmann@26111
   766
      | pretty_constr (co, tys) =
haftmann@26111
   767
          (Pretty.block o Pretty.breaks)
haftmann@26111
   768
            (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
haftmann@26111
   769
              sym_of :: map pretty_typ_br tys);
haftmann@26111
   770
  in (Pretty.block o Pretty.breaks) (
haftmann@26111
   771
    sym_datatype
haftmann@26111
   772
    :: Syntax.pretty_typ ctxt ty
haftmann@26111
   773
    :: sym_binder
haftmann@26111
   774
    :: separate sym_sep (map pretty_constr cos)
haftmann@26111
   775
  ) end
haftmann@26111
   776
haftmann@26111
   777
end;
haftmann@18451
   778
wenzelm@6360
   779
(** package setup **)
wenzelm@6360
   780
wenzelm@6360
   781
(* setup theory *)
wenzelm@6360
   782
wenzelm@18708
   783
val setup =
wenzelm@24098
   784
  DatatypeProp.distinctness_limit_setup #>
wenzelm@24098
   785
  Method.add_methods tactic_emulations #>
wenzelm@24098
   786
  simproc_setup #>
haftmann@24626
   787
  trfun_setup #>
wenzelm@24711
   788
  DatatypeInterpretation.init;
wenzelm@6360
   789
wenzelm@6360
   790
wenzelm@6360
   791
(* outer syntax *)
wenzelm@6360
   792
wenzelm@17057
   793
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6360
   794
wenzelm@24867
   795
val _ = OuterSyntax.keywords ["distinct", "inject", "induction"];
wenzelm@24867
   796
wenzelm@6360
   797
val datatype_decl =
wenzelm@6723
   798
  Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
wenzelm@12876
   799
    (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
wenzelm@6360
   800
wenzelm@6360
   801
fun mk_datatype args =
wenzelm@6360
   802
  let
skalberg@15531
   803
    val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
wenzelm@12876
   804
    val specs = map (fn ((((_, vs), t), mx), cons) =>
wenzelm@12876
   805
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@18008
   806
  in snd o add_datatype false names specs end;
wenzelm@6360
   807
wenzelm@24867
   808
val _ =
wenzelm@6723
   809
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
wenzelm@6723
   810
    (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
wenzelm@6360
   811
wenzelm@6385
   812
wenzelm@6385
   813
val rep_datatype_decl =
wenzelm@6723
   814
  Scan.option (Scan.repeat1 P.name) --
wenzelm@22101
   815
    Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 SpecParse.xthms1)) [[]] --
wenzelm@22101
   816
    Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 SpecParse.xthms1)) [[]] --
wenzelm@22101
   817
    (P.$$$ "induction" |-- P.!!! SpecParse.xthm);
wenzelm@6385
   818
haftmann@18008
   819
fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #2 o rep_datatype opt_ts dss iss ind;
wenzelm@6385
   820
wenzelm@24867
   821
val _ =
wenzelm@6723
   822
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
wenzelm@6385
   823
    (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
wenzelm@6385
   824
haftmann@26111
   825
val _ =
haftmann@26111
   826
  ThyOutput.add_commands [("datatype",
haftmann@26111
   827
    ThyOutput.args args_datatype (ThyOutput.output pretty_datatype))];
haftmann@26111
   828
wenzelm@6385
   829
end;
wenzelm@6385
   830
wenzelm@6360
   831
berghofe@5177
   832
end;
berghofe@5177
   833
wenzelm@6360
   834
structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
wenzelm@6360
   835
open BasicDatatypePackage;
wenzelm@15704
   836