src/HOL/Tools/datatype_package.ML
author wenzelm
Mon May 24 21:57:13 1999 +0200 (1999-05-24)
changeset 6723 f342449d73ca
parent 6556 daa00919502b
child 6729 b6e167580a32
permissions -rw-r--r--
outer syntax keyword classification;
no open OuterParse;
berghofe@5177
     1
(*  Title:      HOL/Tools/datatype_package.ML
berghofe@5177
     2
    ID:         $Id$
berghofe@5177
     3
    Author:     Stefan Berghofer
berghofe@5177
     4
    Copyright   1998  TU Muenchen
berghofe@5177
     5
wenzelm@6360
     6
Datatype package for Isabelle/HOL.
berghofe@5177
     7
*)
berghofe@5177
     8
wenzelm@6360
     9
signature BASIC_DATATYPE_PACKAGE =
wenzelm@6360
    10
sig
wenzelm@6360
    11
  val mutual_induct_tac : string list -> int -> tactic
wenzelm@6360
    12
  val induct_tac : string -> int -> tactic
wenzelm@6360
    13
  val exhaust_tac : string -> int -> tactic
wenzelm@6360
    14
end;
wenzelm@6360
    15
berghofe@5177
    16
signature DATATYPE_PACKAGE =
berghofe@5177
    17
sig
wenzelm@6360
    18
  include BASIC_DATATYPE_PACKAGE
berghofe@5661
    19
  val quiet_mode : bool ref
berghofe@5661
    20
  val add_datatype : bool -> string list -> (string list * bstring * mixfix *
berghofe@5661
    21
    (bstring * string list * mixfix) list) list -> theory -> theory *
berghofe@5177
    22
      {distinct : thm list list,
berghofe@5177
    23
       inject : thm list list,
berghofe@5177
    24
       exhaustion : thm list,
berghofe@5177
    25
       rec_thms : thm list,
berghofe@5177
    26
       case_thms : thm list list,
berghofe@5177
    27
       split_thms : (thm * thm) list,
berghofe@5177
    28
       induction : thm,
berghofe@5177
    29
       size : thm list,
berghofe@5177
    30
       simps : thm list}
berghofe@5661
    31
  val add_datatype_i : bool -> string list -> (string list * bstring * mixfix *
berghofe@5661
    32
    (bstring * typ list * mixfix) list) list -> theory -> theory *
berghofe@5177
    33
      {distinct : thm list list,
berghofe@5177
    34
       inject : thm list list,
berghofe@5177
    35
       exhaustion : thm list,
berghofe@5177
    36
       rec_thms : thm list,
berghofe@5177
    37
       case_thms : thm list list,
berghofe@5177
    38
       split_thms : (thm * thm) list,
berghofe@5177
    39
       induction : thm,
berghofe@5177
    40
       size : thm list,
berghofe@5177
    41
       simps : thm list}
wenzelm@6385
    42
  val rep_datatype_i : string list option -> (thm * theory attribute list) list list ->
wenzelm@6385
    43
    (thm * theory attribute list) list list -> (thm * theory attribute list) -> theory -> theory *
wenzelm@6385
    44
      {distinct : thm list list,
wenzelm@6385
    45
       inject : thm list list,
wenzelm@6385
    46
       exhaustion : thm list,
wenzelm@6385
    47
       rec_thms : thm list,
wenzelm@6385
    48
       case_thms : thm list list,
wenzelm@6385
    49
       split_thms : (thm * thm) list,
wenzelm@6385
    50
       induction : thm,
wenzelm@6385
    51
       size : thm list,
wenzelm@6385
    52
       simps : thm list}
wenzelm@6385
    53
  val rep_datatype : string list option -> (xstring * Args.src list) list list ->
wenzelm@6385
    54
    (xstring * Args.src list) list list -> xstring * Args.src list -> theory -> theory *
berghofe@5177
    55
      {distinct : thm list list,
berghofe@5177
    56
       inject : thm list list,
berghofe@5177
    57
       exhaustion : thm list,
berghofe@5177
    58
       rec_thms : thm list,
berghofe@5177
    59
       case_thms : thm list list,
berghofe@5177
    60
       split_thms : (thm * thm) list,
berghofe@5177
    61
       induction : thm,
berghofe@5177
    62
       size : thm list,
berghofe@5177
    63
       simps : thm list}
berghofe@5177
    64
  val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
wenzelm@6441
    65
  val print_datatypes : theory -> unit
berghofe@5177
    66
  val datatype_info_sg : Sign.sg -> string -> DatatypeAux.datatype_info
berghofe@5177
    67
  val datatype_info : theory -> string -> DatatypeAux.datatype_info
berghofe@5177
    68
  val constrs_of : theory -> string -> term list option
berghofe@5177
    69
  val case_const_of : theory -> string -> term option
wenzelm@6360
    70
  val setup: (theory -> theory) list
berghofe@5177
    71
end;
berghofe@5177
    72
berghofe@5177
    73
structure DatatypePackage : DATATYPE_PACKAGE =
berghofe@5177
    74
struct
berghofe@5177
    75
berghofe@5177
    76
open DatatypeAux;
berghofe@5177
    77
berghofe@5661
    78
val quiet_mode = quiet_mode;
berghofe@5661
    79
wenzelm@6360
    80
berghofe@5177
    81
(* data kind 'HOL/datatypes' *)
berghofe@5177
    82
berghofe@5177
    83
structure DatatypesArgs =
berghofe@5177
    84
