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