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