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