src/HOL/Tools/Datatype/datatype.ML
author haftmann
Sun Sep 27 20:15:45 2009 +0200 (2009-09-27)
changeset 32717 0e787c721fa3
parent 32712 ec5976f4d3d8
child 32718 45929374f1bd
permissions -rw-r--r--
re-established reasonable inner outline for module
haftmann@31723
     1
(*  Title:      HOL/Tools/datatype.ML
wenzelm@11539
     2
    Author:     Stefan Berghofer, TU Muenchen
berghofe@5177
     3
wenzelm@6360
     4
Datatype package for Isabelle/HOL.
berghofe@5177
     5
*)
berghofe@5177
     6
haftmann@31723
     7
signature DATATYPE =
wenzelm@6360
     8
sig
haftmann@31735
     9
  include DATATYPE_COMMON
haftmann@31735
    10
  val add_datatype : config -> string list -> (string list * binding * mixfix *
haftmann@31783
    11
    (binding * typ list * mixfix) list) list -> theory -> string list * theory
haftmann@31735
    12
  val datatype_cmd : string list -> (string list * binding * mixfix *
haftmann@31735
    13
    (binding * string list * mixfix) list) list -> theory -> theory
haftmann@31781
    14
  val rep_datatype : config -> (string list -> Proof.context -> Proof.context)
haftmann@31735
    15
    -> string list option -> term list -> theory -> Proof.state
haftmann@31735
    16
  val rep_datatype_cmd : string list option -> string list -> theory -> Proof.state
haftmann@31784
    17
  val get_info : theory -> string -> info option
haftmann@31784
    18
  val the_info : theory -> string -> info
haftmann@31784
    19
  val the_descr : theory -> string list
haftmann@31735
    20
    -> descr * (string * sort) list * string list
haftmann@31868
    21
      * string * (string list * string list) * (typ list * typ list)
haftmann@31784
    22
  val the_spec : theory -> string -> (string * sort) list * (string * typ list) list
haftmann@31784
    23
  val get_constrs : theory -> string -> (string * typ) list option
haftmann@31784
    24
  val get_all : theory -> info Symtab.table
haftmann@31784
    25
  val info_of_constr : theory -> string -> info option
haftmann@31784
    26
  val info_of_case : theory -> string -> info option
haftmann@31735
    27
  val interpretation : (config -> string list -> theory -> theory) -> theory -> theory
haftmann@31735
    28
  val distinct_simproc : simproc
bulwahn@32671
    29
  val make_case :  Proof.context -> DatatypeCase.config -> string list -> term ->
haftmann@31735
    30
    (term * term) list -> term * (term * (int * bool)) list
haftmann@31735
    31
  val strip_case : Proof.context -> bool -> term -> (term * (term * term) list) option
haftmann@31735
    32
  val read_typ: theory ->
haftmann@31735
    33
    (typ list * (string * sort) list) * string -> typ list * (string * sort) list
wenzelm@18708
    34
  val setup: theory -> theory
berghofe@5177
    35
end;
berghofe@5177
    36
haftmann@31723
    37
structure Datatype : DATATYPE =
berghofe@5177
    38
struct
berghofe@5177
    39
berghofe@5177
    40
open DatatypeAux;
berghofe@5177
    41
haftmann@32717
    42
(** theory data **)
wenzelm@6360
    43
haftmann@32717
    44
(* data management *)
berghofe@5177
    45
wenzelm@16430
    46
structure DatatypesData = TheoryDataFun
wenzelm@22846
    47
