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