struct
berghofe@5177
    85
  val name = "HOL/datatypes";
berghofe@5177
    86
  type T = datatype_info Symtab.table;
berghofe@5177
    87
berghofe@5177
    88
  val empty = Symtab.empty;
wenzelm@6556
    89
  val copy = I;
berghofe@5177
    90
  val prep_ext = I;
berghofe@5177
    91
  val merge: T * T -> T = Symtab.merge (K true);
berghofe@5177
    92
berghofe@5177
    93
  fun print sg tab =
berghofe@5177
    94
    Pretty.writeln (Pretty.strs ("datatypes:" ::
berghofe@5177
    95
      map (Sign.cond_extern sg Sign.typeK o fst) (Symtab.dest tab)));
berghofe@5177
    96
end;
berghofe@5177
    97
berghofe@5177
    98
structure DatatypesData = TheoryDataFun(DatatypesArgs);
berghofe@5177
    99
val get_datatypes_sg = DatatypesData.get_sg;
berghofe@5177
   100
val get_datatypes = DatatypesData.get;
berghofe@5177
   101
val put_datatypes = DatatypesData.put;
wenzelm@6441
   102
val print_datatypes = DatatypesData.print;
berghofe@5177
   103
berghofe@5177
   104
berghofe@5177
   105
(** theory information about datatypes **)
berghofe@5177
   106
berghofe@5177
   107
fun datatype_info_sg sg name =
berghofe@5177
   108
  (case Symtab.lookup (get_datatypes_sg sg, name) of
berghofe@5177
   109
    Some info => info
berghofe@5177
   110
  | None => error ("Unknown datatype " ^ quote name));
berghofe@5177
   111
wenzelm@6394
   112
val datatype_info = datatype_info_sg o Theory.sign_of;
berghofe@5177
   113
berghofe@5177
   114
fun constrs_of thy tname =
berghofe@5177
   115
  let
berghofe@5177
   116
    val {index, descr, ...} = datatype_info thy tname;
berghofe@5177
   117
    val (_, _, constrs) = the (assoc (descr, index))
berghofe@5177
   118
  in
berghofe@5177
   119
    Some (map (fn (cname, _) =>
wenzelm@6394
   120
      Const (cname, the (Sign.const_type (Theory.sign_of thy) cname))) constrs)
berghofe@5177
   121
  end handle _ => None;
berghofe@5177
   122
berghofe@5177
   123
fun case_const_of thy tname =
berghofe@5177
   124
  let
berghofe@5177
   125
    val {case_name, ...} = datatype_info thy tname;
berghofe@5177
   126
  in
wenzelm@6394
   127
    Some (Const (case_name, the (Sign.const_type (Theory.sign_of thy) case_name)))
berghofe@5177
   128
  end handle _ => None;
berghofe@5177
   129
berghofe@5177
   130
fun find_tname var Bi =
berghofe@5177
   131
  let val frees = map dest_Free (term_frees Bi)
berghofe@5177
   132
      val params = Logic.strip_params Bi;
berghofe@5177
   133
  in case assoc (frees @ params, var) of
berghofe@5177
   134
       None => error ("No such variable in subgoal: " ^ quote var)
berghofe@5177
   135
     | Some(Type (tn, _)) => tn
berghofe@5177
   136
     | _ => error ("Cannot determine type of " ^ quote var)
berghofe@5177
   137
  end;
berghofe@5177
   138
berghofe@5177
   139
fun infer_tname state sign i aterm =
berghofe@5177
   140
  let
berghofe@5177
   141
    val (_, _, Bi, _) = dest_state (state, i)
berghofe@5177
   142
    val params = Logic.strip_params Bi;   (*params of subgoal i*)
berghofe@5177
   143
    val params = rev (rename_wrt_term Bi params);   (*as they are printed*)
berghofe@5177
   144
    val (types, sorts) = types_sorts state;
berghofe@5177
   145
    fun types' (a, ~1) = (case assoc (params, a) of None => types(a, ~1) | sm => sm)
berghofe@5177
   146
      | types' ixn = types ixn;