(
berghofe@22777
    48
  type T =
haftmann@31735
    49
    {types: info Symtab.table,
haftmann@31735
    50
     constrs: info Symtab.table,
haftmann@31735
    51
     cases: info Symtab.table};
berghofe@5177
    52
berghofe@22777
    53
  val empty =
berghofe@22777
    54
    {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
wenzelm@6556
    55
  val copy = I;
wenzelm@16430
    56
  val extend = I;
berghofe@22777
    57
  fun merge _
berghofe@22777
    58
    ({types = types1, constrs = constrs1, cases = cases1},
berghofe@22777
    59
     {types = types2, constrs = constrs2, cases = cases2}) =
berghofe@22777
    60
    {types = Symtab.merge (K true) (types1, types2),
berghofe@22777
    61
     constrs = Symtab.merge (K true) (constrs1, constrs2),
berghofe@22777
    62
     cases = Symtab.merge (K true) (cases1, cases2)};
wenzelm@22846
    63
);
berghofe@5177
    64
haftmann@31784
    65
val get_all = #types o DatatypesData.get;
haftmann@32717
    66
val get_info = Symtab.lookup o get_all;
haftmann@32717
    67
fun the_info thy name = (case get_info thy name of
haftmann@32717
    68
      SOME info => info
haftmann@32717
    69
    | NONE => error ("Unknown datatype " ^ quote name));
berghofe@5177
    70
haftmann@32717
    71
val info_of_constr = Symtab.lookup o #constrs o DatatypesData.get;
haftmann@32717
    72
val info_of_case = Symtab.lookup o #cases o DatatypesData.get;
berghofe@5177
    73
haftmann@32717
    74
fun register (dt_infos : (string * info) list) =
haftmann@32717
    75
  DatatypesData.map (fn {types, constrs, cases} =>
berghofe@22777
    76
    {types = fold Symtab.update dt_infos types,
haftmann@31208
    77
     constrs = fold Symtab.default (*conservative wrt. overloaded constructors*)
berghofe@22777
    78
       (maps (fn (_, info as {descr, index, ...}) => map (rpair info o fst)
berghofe@22777
    79
          (#3 (the (AList.lookup op = descr index)))) dt_infos) constrs,
berghofe@22777
    80
     cases = fold Symtab.update
berghofe@22777
    81
       (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)
berghofe@22777
    82
       cases});
berghofe@22777
    83
haftmann@32717
    84
(* complex queries *)
berghofe@7015
    85
haftmann@31784
    86
fun the_spec thy dtco =
haftmann@18518
    87
  let
haftmann@31784
    88
    val info as { descr, index, sorts = raw_sorts, ... } = the_info thy dtco;
haftmann@26093
    89
    val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr index;
haftmann@26093
    90
    val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
haftmann@26093
    91
      o DatatypeAux.dest_DtTFree) dtys;
haftmann@26093
    92
    val cos = map
haftmann@26093
    93
      (fn (co, tys) => (co, map (DatatypeAux.typ_of_dtyp descr sorts) tys)) raw_cos;
haftmann@26093
    94
  in (sorts, cos) end;
haftmann@18518
    95
haftmann@31784
    96
fun the_descr thy (raw_tycos as raw_tyco :: _) =
haftmann@31604
    97
  let
haftmann@31784
    98
    val info = the_info thy raw_tyco;
haftmann@31604
    99
    val descr = #descr info;
haftmann@31604
   100
haftmann@31604
   101
    val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr (#index info);
haftmann@31604
   102
    val vs = map ((fn v => (v, (the o AList.lookup (op =) (#sorts info)) v))
haftmann@31604
   103
      o dest_DtTFree) dtys;
haftmann@31604
   104
haftmann@31604
   105
    fun is_DtTFree (DtTFree _) = true
haftmann@31604
   106
      | is_DtTFree _ = false
haftmann@31604
   107
    val k = find_index (fn (_, (_, dTs, _)) => not (forall is_DtTFree dTs)) descr;
haftmann@31604
   108
    val protoTs as (dataTs, _) = chop k descr
haftmann@31604
   109
      |> (pairself o map) (fn (_, (tyco, dTs, _)) => (tyco, map (typ_of_dtyp descr vs) dTs));
haftmann@31604
   110
    
haftmann@31604
   111
    val tycos = map fst dataTs;
haftmann@31604
   112
    val _ = if gen_eq_set (op =) (tycos, raw_tycos) then ()
haftmann@31604
   113
      else error ("Type constructors " ^ commas (map quote raw_tycos)
haftmann@32374
   114
        ^ " do not belong exhaustively to one mutual recursive datatype");
haftmann@31604
   115
haftmann@31604
   116
    val (Ts, Us) = (pairself o map) Type protoTs;
haftmann@31604
   117
haftmann@31604
   118
    val names = map Long_Name.base_name (the_default tycos (#alt_names info));
haftmann@31604
   119
    val (auxnames, _) = Name.make_context names
haftmann@31868
   120
      |> fold_map (yield_singleton Name.variants o name_of_typ) Us;
haftmann@31868
   121
    val prefix = space_implode "_" names;
haftmann@31604
   122
haftmann@31868
   123
  in (descr, vs, tycos, prefix, (names, auxnames), (Ts, Us)) end;
haftmann@31604
   124
haftmann@31784
   125
fun get_constrs thy dtco =
haftmann@31784
   126
  case try (the_spec thy) dtco
haftmann@19346
   127
   of SOME (sorts, cos) =>
haftmann@19346
   128
        let
haftmann@19346
   129
          fun subst (v, sort) = TVar ((v, 0), sort);
haftmann@19346
   130
          fun subst_ty (TFree v) = subst v
haftmann@19346
   131
            | subst_ty ty = ty;
haftmann@19346
   132
          val dty = Type (dtco, map subst sorts);
haftmann@19346
   133
          fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
haftmann@19346
   134
        in SOME (map mk_co cos) end
haftmann@19346
   135
    | NONE => NONE;
haftmann@18518
   136
berghofe@5177
   137
haftmann@32717
   138
(** various auxiliary **)
wenzelm@8437
   139
haftmann@32717
   140
(* simplification procedure for showing distinctness of constructors *)
berghofe@7015
   141
berghofe@7060
   142
fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
berghofe@7060
   143
  | stripT p = p;
berghofe@7060
   144
berghofe@7060
   145
fun stripC (i, f $ x) = stripC (i + 1, f)
berghofe@7060
   146
  | stripC p = p;
berghofe@7060
   147
berghofe@7015
   148
val distinctN = "constr_distinct";
berghofe@7015
   149
haftmann@31784
   150
fun distinct_rule thy ss tname eq_t = case #distinct (the_info thy tname) of
berghofe@26533
   151
    FewConstrs thms => Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
haftmann@25537
   152
      (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
haftmann@25537
   153
        atac 2, resolve_tac thms 1, etac FalseE 1]))
haftmann@25537
   154
  | ManyConstrs (thm, simpset) =>
haftmann@25537
   155
      let
haftmann@25537
   156
        val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
wenzelm@26343
   157
          map (PureThy.get_thm (ThyInfo.the_theory "Datatype" thy))
haftmann@25537
   158
            ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"];
haftmann@25537
   159
      in
haftmann@25537
   160
        Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
haftmann@25537
   161
        (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
haftmann@25537
   162
          full_simp_tac (Simplifier.inherit_context ss simpset) 1,
haftmann@25537
   163
          REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
haftmann@25537
   164
          eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
haftmann@25537
   165
          etac FalseE 1]))
haftmann@25537
   166
      end;
haftmann@25537
   167
haftmann@32717
   168
fun get_constr thy dtco =
haftmann@32717
   169
  get_info thy dtco
haftmann@32717
   170
  |> Option.map (fn { descr, index, ... } => (#3 o the o AList.lookup (op =) descr) index);
haftmann@32717
   171
wenzelm@19539
   172
fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
berghofe@7060
   173
  (case (stripC (0, t1), stripC (0, t2)) of
berghofe@7060
   174
     ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
berghofe@7060
   175
         (case (stripT (0, T1), stripT (0, T2)) of
berghofe@7060
   176
            ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
berghofe@7060
   177
                if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
haftmann@32717
   178
                   (case get_constr thy tname1 of
haftmann@32717
   179
                      SOME constrs => let val cnames = map fst constrs
berghofe@7015
   180
                        in if cname1 mem cnames andalso cname2 mem cnames then
haftmann@25537
   181
                             SOME (distinct_rule thy ss tname1
haftmann@32717
   182
                               (Logic.mk_equals (t, HOLogic.false_const)))
skalberg@15531
   183
                           else NONE
berghofe@7015
   184
                        end
skalberg@15531
   185
                    | NONE => NONE)
skalberg@15531
   186
                else NONE
skalberg@15531
   187
          | _ => NONE)
skalberg@15531
   188
   | _ => NONE)
wenzelm@20054
   189
  | distinct_proc _ _ _ = NONE;
berghofe@7015
   190
wenzelm@13462
   191
val distinct_simproc =
wenzelm@29064
   192
  Simplifier.simproc @{theory HOL} distinctN ["s = t"] distinct_proc;
berghofe@7015
   193
berghofe@7015
   194
val dist_ss = HOL_ss addsimprocs [distinct_simproc];
berghofe@7015
   195
berghofe@7015
   196
val simproc_setup =
wenzelm@26496
   197
  Simplifier.map_simpset (fn ss => ss addsimprocs [distinct_simproc]);
berghofe@7015
   198
haftmann@32717
   199
(* prepare datatype specifications *)
berghofe@5177
   200
wenzelm@27277
   201
fun read_typ thy ((Ts, sorts), str) =
berghofe@5177
   202
  let
wenzelm@27277
   203
    val ctxt = ProofContext.init thy
wenzelm@27277
   204
      |> fold (Variable.declare_typ o TFree) sorts;
wenzelm@27277
   205
    val T = Syntax.read_typ ctxt str;
wenzelm@27277
   206
  in (Ts @ [T], Term.add_tfreesT T sorts) end;
berghofe@5177
   207
berghofe@5177
   208
fun cert_typ sign ((Ts, sorts), raw_T) =
berghofe@5177
   209
  let
berghofe@5177
   210
    val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
berghofe@5177
   211
      TYPE (msg, _, _) => error msg;
wenzelm@27277
   212
    val sorts' = Term.add_tfreesT T sorts;
berghofe@5177
   213
  in (Ts @ [T],
wenzelm@18964
   214
      case duplicates (op =) (map fst sorts') of
berghofe@5177
   215
         [] => sorts'
berghofe@5177
   216
       | dups => error ("Inconsistent sort constraints for " ^ commas dups))
berghofe@5177
   217
  end;
berghofe@5177
   218
haftmann@32717
   219
(* arrange data entries *)
berghofe@5177
   220
haftmann@32712
   221
fun make_dt_info alt_names descr sorts inducts reccomb_names rec_thms
haftmann@32712
   222
    ((((((((((i, (_, (tname, _, _))), case_name), case_thms),
haftmann@32712
   223
      exhaust_thm), distinct_thm), inject), splits), nchotomy), case_cong), weak_case_cong) =
wenzelm@10121
   224
  (tname,
wenzelm@10121
   225
   {index = i,
berghofe@25677
   226
    alt_names = alt_names,
wenzelm@10121
   227
    descr = descr,
berghofe@18319
   228
    sorts = sorts,
wenzelm@10121
   229
    rec_names = reccomb_names,
wenzelm@10121
   230
    rec_rewrites = rec_thms,
wenzelm@10121
   231
    case_name = case_name,
wenzelm@10121
   232
    case_rewrites = case_thms,
haftmann@32712
   233
    inducts = inducts,
haftmann@32712
   234
    exhaust = exhaust_thm,
wenzelm@10121
   235
    distinct = distinct_thm,
wenzelm@10121
   236
    inject = inject,
haftmann@32712
   237
    splits = splits,
wenzelm@10121
   238
    nchotomy = nchotomy,
wenzelm@10121
   239
    case_cong = case_cong,
wenzelm@10121
   240
    weak_case_cong = weak_case_cong});
berghofe@5177
   241
haftmann@32717
   242
(* case names *)
haftmann@32717
   243
haftmann@32717
   244
local
haftmann@32717
   245
haftmann@32717
   246
fun dt_recs (DtTFree _) = []
haftmann@32717
   247
  | dt_recs (DtType (_, dts)) = maps dt_recs dts
haftmann@32717
   248
  | dt_recs (DtRec i) = [i];
haftmann@32717
   249
haftmann@32717
   250
fun dt_cases (descr: descr) (_, args, constrs) =
haftmann@32717
   251
  let
haftmann@32717
   252
    fun the_bname i = Long_Name.base_name (#1 (the (AList.lookup (op =) descr i)));
haftmann@32717
   253
    val bnames = map the_bname (distinct (op =) (maps dt_recs args));
haftmann@32717
   254
  in map (fn (c, _) => space_implode "_" (Long_Name.base_name c :: bnames)) constrs end;
haftmann@32717
   255
haftmann@32717
   256
fun induct_cases descr =
haftmann@32717
   257
  DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
haftmann@32717
   258
haftmann@32717
   259
fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
haftmann@32717
   260
haftmann@32717
   261
in
haftmann@32717
   262
haftmann@32717
   263
fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
haftmann@32717
   264
haftmann@32717
   265
fun mk_case_names_exhausts descr new =
haftmann@32717
   266
  map (RuleCases.case_names o exhaust_cases descr o #1)
haftmann@32717
   267
    (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
haftmann@32717
   268
haftmann@32717
   269
end;
haftmann@32717
   270
haftmann@32717
   271
(* note rules and interpretations *)
haftmann@32717
   272
haftmann@32717
   273
fun add_rules simps case_thms rec_thms inject distinct
haftmann@32717
   274
                  weak_case_congs cong_att =
haftmann@32717
   275
  PureThy.add_thmss [((Binding.name "simps", simps), []),
haftmann@32717
   276
    ((Binding.empty, flat case_thms @
haftmann@32717
   277
          flat distinct @ rec_thms), [Simplifier.simp_add]),
haftmann@32717
   278
    ((Binding.empty, rec_thms), [Code.add_default_eqn_attribute]),
haftmann@32717
   279
    ((Binding.empty, flat inject), [iff_add]),
haftmann@32717
   280
    ((Binding.empty, map (fn th => th RS notE) (flat distinct)), [Classical.safe_elim NONE]),
haftmann@32717
   281
    ((Binding.empty, weak_case_congs), [cong_att])]
haftmann@32717
   282
  #> snd;
haftmann@32717
   283
haftmann@32717
   284
fun add_cases_induct infos inducts thy =
haftmann@32717
   285
  let
haftmann@32717
   286
    fun named_rules (name, {index, exhaust, ...}: info) =
haftmann@32717
   287
      [((Binding.empty, nth inducts index), [Induct.induct_type name]),
haftmann@32717
   288
       ((Binding.empty, exhaust), [Induct.cases_type name])];
haftmann@32717
   289
    fun unnamed_rule i =
haftmann@32717
   290
      ((Binding.empty, nth inducts i), [Thm.kind_internal, Induct.induct_type ""]);
haftmann@32717
   291
  in
haftmann@32717
   292
    thy |> PureThy.add_thms
haftmann@32717
   293
      (maps named_rules infos @
haftmann@32717
   294
        map unnamed_rule (length infos upto length inducts - 1)) |> snd
haftmann@32717
   295
    |> PureThy.add_thmss [((Binding.name "inducts", inducts), [])] |> snd
haftmann@32717
   296
  end;
haftmann@32717
   297
haftmann@31668
   298
structure DatatypeInterpretation = InterpretationFun
haftmann@31735
   299
  (type T = config * string list val eq: T * T -> bool = eq_snd op =);
haftmann@31668
   300
fun interpretation f = DatatypeInterpretation.interpretation (uncurry f);
haftmann@24626
   301
haftmann@32717
   302
(* translation rules for case *)
berghofe@5177
   303
haftmann@32717
   304
fun make_case ctxt = DatatypeCase.make_case
haftmann@32717
   305
  (info_of_constr (ProofContext.theory_of ctxt)) ctxt;
haftmann@32717
   306
haftmann@32717
   307
fun strip_case ctxt = DatatypeCase.strip_case
haftmann@32717
   308
  (info_of_case (ProofContext.theory_of ctxt));
berghofe@5177
   309
haftmann@32717
   310
fun add_case_tr' case_names thy =
haftmann@32717
   311
  Sign.add_advanced_trfuns ([], [],
haftmann@32717
   312
    map (fn case_name =>
haftmann@32717
   313
      let val case_name' = Sign.const_syntax_name thy case_name
haftmann@32717
   314
      in (case_name', DatatypeCase.case_tr' info_of_case case_name')
haftmann@32717
   315
      end) case_names, []) thy;
berghofe@5177
   316
haftmann@32717
   317
val trfun_setup =
haftmann@32717
   318
  Sign.add_advanced_trfuns ([],
haftmann@32717
   319
    [("_case_syntax", DatatypeCase.case_tr true info_of_constr)],
haftmann@32717
   320
    [], []);
haftmann@32717
   321
haftmann@32717
   322
(* document antiquotation *)
berghofe@5177
   323
haftmann@32717
   324
val _ = ThyOutput.antiquotation "datatype" Args.tyname
haftmann@32717
   325
  (fn {source = src, context = ctxt, ...} => fn dtco =>
haftmann@32717
   326
    let
haftmann@32717
   327
      val thy = ProofContext.theory_of ctxt;
haftmann@32717
   328
      val (vs, cos) = the_spec thy dtco;
haftmann@32717
   329
      val ty = Type (dtco, map TFree vs);
haftmann@32717
   330
      fun pretty_typ_bracket (ty as Type (_, _ :: _)) =
haftmann@32717
   331
            Pretty.enclose "(" ")" [Syntax.pretty_typ ctxt ty]
haftmann@32717
   332
        | pretty_typ_bracket ty =
haftmann@32717
   333
            Syntax.pretty_typ ctxt ty;
haftmann@32717
   334
      fun pretty_constr (co, tys) =
haftmann@32717
   335
        (Pretty.block o Pretty.breaks)
haftmann@32717
   336
          (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
haftmann@32717
   337
            map pretty_typ_bracket tys);
haftmann@32717
   338
      val pretty_datatype =
haftmann@32717
   339
        Pretty.block
haftmann@32717
   340
          (Pretty.command "datatype" :: Pretty.brk 1 ::
haftmann@32717
   341
           Syntax.pretty_typ ctxt ty ::
haftmann@32717
   342
           Pretty.str " =" :: Pretty.brk 1 ::
haftmann@32717
   343
           flat (separate [Pretty.brk 1, Pretty.str "| "]
haftmann@32717
   344
             (map (single o pretty_constr) cos)));
haftmann@32717
   345
    in ThyOutput.output (ThyOutput.maybe_pretty_source (K pretty_datatype) src [()]) end);
berghofe@5177
   346
berghofe@5177
   347
haftmann@32717
   348
(** declare existing type as datatype **)
berghofe@5177
   349
haftmann@31735
   350
fun prove_rep_datatype (config : config) alt_names new_type_names descr sorts induct inject half_distinct thy =
berghofe@5177
   351
  let
haftmann@27104
   352
    val ((_, [induct']), _) =
wenzelm@31794
   353
      Variable.importT [induct] (Variable.thm_context induct);
berghofe@5177
   354
berghofe@5177
   355
    fun err t = error ("Ill-formed predicate in induction rule: " ^
haftmann@27104
   356
      Syntax.string_of_term_global thy t);
berghofe@5177
   357
berghofe@5177
   358
    fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
berghofe@25888
   359
          ((tname, map (fst o dest_TFree) Ts) handle TERM _ => err t)
berghofe@5177
   360
      | get_typ t = err t;
haftmann@27104
   361
    val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induct')));
berghofe@5177
   362
haftmann@31784
   363
    val dt_info = get_all thy;
berghofe@5177
   364
haftmann@27300
   365
    val distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
haftmann@21419
   366
    val (case_names_induct, case_names_exhausts) =
haftmann@21419
   367
      (mk_case_names_induct descr, mk_case_names_exhausts descr (map #1 dtnames));
wenzelm@8437
   368
haftmann@31668
   369
    val _ = message config ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   370
haftmann@27104
   371
    val (casedist_thms, thy2) = thy |>
haftmann@31668
   372
      DatatypeAbsProofs.prove_casedist_thms config new_type_names [descr] sorts induct
wenzelm@8437
   373
        case_names_exhausts;
haftmann@18314
   374
    val ((reccomb_names, rec_thms), thy3) = DatatypeAbsProofs.prove_primrec_thms
haftmann@31668
   375
      config new_type_names [descr] sorts dt_info inject distinct
haftmann@27104
   376
      (Simplifier.theory_context thy2 dist_ss) induct thy2;
haftmann@31668
   377
    val ((case_thms, case_names), thy4) = DatatypeAbsProofs.prove_case_thms
haftmann@31668
   378
      config new_type_names [descr] sorts reccomb_names rec_thms thy3;
haftmann@18314
   379
    val (split_thms, thy5) = DatatypeAbsProofs.prove_split_thms
haftmann@31668
   380
      config new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
haftmann@31668
   381
    val (nchotomys, thy6) = DatatypeAbsProofs.prove_nchotomys config new_type_names
berghofe@5177
   382
      [descr] sorts casedist_thms thy5;
haftmann@18314
   383
    val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   384
      [descr] sorts nchotomys case_thms thy6;
haftmann@18314
   385
    val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   386
      [descr] sorts thy7;
berghofe@5177
   387
haftmann@27104
   388
    val ((_, [induct']), thy10) =
haftmann@24699
   389
      thy8
haftmann@18377
   390
      |> store_thmss "inject" new_type_names inject
haftmann@18377
   391
      ||>> store_thmss "distinct" new_type_names distinct
wenzelm@24712
   392
      ||> Sign.add_path (space_implode "_" new_type_names)
haftmann@29579
   393
      ||>> PureThy.add_thms [((Binding.name "induct", induct), [case_names_induct])];
haftmann@32712
   394
    val inducts = Project_Rule.projections (ProofContext.init thy10) induct';
wenzelm@9149
   395
haftmann@32712
   396
    val dt_infos = map (make_dt_info alt_names descr sorts (inducts, induct') reccomb_names rec_thms)
wenzelm@10121
   397
      ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
haftmann@32712
   398
        map FewConstrs distinct ~~ inject ~~ split_thms ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   399
haftmann@24699
   400
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
haftmann@31781
   401
    val dt_names = map fst dt_infos;
berghofe@5177
   402
haftmann@19599
   403
    val thy11 =
haftmann@19599
   404
      thy10
berghofe@22777
   405
      |> add_case_tr' case_names
haftmann@24699
   406
      |> add_rules simps case_thms rec_thms inject distinct
haftmann@19599
   407
           weak_case_congs (Simplifier.attrib (op addcongs))
haftmann@32717
   408
      |> register dt_infos
haftmann@32712
   409
      |> add_cases_induct dt_infos inducts
wenzelm@24712
   410
      |> Sign.parent_path
haftmann@19599
   411
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
haftmann@19599
   412
      |> snd
haftmann@31781
   413
      |> DatatypeInterpretation.data (config, dt_names);
haftmann@31781
   414
  in (dt_names, thy11) end;
berghofe@5177
   415
haftmann@31735
   416
fun gen_rep_datatype prep_term (config : config) after_qed alt_names raw_ts thy =
haftmann@27104
   417
  let
haftmann@27104
   418
    fun constr_of_term (Const (c, T)) = (c, T)
haftmann@27104
   419
      | constr_of_term t =
haftmann@27104
   420
          error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
haftmann@27104
   421
    fun no_constr (c, T) = error ("Bad constructor: "
haftmann@27104
   422
      ^ Sign.extern_const thy c ^ "::"
haftmann@27104
   423
      ^ Syntax.string_of_typ_global thy T);
haftmann@27104
   424
    fun type_of_constr (cT as (_, T)) =
haftmann@27104
   425
      let
wenzelm@29270
   426
        val frees = OldTerm.typ_tfrees T;
haftmann@27104
   427
        val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) T
haftmann@27104
   428
          handle TYPE _ => no_constr cT
haftmann@27104
   429
        val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
haftmann@27104
   430
        val _ = if length frees <> length vs then no_constr cT else ();
haftmann@27104
   431
      in (tyco, (vs, cT)) end;
haftmann@27104
   432
haftmann@27104
   433
    val raw_cs = AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
haftmann@27104
   434
    val _ = case map_filter (fn (tyco, _) =>
haftmann@31784
   435
        if Symtab.defined (get_all thy) tyco then SOME tyco else NONE) raw_cs
haftmann@27104
   436
     of [] => ()
haftmann@27104
   437
      | tycos => error ("Type(s) " ^ commas (map quote tycos)
haftmann@27104
   438
          ^ " already represented inductivly");
haftmann@27104
   439
    val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
haftmann@27104
   440
    val ms = case distinct (op =) (map length raw_vss)
haftmann@27104
   441
     of [n] => 0 upto n - 1
haftmann@27104
   442
      | _ => error ("Different types in given constructors");
haftmann@27104
   443
    fun inter_sort m = map (fn xs => nth xs m) raw_vss
haftmann@27104
   444
      |> Library.foldr1 (Sorts.inter_sort (Sign.classes_of thy))
haftmann@27104
   445
    val sorts = map inter_sort ms;
haftmann@27104
   446
    val vs = Name.names Name.context Name.aT sorts;
haftmann@27104
   447
haftmann@27104
   448
    fun norm_constr (raw_vs, (c, T)) = (c, map_atyps
haftmann@27104
   449
      (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
haftmann@27104
   450
haftmann@27104
   451
    val cs = map (apsnd (map norm_constr)) raw_cs;
haftmann@27104
   452
    val dtyps_of_typ = map (dtyp_of_typ (map (rpair (map fst vs) o fst) cs))
haftmann@27104
   453
      o fst o strip_type;
wenzelm@30364
   454
    val new_type_names = map Long_Name.base_name (the_default (map fst cs) alt_names);
haftmann@27104
   455
haftmann@27104
   456
    fun mk_spec (i, (tyco, constr)) = (i, (tyco,
haftmann@27104
   457
      map (DtTFree o fst) vs,
haftmann@27104
   458
      (map o apsnd) dtyps_of_typ constr))
haftmann@27104
   459
    val descr = map_index mk_spec cs;
haftmann@27104
   460
    val injs = DatatypeProp.make_injs [descr] vs;
haftmann@27300
   461
    val half_distincts = map snd (DatatypeProp.make_distincts [descr] vs);
haftmann@27104
   462
    val ind = DatatypeProp.make_ind [descr] vs;
haftmann@27300
   463
    val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
haftmann@27104
   464
haftmann@27104
   465
    fun after_qed' raw_thms =
haftmann@27104
   466
      let
haftmann@27300
   467
        val [[[induct]], injs, half_distincts] =
haftmann@27104
   468
          unflat rules (map Drule.zero_var_indexes_list raw_thms);
haftmann@27104
   469
            (*FIXME somehow dubious*)
haftmann@27104
   470
      in
haftmann@27104
   471
        ProofContext.theory_result
haftmann@31668
   472
          (prove_rep_datatype config alt_names new_type_names descr vs induct injs half_distincts)
haftmann@27104
   473
        #-> after_qed
haftmann@27104
   474
      end;
haftmann@27104
   475
  in
haftmann@27104
   476
    thy
haftmann@27104
   477
    |> ProofContext.init
haftmann@27104
   478
    |> Proof.theorem_i NONE after_qed' ((map o map) (rpair []) (flat rules))
haftmann@27104
   479
  end;
haftmann@27104
   480
haftmann@27104
   481
val rep_datatype = gen_rep_datatype Sign.cert_term;
haftmann@31735
   482
val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global default_config (K I);
wenzelm@6385
   483
berghofe@5177
   484
haftmann@32717
   485
(** definitional introduction of datatypes **)
wenzelm@11958
   486
haftmann@32717
   487
fun add_datatype_def (config : config) new_type_names descr sorts types_syntax constr_syntax dt_info
haftmann@32717
   488
    case_names_induct case_names_exhausts thy =
haftmann@32717
   489
  let
haftmann@32717
   490
    val _ = message config ("Proofs for datatype(s) " ^ commas_quote new_type_names);
haftmann@32717
   491
haftmann@32717
   492
    val ((inject, distinct, dist_rewrites, simproc_dists, induct), thy2) = thy |>
haftmann@32717
   493
      DatatypeRepProofs.representation_proofs config dt_info new_type_names descr sorts
haftmann@32717
   494
        types_syntax constr_syntax case_names_induct;
haftmann@32717
   495
    val inducts = Project_Rule.projections (ProofContext.init thy2) induct;
haftmann@32717
   496
haftmann@32717
   497
    val (casedist_thms, thy3) = DatatypeAbsProofs.prove_casedist_thms config new_type_names descr
haftmann@32717
   498
      sorts induct case_names_exhausts thy2;
haftmann@32717
   499
    val ((reccomb_names, rec_thms), thy4) = DatatypeAbsProofs.prove_primrec_thms
haftmann@32717
   500
      config new_type_names descr sorts dt_info inject dist_rewrites
haftmann@32717
   501
      (Simplifier.theory_context thy3 dist_ss) induct thy3;
haftmann@32717
   502
    val ((case_thms, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
haftmann@32717
   503
      config new_type_names descr sorts reccomb_names rec_thms thy4;
haftmann@32717
   504
    val (split_thms, thy7) = DatatypeAbsProofs.prove_split_thms config new_type_names
haftmann@32717
   505
      descr sorts inject dist_rewrites casedist_thms case_thms thy6;
haftmann@32717
   506
    val (nchotomys, thy8) = DatatypeAbsProofs.prove_nchotomys config new_type_names
haftmann@32717
   507
      descr sorts casedist_thms thy7;
haftmann@32717
   508
    val (case_congs, thy9) = DatatypeAbsProofs.prove_case_congs new_type_names
haftmann@32717
   509
      descr sorts nchotomys case_thms thy8;
haftmann@32717
   510
    val (weak_case_congs, thy10) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
haftmann@32717
   511
      descr sorts thy9;
haftmann@32717
   512
haftmann@32717
   513
    val dt_infos = map
haftmann@32717
   514
      (make_dt_info (SOME new_type_names) (flat descr) sorts (inducts, induct) reccomb_names rec_thms)
haftmann@32717
   515
      ((0 upto length (hd descr) - 1) ~~ hd descr ~~ case_names ~~ case_thms ~~
haftmann@32717
   516
        casedist_thms ~~ simproc_dists ~~ inject ~~ split_thms ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
haftmann@32717
   517
haftmann@32717
   518
    val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
haftmann@32717
   519
    val dt_names = map fst dt_infos;
haftmann@32717
   520
haftmann@32717
   521
    val thy12 =
haftmann@32717
   522
      thy10
haftmann@32717
   523
      |> add_case_tr' case_names
haftmann@32717
   524
      |> Sign.add_path (space_implode "_" new_type_names)
haftmann@32717
   525
      |> add_rules simps case_thms rec_thms inject distinct
haftmann@32717
   526
          weak_case_congs (Simplifier.attrib (op addcongs))
haftmann@32717
   527
      |> register dt_infos
haftmann@32717
   528
      |> add_cases_induct dt_infos inducts
haftmann@32717
   529
      |> Sign.parent_path
haftmann@32717
   530
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
haftmann@32717
   531
      |> DatatypeInterpretation.data (config, map fst dt_infos);
haftmann@32717
   532
  in (dt_names, thy12) end;
berghofe@5177
   533
haftmann@31735
   534
fun gen_add_datatype prep_typ (config : config) new_type_names dts thy =
berghofe@5177
   535
  let
wenzelm@20820
   536
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   537
berghofe@5177
   538
    (* this theory is used just for parsing *)
berghofe@5177
   539
berghofe@5177
   540
    val tmp_thy = thy |>
wenzelm@5892
   541
      Theory.copy |>
wenzelm@24712
   542
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   543
        (tname, length tvs, mx)) dts);
berghofe@5177
   544
berghofe@5661
   545
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   546
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
wenzelm@30345
   547
      let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
wenzelm@18964
   548
      in (case duplicates (op =) tvs of
berghofe@5661
   549
            [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
berghofe@5661
   550
                  else error ("Mutually recursive datatypes must have same type parameters")
wenzelm@30345
   551
          | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
berghofe@5177
   552
              " : " ^ commas dups))
berghofe@5177
   553
      end) dts);
berghofe@5177
   554
wenzelm@18964
   555
    val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
berghofe@5177
   556
      [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   557
berghofe@31361
   558
    fun prep_dt_spec ((tvs, tname, mx, constrs), tname') (dts', constr_syntax, sorts, i) =
berghofe@5177
   559
      let
haftmann@21045
   560
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
berghofe@5279
   561
          let
haftmann@20597
   562
            val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
wenzelm@29270
   563
            val _ = (case fold (curry OldTerm.add_typ_tfree_names) cargs' [] \\ tvs of
berghofe@5279
   564
                [] => ()
berghofe@5279
   565
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@32124
   566
          in (constrs @ [(Sign.full_name_path tmp_thy tname'
wenzelm@30345
   567
                  (Binding.map_name (Syntax.const_name mx') cname),
berghofe@5177
   568
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   569
              constr_syntax' @ [(cname, mx')], sorts'')
wenzelm@30345
   570
          end handle ERROR msg => cat_error msg
wenzelm@30345
   571
           ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
wenzelm@30345
   572
            " of datatype " ^ quote (Binding.str_of tname));
berghofe@5177
   573
berghofe@5177
   574
        val (constrs', constr_syntax', sorts') =
haftmann@21045
   575
          fold prep_constr constrs ([], [], sorts)
berghofe@5177
   576
wenzelm@8405
   577
      in
wenzelm@18964
   578
        case duplicates (op =) (map fst constrs') of
berghofe@5177
   579
           [] =>
wenzelm@30345
   580
             (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
berghofe@5177
   581
                map DtTFree tvs, constrs'))],
berghofe@5177
   582
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   583
         | dups => error ("Duplicate constructors " ^ commas dups ^
wenzelm@30345
   584
             " in datatype " ^ quote (Binding.str_of tname))
berghofe@5177
   585
      end;
berghofe@5177
   586
berghofe@31361
   587
    val (dts', constr_syntax, sorts', i) =
berghofe@31361
   588
      fold prep_dt_spec (dts ~~ new_type_names) ([], [], [], 0);
haftmann@20597
   589
    val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
haftmann@31784
   590
    val dt_info = get_all thy;
haftmann@20597
   591
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
berghofe@14887
   592
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
haftmann@31668
   593
      if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
berghofe@14887
   594
      else raise exn;
berghofe@5177
   595
haftmann@21045
   596
    val descr' = flat descr;
wenzelm@8437
   597
    val case_names_induct = mk_case_names_induct descr';
wenzelm@8437
   598
    val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
berghofe@5177
   599
  in
berghofe@26533
   600
    add_datatype_def
haftmann@31735
   601
      (config : config) new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   602
      case_names_induct case_names_exhausts thy
berghofe@5177
   603
  end;
berghofe@5177
   604
haftmann@27104
   605
val add_datatype = gen_add_datatype cert_typ;
haftmann@31735
   606
val datatype_cmd = snd ooo gen_add_datatype read_typ default_config;
berghofe@5177
   607
wenzelm@6360
   608
wenzelm@6360
   609
(** package setup **)
wenzelm@6360
   610
wenzelm@6360
   611
(* setup theory *)
wenzelm@6360
   612
wenzelm@18708
   613
val setup =
haftmann@27002
   614
  DatatypeRepProofs.distinctness_limit_setup #>
wenzelm@24098
   615
  simproc_setup #>
haftmann@24626
   616
  trfun_setup #>
wenzelm@24711
   617
  DatatypeInterpretation.init;
wenzelm@6360
   618
wenzelm@6360
   619
(* outer syntax *)
wenzelm@6360
   620
haftmann@31735
   621
local
wenzelm@6360
   622
haftmann@31735
   623
structure P = OuterParse and K = OuterKeyword
wenzelm@6360
   624
haftmann@31735
   625
fun prep_datatype_decls args =
wenzelm@6360
   626
  let
wenzelm@30345
   627
    val names = map
wenzelm@30345
   628
      (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
wenzelm@12876
   629
    val specs = map (fn ((((_, vs), t), mx), cons) =>
wenzelm@12876
   630
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@31735
   631
  in (names, specs) end;
haftmann@31735
   632
haftmann@31735
   633
val parse_datatype_decl =
haftmann@31735
   634
  (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
haftmann@31735
   635
    (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
haftmann@31735
   636
haftmann@31735
   637
val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
haftmann@31735
   638
haftmann@31735
   639
in
wenzelm@6360
   640
wenzelm@24867
   641
val _ =
wenzelm@6723
   642
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
haftmann@31735
   643
    (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
wenzelm@6360
   644
wenzelm@24867
   645
val _ =
haftmann@27104
   646
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_goal
haftmann@27104
   647
    (Scan.option (P.$$$ "(" |-- Scan.repeat1 P.name --| P.$$$ ")") -- Scan.repeat1 P.term
haftmann@27104
   648
      >> (fn (alt_names, ts) => Toplevel.print
haftmann@27104
   649
           o Toplevel.theory_to_proof (rep_datatype_cmd alt_names ts)));
wenzelm@6385
   650
wenzelm@30391
   651
end;
wenzelm@30391
   652
wenzelm@6385
   653
end;
wenzelm@6385
   654