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