berghofe@5177
   147
    val (ct, _) = read_def_cterm (sign, types', sorts) [] false
berghofe@5177
   148
                                  (aterm, TVar (("", 0), []));
berghofe@5177
   149
  in case #T (rep_cterm ct) of
berghofe@5177
   150
       Type (tn, _) => tn
berghofe@5177
   151
     | _ => error ("Cannot determine type of " ^ quote aterm)
berghofe@5177
   152
  end;
berghofe@5177
   153
berghofe@5177
   154
(*Warn if the (induction) variable occurs Free among the premises, which
berghofe@5177
   155
  usually signals a mistake.  But calls the tactic either way!*)
berghofe@5177
   156
fun occs_in_prems tacf vars = 
berghofe@5177
   157
  SUBGOAL (fn (Bi, i) =>
berghofe@5177
   158
	   (if  exists (fn Free (a, _) => a mem vars)
berghofe@5177
   159
	              (foldr add_term_frees (#2 (strip_context Bi), []))
berghofe@5177
   160
	     then warning "Induction variable occurs also among premises!"
berghofe@5177
   161
	     else ();
berghofe@5177
   162
	    tacf i));
berghofe@5177
   163
berghofe@5177
   164
(* generic induction tactic for datatypes *)
berghofe@5177
   165
berghofe@5177
   166
fun mutual_induct_tac vars i state =
berghofe@5177
   167
  let
berghofe@5177
   168
    val (_, _, Bi, _) = dest_state (state, i);
berghofe@5177
   169
    val {sign, ...} = rep_thm state;
berghofe@5177
   170
    val tn = find_tname (hd vars) Bi;
berghofe@5177
   171
    val {induction, ...} = datatype_info_sg sign tn;
berghofe@5177
   172
    val ind_vnames = map (fn (_ $ Var (ixn, _)) =>
berghofe@5177
   173
      implode (tl (explode (Syntax.string_of_vname ixn))))
berghofe@5177
   174
        (dest_conj (HOLogic.dest_Trueprop (concl_of induction)));
berghofe@5177
   175
    val insts = (ind_vnames ~~ vars) handle _ =>
berghofe@5177
   176
      error ("Induction rule for type " ^ tn ^ " has different number of variables")
berghofe@5177
   177
  in
berghofe@5177
   178
    occs_in_prems (res_inst_tac insts induction) vars i state
berghofe@5177
   179
  end;
berghofe@5177
   180
berghofe@5177
   181
fun induct_tac var = mutual_induct_tac [var];
berghofe@5177
   182
berghofe@5177
   183
(* generic exhaustion tactic for datatypes *)
berghofe@5177
   184
berghofe@5177
   185
fun exhaust_tac aterm i state =
berghofe@5177
   186
  let
berghofe@5177
   187
    val {sign, ...} = rep_thm state;
berghofe@5177
   188
    val tn = infer_tname state sign i aterm;
berghofe@5177
   189
    val {exhaustion, ...} = datatype_info_sg sign tn;
berghofe@5177
   190
    val _ $ Var (ixn, _) $ _ = HOLogic.dest_Trueprop
berghofe@5177
   191
      (hd (Logic.strip_assums_hyp (hd (prems_of exhaustion))));
berghofe@5177
   192
    val exh_vname = implode (tl (explode (Syntax.string_of_vname ixn)))
berghofe@5177
   193
  in
berghofe@5177
   194
    res_inst_tac [(exh_vname, aterm)] exhaustion i state
berghofe@5177
   195
  end;
berghofe@5177
   196
berghofe@5177
   197
berghofe@5177
   198
(* prepare types *)
berghofe@5177
   199
berghofe@5177
   200
fun read_typ sign ((Ts, sorts), str) =
berghofe@5177
   201
  let
berghofe@5177
   202
    val T = Type.no_tvars (Sign.read_typ (sign, (curry assoc)
berghofe@5177
   203
      (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
berghofe@5177
   204
  in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
berghofe@5177
   205
berghofe@5177
   206
fun cert_typ sign ((Ts, sorts), raw_T) =
berghofe@5177
   207
  let
berghofe@5177
   208
    val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
berghofe@5177
   209
      TYPE (msg, _, _) => error msg;
berghofe@5177
   210
    val sorts' = add_typ_tfrees (T, sorts)
berghofe@5177
   211
  in (Ts @ [T],
berghofe@5177
   212
      case duplicates (map fst sorts') of
berghofe@5177
   213
         [] => sorts'
berghofe@5177
   214
       | dups => error ("Inconsistent sort constraints for " ^ commas dups))
berghofe@5177
   215
  end;
berghofe@5177
   216
berghofe@5177
   217
berghofe@5177
   218
(**** make datatype info ****)
berghofe@5177
   219
berghofe@5177
   220
fun make_dt_info descr induct reccomb_names rec_thms
berghofe@5177
   221
  ((((((((i, (_, (tname, _, _))), case_name), case_thms),
berghofe@5177
   222
    exhaustion_thm), distinct_thm), inject), nchotomy), case_cong) = (tname,
berghofe@5177
   223
      {index = i,
berghofe@5177
   224
       descr = descr,
berghofe@5177
   225
       rec_names = reccomb_names,
berghofe@5177
   226
       rec_rewrites = rec_thms,
berghofe@5177
   227
       case_name = case_name,
berghofe@5177
   228
       case_rewrites = case_thms,
berghofe@5177
   229
       induction = induct,
berghofe@5177
   230
       exhaustion = exhaustion_thm,
berghofe@5177
   231
       distinct = distinct_thm,
berghofe@5177
   232
       inject = inject,
berghofe@5177
   233
       nchotomy = nchotomy,
berghofe@5177
   234
       case_cong = case_cong});
berghofe@5177
   235
berghofe@5177
   236
fun store_clasimp thy (cla, simp) =
berghofe@5177
   237
  (claset_ref_of thy := cla; simpset_ref_of thy := simp);
berghofe@5177
   238
berghofe@5177
   239
infix 4 addDistinct;
berghofe@5177
   240
berghofe@5177
   241
fun clasimp addDistinct ([], _) = clasimp
berghofe@5177
   242
  | clasimp addDistinct (thms::thmss, (_, (_, _, constrs))::descr) =
berghofe@5177
   243
      if length constrs < DatatypeProp.dtK then
berghofe@5177
   244
        clasimp addIffs thms addDistinct (thmss, descr)
berghofe@5177
   245
      else
berghofe@5177
   246
        clasimp addsimps2 thms addDistinct (thmss, descr);
berghofe@5177
   247
berghofe@5177
   248
berghofe@5177
   249
(********************* axiomatic introduction of datatypes ********************)
berghofe@5177
   250
berghofe@5177
   251
fun add_and_get_axioms label tnames ts thy =
berghofe@5177
   252
  foldr (fn ((tname, t), (thy', axs)) =>
berghofe@5177
   253
    let
berghofe@5177
   254
      val thy'' = thy' |>
berghofe@5661
   255
        Theory.add_path tname |>
berghofe@5177
   256
        PureThy.add_axioms_i [((label, t), [])];
berghofe@5177
   257
      val ax = get_axiom thy'' label
berghofe@5661
   258
    in (Theory.parent_path thy'', ax::axs)
berghofe@5177
   259
    end) (tnames ~~ ts, (thy, []));
berghofe@5177
   260
berghofe@5177
   261
fun add_and_get_axiomss label tnames tss thy =
berghofe@5177
   262
  foldr (fn ((tname, ts), (thy', axss)) =>
berghofe@5177
   263
    let
berghofe@5177
   264
      val thy'' = thy' |>
berghofe@5661
   265
        Theory.add_path tname |>
berghofe@5177
   266
        PureThy.add_axiomss_i [((label, ts), [])];
berghofe@5177
   267
      val axs = PureThy.get_thms thy'' label
berghofe@5661
   268
    in (Theory.parent_path thy'', axs::axss)
berghofe@5177
   269
    end) (tnames ~~ tss, (thy, []));
berghofe@5177
   270
berghofe@5661
   271
fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
berghofe@5177
   272
  let
berghofe@5177
   273
    val descr' = flat descr;
berghofe@5177
   274
    val recTs = get_rec_types descr' sorts;
berghofe@5578
   275
    val used = foldr add_typ_tfree_names (recTs, []);
berghofe@5177
   276
    val newTs = take (length (hd descr), recTs);
berghofe@5177
   277
wenzelm@6360
   278
    val _ = message ("Adding axioms for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   279
berghofe@5177
   280
    (**** declare new types and constants ****)
berghofe@5177
   281
berghofe@5177
   282
    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
berghofe@5177
   283
berghofe@5177
   284
    val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
berghofe@5177
   285
      map (fn ((_, cargs), (cname, mx)) =>
berghofe@5177
   286
        (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
berghofe@5177
   287
          (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
berghofe@5177
   288
berghofe@5578
   289
    val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
berghofe@5578
   290
      replicate (length descr') HOLogic.termS);
berghofe@5177
   291
berghofe@5177
   292
    val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
berghofe@5177
   293
      map (fn (_, cargs) =>
berghofe@5177
   294
        let
berghofe@5177
   295
          val recs = filter is_rec_type cargs;
berghofe@5177
   296
          val argTs = (map (typ_of_dtyp descr' sorts) cargs) @
berghofe@5177
   297
            (map (fn r => nth_elem (dest_DtRec r, rec_result_Ts)) recs)
berghofe@5177
   298
        in argTs ---> nth_elem (i, rec_result_Ts)
berghofe@5177
   299
        end) constrs) descr');
berghofe@5177
   300
berghofe@5177
   301
    val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
berghofe@5177
   302
    val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
berghofe@5177
   303
      (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
berghofe@5177
   304
        (1 upto (length descr')));
berghofe@5177
   305
berghofe@5177
   306
    val big_size_name = space_implode "_" new_type_names ^ "_size";
berghofe@5177
   307
    val size_names = if length (flat (tl descr)) = 1 then [big_size_name] else
berghofe@5177
   308
      map (fn i => big_size_name ^ "_" ^ string_of_int i)
berghofe@5177
   309
        (1 upto length (flat (tl descr)));
berghofe@5177
   310
berghofe@5578
   311
    val freeT = TFree (variant used "'t", HOLogic.termS);
berghofe@5177
   312
    val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
berghofe@5177
   313
      map (fn (_, cargs) =>
berghofe@5177
   314
        let val Ts = map (typ_of_dtyp descr' sorts) cargs
berghofe@5177
   315
        in Ts ---> freeT end) constrs) (hd descr);
berghofe@5177
   316
berghofe@5177
   317
    val case_names = map (fn s => (s ^ "_case")) new_type_names;
berghofe@5177
   318
berghofe@6305
   319
    val thy2' = thy |>
berghofe@5177
   320
berghofe@5177
   321
      (** new types **)
berghofe@5177
   322
berghofe@5177
   323
      curry (foldr (fn (((name, mx), tvs), thy') => thy' |>
wenzelm@6385
   324
          TypedefPackage.add_typedecls [(name, tvs, mx)]))
wenzelm@6385
   325
        (types_syntax ~~ tyvars) |>
berghofe@5661
   326
      add_path flat_names (space_implode "_" new_type_names) |>
berghofe@5177
   327
berghofe@5177
   328
      (** primrec combinators **)
berghofe@5177
   329
berghofe@5177
   330
      Theory.add_consts_i (map (fn ((name, T), T') =>
berghofe@5177
   331
        (name, reccomb_fn_Ts @ [T] ---> T', NoSyn))
berghofe@5177
   332
          (reccomb_names ~~ recTs ~~ rec_result_Ts)) |>
berghofe@5177
   333
berghofe@5177
   334
      (** case combinators **)
berghofe@5177
   335
berghofe@5177
   336
      Theory.add_consts_i (map (fn ((name, T), Ts) =>
berghofe@5177
   337
        (name, Ts @ [T] ---> freeT, NoSyn))
berghofe@5177
   338
          (case_names ~~ newTs ~~ case_fn_Ts)) |>
berghofe@6305
   339
      Theory.add_trrules_i (DatatypeProp.make_case_trrules new_type_names descr);
berghofe@6305
   340
wenzelm@6394
   341
    val reccomb_names' = map (Sign.intern_const (Theory.sign_of thy2')) reccomb_names;
wenzelm@6394
   342
    val case_names' = map (Sign.intern_const (Theory.sign_of thy2')) case_names;
berghofe@6305
   343
berghofe@6305
   344
    val thy2 = thy2' |>
berghofe@5177
   345
berghofe@5177
   346
      (** t_ord functions **)
berghofe@5177
   347
berghofe@5177
   348
      Theory.add_consts_i
berghofe@5177
   349
        (foldr (fn ((((_, (_, _, constrs)), tname), T), decls) =>
berghofe@5177
   350
          if length constrs < DatatypeProp.dtK then decls
berghofe@5177
   351
          else (tname ^ "_ord", T --> HOLogic.natT, NoSyn)::decls)
berghofe@5177
   352
            ((hd descr) ~~ new_type_names ~~ newTs, [])) |>
berghofe@5177
   353
berghofe@5177
   354
      (** size functions **)
berghofe@5177
   355
berghofe@5177
   356
      Theory.add_consts_i (map (fn (s, T) =>
berghofe@5177
   357
        (Sign.base_name s, T --> HOLogic.natT, NoSyn))
berghofe@5661
   358
          (size_names ~~ drop (length (hd descr), recTs))) |>
berghofe@5661
   359
berghofe@5661
   360
      (** constructors **)
berghofe@5661
   361
berghofe@5661
   362
      parent_path flat_names |>
berghofe@5661
   363
      curry (foldr (fn (((((_, (_, _, constrs)), T), tname),
berghofe@5661
   364
        constr_syntax'), thy') => thy' |>
berghofe@5661
   365
          add_path flat_names tname |>
berghofe@5661
   366
            Theory.add_consts_i (map (fn ((_, cargs), (cname, mx)) =>
berghofe@5661
   367
              (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
berghofe@5661
   368
                (constrs ~~ constr_syntax')) |>
berghofe@5661
   369
          parent_path flat_names))
berghofe@5661
   370
            (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
berghofe@5177
   371
berghofe@5177
   372
    (**** introduction of axioms ****)
berghofe@5177
   373
berghofe@5661
   374
    val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
berghofe@5661
   375
    val size_axs = DatatypeProp.make_size new_type_names descr sorts thy2;
berghofe@5661
   376
berghofe@5177
   377
    val (thy3, inject) = thy2 |>
berghofe@5661
   378
      Theory.add_path (space_implode "_" new_type_names) |>
berghofe@5177
   379
      PureThy.add_axioms_i [(("induct", DatatypeProp.make_ind descr sorts), [])] |>
berghofe@5661
   380
      PureThy.add_axiomss_i [(("recs", rec_axs), [])] |>
berghofe@5661
   381
      PureThy.add_axiomss_i [(("size", size_axs), [])] |>
berghofe@5661
   382
      Theory.parent_path |>
berghofe@5177
   383
      add_and_get_axiomss "inject" new_type_names
berghofe@5177
   384
        (DatatypeProp.make_injs descr sorts);
berghofe@5661
   385
    val induct = get_axiom thy3 "induct";
berghofe@5661
   386
    val rec_thms = get_thms thy3 "recs";
berghofe@5661
   387
    val size_thms = get_thms thy3 "size";
berghofe@5177
   388
    val (thy4, distinct) = add_and_get_axiomss "distinct" new_type_names
berghofe@5177
   389
      (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
berghofe@5177
   390
    val (thy5, exhaustion) = add_and_get_axioms "exhaust" new_type_names
berghofe@5661
   391
      (DatatypeProp.make_casedists descr sorts) thy4;
berghofe@5177
   392
    val (thy6, case_thms) = add_and_get_axiomss "cases" new_type_names
berghofe@5177
   393
      (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
berghofe@5177
   394
    val (split_ts, split_asm_ts) = ListPair.unzip
berghofe@5177
   395
      (DatatypeProp.make_splits new_type_names descr sorts thy6);
berghofe@5177
   396
    val (thy7, split) = add_and_get_axioms "split" new_type_names split_ts thy6;
berghofe@5177
   397
    val (thy8, split_asm) = add_and_get_axioms "split_asm" new_type_names
berghofe@5177
   398
      split_asm_ts thy7;
berghofe@5177
   399
    val (thy9, nchotomys) = add_and_get_axioms "nchotomy" new_type_names
berghofe@5177
   400
      (DatatypeProp.make_nchotomys descr sorts) thy8;
berghofe@5177
   401
    val (thy10, case_congs) = add_and_get_axioms "case_cong" new_type_names
berghofe@5177
   402
      (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
berghofe@5177
   403
    
berghofe@6305
   404
    val dt_infos = map (make_dt_info descr' induct reccomb_names' rec_thms)
berghofe@6305
   405
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
berghofe@5177
   406
        exhaustion ~~ distinct ~~ inject ~~ nchotomys ~~ case_congs);
berghofe@5177
   407
berghofe@5177
   408
    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
berghofe@5177
   409
berghofe@5661
   410
    val thy11 = thy10 |>
berghofe@5661
   411
      Theory.add_path (space_implode "_" new_type_names) |>
wenzelm@6092
   412
      PureThy.add_thmss [(("simps", simps), [])] |>
berghofe@5177
   413
      put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
berghofe@5177
   414
      Theory.parent_path;
berghofe@5177
   415
berghofe@5661
   416
    val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
berghofe@5177
   417
      addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
berghofe@5177
   418
      addIffs flat inject addDistinct (distinct, hd descr));
berghofe@5177
   419
berghofe@5177
   420
  in
berghofe@5661
   421
    (thy11,
berghofe@5177
   422
     {distinct = distinct,
berghofe@5177
   423
      inject = inject,
berghofe@5177
   424
      exhaustion = exhaustion,
berghofe@5177
   425
      rec_thms = rec_thms,
berghofe@5177
   426
      case_thms = case_thms,
berghofe@5177
   427
      split_thms = split ~~ split_asm,
berghofe@5177
   428
      induction = induct,
berghofe@5177
   429
      size = size_thms,
berghofe@5177
   430
      simps = simps})
berghofe@5177
   431
  end;
berghofe@5177
   432
berghofe@5177
   433
berghofe@5177
   434
(******************* definitional introduction of datatypes *******************)
berghofe@5177
   435
berghofe@5661
   436
fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
berghofe@5177
   437
  let
wenzelm@6360
   438
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   439
berghofe@5177
   440
    val (thy2, inject, dist_rewrites, induct) = thy |>
berghofe@5661
   441
      DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
berghofe@5177
   442
        types_syntax constr_syntax;
berghofe@5177
   443
berghofe@5177
   444
    val (thy3, casedist_thms) =
berghofe@5177
   445
      DatatypeAbsProofs.prove_casedist_thms new_type_names descr sorts induct thy2;
berghofe@5177
   446
    val (thy4, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
berghofe@5661
   447
      flat_names new_type_names descr sorts dt_info inject dist_rewrites induct thy3;
berghofe@5177
   448
    val (thy5, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms
berghofe@5661
   449
      flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
berghofe@5177
   450
    val (thy6, distinct) = DatatypeAbsProofs.prove_distinctness_thms
berghofe@5661
   451
      flat_names new_type_names descr sorts dist_rewrites case_thms thy5;
berghofe@5177
   452
    val (thy7, split_thms) = DatatypeAbsProofs.prove_split_thms new_type_names
berghofe@5177
   453
      descr sorts inject dist_rewrites casedist_thms case_thms thy6;
berghofe@5177
   454
    val (thy8, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   455
      descr sorts casedist_thms thy7;
berghofe@5177
   456
    val (thy9, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   457
      descr sorts nchotomys case_thms thy8;
berghofe@5661
   458
    val (thy10, size_thms) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
berghofe@5177
   459
      descr sorts reccomb_names rec_thms thy9;
berghofe@5177
   460
berghofe@5177
   461
    val dt_infos = map (make_dt_info (flat descr) induct reccomb_names rec_thms)
berghofe@5177
   462
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
berghofe@5177
   463
        casedist_thms ~~ distinct ~~ inject ~~ nchotomys ~~ case_congs);
berghofe@5177
   464
berghofe@5177
   465
    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
berghofe@5177
   466
berghofe@5177
   467
    val thy11 = thy10 |>
berghofe@5661
   468
      Theory.add_path (space_implode "_" new_type_names) |>
wenzelm@6092
   469
      PureThy.add_thmss [(("simps", simps), [])] |>
berghofe@5177
   470
      put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
berghofe@5663
   471
      Theory.parent_path;
berghofe@5177
   472
berghofe@5177
   473
    val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
berghofe@5177
   474
      addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
berghofe@5177
   475
      addIffs flat inject addDistinct (distinct, hd descr));
berghofe@5177
   476
berghofe@5177
   477
  in
berghofe@5177
   478
    (thy11,
berghofe@5177
   479
     {distinct = distinct,
berghofe@5177
   480
      inject = inject,
berghofe@5177
   481
      exhaustion = casedist_thms,
berghofe@5177
   482
      rec_thms = rec_thms,
berghofe@5177
   483
      case_thms = case_thms,
berghofe@5177
   484
      split_thms = split_thms,
berghofe@5177
   485
      induction = induct,
berghofe@5177
   486
      size = size_thms,
berghofe@5177
   487
      simps = simps})
berghofe@5177
   488
  end;
berghofe@5177
   489
berghofe@5177
   490
wenzelm@6385
   491
(*********************** declare existing type as datatype *********************)
berghofe@5177
   492
wenzelm@6385
   493
fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
berghofe@5177
   494
  let
wenzelm@6385
   495
    fun app_thmss srcs thy = foldl_map (fn (thy, x) => apply_theorems x thy) (thy, srcs);
wenzelm@6385
   496
    fun app_thm src thy = apsnd Library.hd (apply_theorems [src] thy);
wenzelm@6385
   497
wenzelm@6385
   498
    val (((thy1, induction), inject), distinct) = thy0
wenzelm@6385
   499
      |> app_thmss raw_distinct
wenzelm@6385
   500
      |> apfst (app_thmss raw_inject)
wenzelm@6385
   501
      |> apfst (apfst (app_thm raw_induction));
wenzelm@6394
   502
    val sign = Theory.sign_of thy1;
berghofe@5177
   503
berghofe@5177
   504
    val induction' = freezeT induction;
berghofe@5177
   505
berghofe@5177
   506
    fun err t = error ("Ill-formed predicate in induction rule: " ^
berghofe@5177
   507
      Sign.string_of_term sign t);
berghofe@5177
   508
berghofe@5177
   509
    fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
berghofe@5177
   510
          ((tname, map dest_TFree Ts) handle _ => err t)
berghofe@5177
   511
      | get_typ t = err t;
berghofe@5177
   512
berghofe@5177
   513
    val dtnames = map get_typ (dest_conj (HOLogic.dest_Trueprop (concl_of induction')));
berghofe@5177
   514
    val new_type_names = if_none alt_names (map fst dtnames);
berghofe@5177
   515
berghofe@5177
   516
    fun get_constr t = (case Logic.strip_assums_concl t of
berghofe@5177
   517
        _ $ (_ $ t') => (case head_of t' of
berghofe@5177
   518
            Const (cname, cT) => (case strip_type cT of
berghofe@5177
   519
                (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
berghofe@5177
   520
              | _ => err t)
berghofe@5177
   521
          | _ => err t)
berghofe@5177
   522
      | _ => err t);
berghofe@5177
   523
berghofe@5177
   524
    fun make_dt_spec [] _ _ = []
berghofe@5177
   525
      | make_dt_spec ((tname, tvs)::dtnames') i constrs =
berghofe@5177
   526
          let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
berghofe@5177
   527
          in (i, (tname, map DtTFree tvs, map snd constrs'))::
berghofe@5177
   528
            (make_dt_spec dtnames' (i + 1) constrs'')
berghofe@5177
   529
          end;
berghofe@5177
   530
berghofe@5177
   531
    val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
berghofe@5177
   532
    val sorts = add_term_tfrees (concl_of induction', []);
wenzelm@6385
   533
    val dt_info = get_datatypes thy1;
berghofe@5177
   534
wenzelm@6427
   535
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   536
wenzelm@6385
   537
    val (thy2, casedist_thms) = thy1 |>
berghofe@5177
   538
      DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction;
berghofe@5177
   539
    val (thy3, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
berghofe@5661
   540
      false new_type_names [descr] sorts dt_info inject distinct induction thy2;
berghofe@5661
   541
    val (thy4, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms false
berghofe@5177
   542
      new_type_names [descr] sorts reccomb_names rec_thms thy3;
berghofe@5177
   543
    val (thy5, split_thms) = DatatypeAbsProofs.prove_split_thms
berghofe@5177
   544
      new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
berghofe@5177
   545
    val (thy6, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   546
      [descr] sorts casedist_thms thy5;
berghofe@5177
   547
    val (thy7, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   548
      [descr] sorts nchotomys case_thms thy6;
berghofe@5177
   549
    val (thy8, size_thms) =
wenzelm@6394
   550
      if exists (equal "Arith") (Sign.stamp_names_of (Theory.sign_of thy7)) then
berghofe@5661
   551
        DatatypeAbsProofs.prove_size_thms false new_type_names
berghofe@5177
   552
          [descr] sorts reccomb_names rec_thms thy7
berghofe@5177
   553
      else (thy7, []);
berghofe@5177
   554
berghofe@5177
   555
    val dt_infos = map (make_dt_info descr induction reccomb_names rec_thms)
berghofe@5177
   556
      ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~
berghofe@5177
   557
        casedist_thms ~~ distinct ~~ inject ~~ nchotomys ~~ case_congs);
berghofe@5177
   558
berghofe@5177
   559
    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
berghofe@5177
   560
berghofe@5177
   561
    val thy9 = thy8 |>
berghofe@5661
   562
      Theory.add_path (space_implode "_" new_type_names) |>
wenzelm@6092
   563
      PureThy.add_thmss [(("simps", simps), [])] |>
berghofe@5177
   564
      put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
berghofe@5177
   565
      Theory.parent_path;
berghofe@5177
   566
berghofe@5177
   567
    val _ = store_clasimp thy9 ((claset_of thy9, simpset_of thy9)
berghofe@5177
   568
      addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
berghofe@5177
   569
      addIffs flat inject addDistinct (distinct, descr));
berghofe@5177
   570
berghofe@5177
   571
  in
berghofe@5177
   572
    (thy9,
berghofe@5177
   573
     {distinct = distinct,
berghofe@5177
   574
      inject = inject,
berghofe@5177
   575
      exhaustion = casedist_thms,
berghofe@5177
   576
      rec_thms = rec_thms,
berghofe@5177
   577
      case_thms = case_thms,
berghofe@5177
   578
      split_thms = split_thms,
berghofe@5177
   579
      induction = induction,
berghofe@5177
   580
      size = size_thms,
berghofe@5177
   581
      simps = simps})
berghofe@5177
   582
  end;
berghofe@5177
   583
wenzelm@6385
   584
val rep_datatype = gen_rep_datatype IsarThy.apply_theorems;
wenzelm@6385
   585
val rep_datatype_i = gen_rep_datatype IsarThy.apply_theorems_i;
wenzelm@6385
   586
berghofe@5177
   587
berghofe@5177
   588
(******************************** add datatype ********************************)
berghofe@5177
   589
berghofe@5661
   590
fun gen_add_datatype prep_typ flat_names new_type_names dts thy =
berghofe@5177
   591
  let
berghofe@5177
   592
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   593
berghofe@5177
   594
    (* this theory is used just for parsing *)
berghofe@5177
   595
berghofe@5177
   596
    val tmp_thy = thy |>
wenzelm@5892
   597
      Theory.copy |>
berghofe@5177
   598
      Theory.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   599
        (tname, length tvs, mx)) dts);
berghofe@5177
   600
wenzelm@6394
   601
    val sign = Theory.sign_of tmp_thy;
berghofe@5177
   602
berghofe@5661
   603
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   604
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   605
      let val full_tname = Sign.full_name sign (Syntax.type_name tname mx)
berghofe@5177
   606
      in (case duplicates tvs of
berghofe@5661
   607
            [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
berghofe@5661
   608
                  else error ("Mutually recursive datatypes must have same type parameters")
berghofe@5177
   609
          | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
berghofe@5177
   610
              " : " ^ commas dups))
berghofe@5177
   611
      end) dts);
berghofe@5177
   612
berghofe@5177
   613
    val _ = (case duplicates (map fst new_dts) @ duplicates new_type_names of
berghofe@5177
   614
      [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   615
berghofe@5177
   616
    fun prep_dt_spec ((dts', constr_syntax, sorts, i), (tvs, tname, mx, constrs)) =
berghofe@5177
   617
      let
berghofe@5661
   618
        fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
berghofe@5279
   619
          let
berghofe@5279
   620
            val (cargs', sorts'') = foldl (prep_typ sign) (([], sorts'), cargs);
berghofe@5279
   621
            val _ = (case foldr add_typ_tfree_names (cargs', []) \\ tvs of
berghofe@5279
   622
                [] => ()
berghofe@5279
   623
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
berghofe@5661
   624
          in (constrs @ [((if flat_names then Sign.full_name sign else
berghofe@5661
   625
                Sign.full_name_path sign tname) (Syntax.const_name cname mx'),
berghofe@5177
   626
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   627
              constr_syntax' @ [(cname, mx')], sorts'')
berghofe@5177
   628
          end handle ERROR =>
berghofe@5177
   629
            error ("The error above occured in constructor " ^ cname ^
berghofe@5177
   630
              " of datatype " ^ tname);
berghofe@5177
   631
berghofe@5177
   632
        val (constrs', constr_syntax', sorts') =
berghofe@5177
   633
          foldl prep_constr (([], [], sorts), constrs)
berghofe@5177
   634
berghofe@5177
   635
      in 
berghofe@5177
   636
        case duplicates (map fst constrs') of
berghofe@5177
   637
           [] =>
berghofe@5177
   638
             (dts' @ [(i, (Sign.full_name sign (Syntax.type_name tname mx),
berghofe@5177
   639
                map DtTFree tvs, constrs'))],
berghofe@5177
   640
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   641
         | dups => error ("Duplicate constructors " ^ commas dups ^
berghofe@5177
   642
             " in datatype " ^ tname)
berghofe@5177
   643
      end;
berghofe@5177
   644
berghofe@5661
   645
    val (dts', constr_syntax, sorts', i) = foldl prep_dt_spec (([], [], [], 0), dts);
berghofe@5177
   646
    val dt_info = get_datatypes thy;
berghofe@5177
   647
    val (descr, _) = unfold_datatypes dt_info dts' i;
berghofe@5177
   648
    val _ = check_nonempty descr;
berghofe@5661
   649
    val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
berghofe@5177
   650
berghofe@5177
   651
  in
berghofe@5177
   652
    (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
berghofe@5661
   653
      flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy
berghofe@5177
   654
  end;
berghofe@5177
   655
berghofe@5177
   656
val add_datatype_i = gen_add_datatype cert_typ;
berghofe@5177
   657
val add_datatype = gen_add_datatype read_typ;
berghofe@5177
   658
wenzelm@6360
   659
wenzelm@6360
   660
(** package setup **)
wenzelm@6360
   661
wenzelm@6360
   662
(* setup theory *)
wenzelm@6360
   663
wenzelm@6360
   664
val setup = [DatatypesData.init];
wenzelm@6360
   665
wenzelm@6360
   666
wenzelm@6360
   667
(* outer syntax *)
wenzelm@6360
   668
wenzelm@6723
   669
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@6360
   670
wenzelm@6360
   671
val datatype_decl =
wenzelm@6723
   672
  Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
wenzelm@6723
   673
    (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
wenzelm@6360
   674
wenzelm@6360
   675
fun mk_datatype args =
wenzelm@6360
   676
  let
wenzelm@6360
   677
    val names = map (fn ((((None, _), t), _), _) => t | ((((Some t, _), _), _), _) => t) args;
wenzelm@6360
   678
    val specs = map (fn ((((_, vs), t), mx), cons) => (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
wenzelm@6360
   679
  in #1 o add_datatype false names specs end;
wenzelm@6360
   680
wenzelm@6360
   681
val datatypeP =
wenzelm@6723
   682
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
wenzelm@6723
   683
    (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
wenzelm@6360
   684
wenzelm@6385
   685
wenzelm@6385
   686
val rep_datatype_decl =
wenzelm@6723
   687
  Scan.option (Scan.repeat1 P.name) --
wenzelm@6723
   688
    Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 P.xthms1)) [] --
wenzelm@6723
   689
    Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 P.xthms1)) [] --
wenzelm@6723
   690
    (P.$$$ "induction" |-- P.!!! P.xthm);
wenzelm@6385
   691
wenzelm@6385
   692
fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #1 o rep_datatype opt_ts dss iss ind;
wenzelm@6385
   693
wenzelm@6385
   694
val rep_datatypeP =
wenzelm@6723
   695
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
wenzelm@6385
   696
    (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
wenzelm@6385
   697
wenzelm@6385
   698
wenzelm@6479
   699
val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
wenzelm@6385
   700
val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
wenzelm@6385
   701
wenzelm@6385
   702
end;
wenzelm@6385
   703
wenzelm@6360
   704
berghofe@5177
   705
end;
berghofe@5177
   706
wenzelm@6360
   707
structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
wenzelm@6360
   708
open BasicDatatypePackage;