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