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