src/HOL/Tools/datatype_package.ML
author wenzelm
Tue May 02 20:42:35 2006 +0200 (2006-05-02)
changeset 19539 5b37bb0ad964
parent 19346 c4c003abd830
child 19599 a5c7eb37d14f
permissions -rw-r--r--
ThyInfo.the_theory;
tuned;
     1 (*  Title:      HOL/Tools/datatype_package.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 Datatype package for Isabelle/HOL.
     6 *)
     7 
     8 signature BASIC_DATATYPE_PACKAGE =
     9 sig
    10   val induct_tac : string -> int -> tactic
    11   val induct_thm_tac : thm -> string -> int -> tactic
    12   val case_tac : string -> int -> tactic
    13   val distinct_simproc : simproc
    14 end;
    15 
    16 signature DATATYPE_PACKAGE =
    17 sig
    18   include BASIC_DATATYPE_PACKAGE
    19   val quiet_mode : bool ref
    20   val add_datatype : bool -> string list -> (string list * bstring * mixfix *
    21     (bstring * string list * mixfix) list) list -> theory ->
    22       {distinct : thm list list,
    23        inject : thm list list,
    24        exhaustion : thm list,
    25        rec_thms : thm list,
    26        case_thms : thm list list,
    27        split_thms : (thm * thm) list,
    28        induction : thm,
    29        size : thm list,
    30        simps : thm list} * theory
    31   val add_datatype_i : bool -> bool -> string list -> (string list * bstring * mixfix *
    32     (bstring * typ list * mixfix) list) list -> theory ->
    33       {distinct : thm list list,
    34        inject : thm list list,
    35        exhaustion : thm list,
    36        rec_thms : thm list,
    37        case_thms : thm list list,
    38        split_thms : (thm * thm) list,
    39        induction : thm,
    40        size : thm list,
    41        simps : thm list} * theory
    42   val rep_datatype_i : string list option -> (thm list * attribute list) list list ->
    43     (thm list * attribute list) list list -> (thm list * attribute list) ->
    44     theory ->
    45       {distinct : thm list list,
    46        inject : thm list list,
    47        exhaustion : thm list,
    48        rec_thms : thm list,
    49        case_thms : thm list list,
    50        split_thms : (thm * thm) list,
    51        induction : thm,
    52        size : thm list,
    53        simps : thm list} * theory
    54   val rep_datatype : string list option -> (thmref * Attrib.src list) list list ->
    55     (thmref * Attrib.src list) list list -> thmref * Attrib.src list -> theory ->
    56       {distinct : thm list list,
    57        inject : thm list list,
    58        exhaustion : thm list,
    59        rec_thms : thm list,
    60        case_thms : thm list list,
    61        split_thms : (thm * thm) list,
    62        induction : thm,
    63        size : thm list,
    64        simps : thm list} * theory
    65   val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
    66   val get_datatype : theory -> string -> DatatypeAux.datatype_info option
    67   val the_datatype : theory -> string -> DatatypeAux.datatype_info
    68   val get_datatype_spec : theory -> string -> ((string * sort) list * (string * typ list) list) option
    69   val get_datatype_constrs : theory -> string -> (string * typ) list option
    70   val print_datatypes : theory -> unit
    71   val setup: theory -> theory
    72 end;
    73 
    74 structure DatatypePackage : DATATYPE_PACKAGE =
    75 struct
    76 
    77 open DatatypeAux;
    78 
    79 val quiet_mode = quiet_mode;
    80 
    81 
    82 (* data kind 'HOL/datatypes' *)
    83 
    84 structure DatatypesData = TheoryDataFun
    85 (struct
    86   val name = "HOL/datatypes";
    87   type T = datatype_info Symtab.table;
    88 
    89   val empty = Symtab.empty;
    90   val copy = I;
    91   val extend = I;
    92   fun merge _ tabs : T = Symtab.merge (K true) tabs;
    93 
    94   fun print sg tab =
    95     Pretty.writeln (Pretty.strs ("datatypes:" ::
    96       map #1 (NameSpace.extern_table (Sign.type_space sg, tab))));
    97 end);
    98 
    99 val get_datatypes = DatatypesData.get;
   100 val put_datatypes = DatatypesData.put;
   101 val print_datatypes = DatatypesData.print;
   102 
   103 
   104 (** theory information about datatypes **)
   105 
   106 val get_datatype = Symtab.lookup o get_datatypes;
   107 
   108 fun the_datatype thy name = (case get_datatype thy name of
   109       SOME info => info
   110     | NONE => error ("Unknown datatype " ^ quote name));
   111 
   112 fun get_datatype_descr thy dtco =
   113   get_datatype thy dtco
   114   |> Option.map (fn info as { descr, index, ... } => 
   115        (info, (((fn SOME (_, dtys, cos) => (dtys, cos)) o AList.lookup (op =) descr) index)));
   116 
   117 fun get_datatype_spec thy dtco =
   118   let
   119     fun mk_cons typ_of_dtyp (co, tys) =
   120       (co, map typ_of_dtyp tys);
   121     fun mk_dtyp ({ sorts = raw_sorts, descr, ... } : DatatypeAux.datatype_info, (dtys, cos)) =
   122       let
   123         val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
   124           o DatatypeAux.dest_DtTFree) dtys;
   125         val typ_of_dtyp = DatatypeAux.typ_of_dtyp descr sorts;
   126         val tys = map typ_of_dtyp dtys;
   127       in (sorts, map (mk_cons typ_of_dtyp) cos) end;
   128   in Option.map mk_dtyp (get_datatype_descr thy dtco) end;
   129 
   130 fun get_datatype_constrs thy dtco =
   131   case get_datatype_spec thy dtco
   132    of SOME (sorts, cos) =>
   133         let
   134           fun subst (v, sort) = TVar ((v, 0), sort);
   135           fun subst_ty (TFree v) = subst v
   136             | subst_ty ty = ty;
   137           val dty = Type (dtco, map subst sorts);
   138           fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
   139         in SOME (map mk_co cos) end
   140     | NONE => NONE;
   141 
   142 fun get_case_const_data thy c =
   143   case find_first (fn (_, {index, descr, case_name, ...}) =>
   144       case_name = c
   145     ) ((Symtab.dest o get_datatypes) thy)
   146    of NONE => NONE
   147     | SOME (_, {index, descr, ...}) =>
   148         (SOME o map (apsnd length) o #3 o the o AList.lookup (op =) descr) index;
   149 
   150 fun find_tname var Bi =
   151   let val frees = map dest_Free (term_frees Bi)
   152       val params = rename_wrt_term Bi (Logic.strip_params Bi);
   153   in case AList.lookup (op =) (frees @ params) var of
   154        NONE => error ("No such variable in subgoal: " ^ quote var)
   155      | SOME(Type (tn, _)) => tn
   156      | _ => error ("Cannot determine type of " ^ quote var)
   157   end;
   158 
   159 fun infer_tname state i aterm =
   160   let
   161     val sign = Thm.sign_of_thm state;
   162     val (_, _, Bi, _) = Thm.dest_state (state, i)
   163     val params = Logic.strip_params Bi;   (*params of subgoal i*)
   164     val params = rev (rename_wrt_term Bi params);   (*as they are printed*)
   165     val (types, sorts) = types_sorts state;
   166     fun types' (a, ~1) = (case AList.lookup (op =) params a of NONE => types(a, ~1) | sm => sm)
   167       | types' ixn = types ixn;
   168     val (ct, _) = read_def_cterm (sign, types', sorts) [] false (aterm, TypeInfer.logicT);
   169   in case #T (rep_cterm ct) of
   170        Type (tn, _) => tn
   171      | _ => error ("Cannot determine type of " ^ quote aterm)
   172   end;
   173 
   174 (*Warn if the (induction) variable occurs Free among the premises, which
   175   usually signals a mistake.  But calls the tactic either way!*)
   176 fun occs_in_prems tacf vars =
   177   SUBGOAL (fn (Bi, i) =>
   178            (if  exists (fn Free (a, _) => a mem vars)
   179                       (foldr add_term_frees [] (#2 (strip_context Bi)))
   180              then warning "Induction variable occurs also among premises!"
   181              else ();
   182             tacf i));
   183 
   184 
   185 (* generic induction tactic for datatypes *)
   186 
   187 local
   188 
   189 fun prep_var (Var (ixn, _), SOME x) = SOME (ixn, x)
   190   | prep_var _ = NONE;
   191 
   192 fun prep_inst (concl, xs) =	(*exception UnequalLengths *)
   193   let val vs = InductAttrib.vars_of concl
   194   in List.mapPartial prep_var (Library.drop (length vs - length xs, vs) ~~ xs) end;
   195 
   196 in
   197 
   198 fun gen_induct_tac inst_tac (varss, opt_rule) i state = 
   199   SUBGOAL (fn (Bi,_) =>
   200   let
   201     val (rule, rule_name) =
   202       case opt_rule of
   203 	  SOME r => (r, "Induction rule")
   204 	| NONE =>
   205 	    let val tn = find_tname (hd (List.mapPartial I (List.concat varss))) Bi
   206                 val {sign, ...} = Thm.rep_thm state
   207 	    in (#induction (the_datatype sign tn), "Induction rule for type " ^ tn) 
   208 	    end
   209     val concls = HOLogic.dest_concls (Thm.concl_of rule);
   210     val insts = List.concat (map prep_inst (concls ~~ varss)) handle UnequalLengths =>
   211       error (rule_name ^ " has different numbers of variables");
   212   in occs_in_prems (inst_tac insts rule) (map #2 insts) i end)
   213   i state;
   214 
   215 fun induct_tac s =
   216   gen_induct_tac Tactic.res_inst_tac'
   217     (map (Library.single o SOME) (Syntax.read_idents s), NONE);
   218 
   219 fun induct_thm_tac th s =
   220   gen_induct_tac Tactic.res_inst_tac'
   221     ([map SOME (Syntax.read_idents s)], SOME th);
   222 
   223 end;
   224 
   225 
   226 (* generic case tactic for datatypes *)
   227 
   228 fun case_inst_tac inst_tac t rule i state =
   229   let
   230     val _ $ Var (ixn, _) $ _ = HOLogic.dest_Trueprop
   231       (hd (Logic.strip_assums_hyp (hd (Thm.prems_of rule))));
   232   in inst_tac [(ixn, t)] rule i state end;
   233 
   234 fun gen_case_tac inst_tac (t, SOME rule) i state =
   235       case_inst_tac inst_tac t rule i state
   236   | gen_case_tac inst_tac (t, NONE) i state =
   237       let val tn = infer_tname state i t in
   238         if tn = HOLogic.boolN then inst_tac [(("P", 0), t)] case_split_thm i state
   239         else case_inst_tac inst_tac t
   240                (#exhaustion (the_datatype (Thm.sign_of_thm state) tn))
   241                i state
   242       end handle THM _ => Seq.empty;
   243 
   244 fun case_tac t = gen_case_tac Tactic.res_inst_tac' (t, NONE);
   245 
   246 
   247 
   248 (** Isar tactic emulations **)
   249 
   250 local
   251 
   252 val rule_spec = Scan.lift (Args.$$$ "rule" -- Args.$$$ ":");
   253 val opt_rule = Scan.option (rule_spec |-- Attrib.thm);
   254 
   255 val varss =
   256   Args.and_list (Scan.repeat (Scan.unless rule_spec (Scan.lift (Args.maybe Args.name))));
   257 
   258 val inst_tac = Method.bires_inst_tac false;
   259 
   260 fun induct_meth ctxt (varss, opt_rule) =
   261   gen_induct_tac (inst_tac ctxt) (varss, opt_rule);
   262 fun case_meth ctxt (varss, opt_rule) =
   263   gen_case_tac (inst_tac ctxt) (varss, opt_rule);
   264 
   265 in
   266 
   267 val tactic_emulations =
   268  [("induct_tac", Method.goal_args_ctxt' (varss -- opt_rule) induct_meth,
   269     "induct_tac emulation (dynamic instantiation)"),
   270   ("case_tac", Method.goal_args_ctxt' (Scan.lift Args.name -- opt_rule) case_meth,
   271     "case_tac emulation (dynamic instantiation)")];
   272 
   273 end;
   274 
   275 
   276 
   277 (** induct method setup **)
   278 
   279 (* case names *)
   280 
   281 local
   282 
   283 fun dt_recs (DtTFree _) = []
   284   | dt_recs (DtType (_, dts)) = List.concat (map dt_recs dts)
   285   | dt_recs (DtRec i) = [i];
   286 
   287 fun dt_cases (descr: descr) (_, args, constrs) =
   288   let
   289     fun the_bname i = Sign.base_name (#1 (valOf (AList.lookup (op =) descr i)));
   290     val bnames = map the_bname (distinct (op =) (List.concat (map dt_recs args)));
   291   in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
   292 
   293 
   294 fun induct_cases descr =
   295   DatatypeProp.indexify_names (List.concat (map (dt_cases descr) (map #2 descr)));
   296 
   297 fun exhaust_cases descr i = dt_cases descr (valOf (AList.lookup (op =) descr i));
   298 
   299 in
   300 
   301 fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
   302 
   303 fun mk_case_names_exhausts descr new =
   304   map (RuleCases.case_names o exhaust_cases descr o #1)
   305     (List.filter (fn ((_, (name, _, _))) => name mem_string new) descr);
   306 
   307 end;
   308 
   309 (*Name management for ATP linkup. The suffix here must agree with the one given
   310   for notE in Clasimp.addIff*)
   311 fun name_notE th =
   312     Thm.name_thm (Thm.name_of_thm th ^ "_iff1", th RS notE);
   313       
   314 fun add_rules simps case_thms size_thms rec_thms inject distinct
   315                   weak_case_congs cong_att =
   316   (snd o PureThy.add_thmss [(("simps", simps), []),
   317     (("", List.concat case_thms @ size_thms @ 
   318           List.concat distinct  @ rec_thms), [Simplifier.simp_add]),
   319     (("", size_thms @ rec_thms),             [RecfunCodegen.add NONE]),
   320     (("", List.concat inject),               [iff_add]),
   321     (("", map name_notE (List.concat distinct)),  [Classical.safe_elim NONE]),
   322     (("", weak_case_congs),                  [cong_att])]);
   323 
   324 
   325 (* add_cases_induct *)
   326 
   327 fun add_cases_induct infos induction =
   328   let
   329     val n = length (HOLogic.dest_concls (Thm.concl_of induction));
   330     fun proj i = ProjectRule.project induction (i + 1);
   331 
   332     fun named_rules (name, {index, exhaustion, ...}: datatype_info) =
   333       [(("", proj index), [InductAttrib.induct_type name]),
   334        (("", exhaustion), [InductAttrib.cases_type name])];
   335     fun unnamed_rule i =
   336       (("", proj i), [PureThy.kind_internal, InductAttrib.induct_type ""]);
   337   in
   338     PureThy.add_thms
   339       (List.concat (map named_rules infos) @
   340         map unnamed_rule (length infos upto n - 1)) #> snd #>
   341     PureThy.add_thmss [(("inducts",
   342       map (proj #> standard #> RuleCases.save induction) (0 upto n - 1)), [])] #> snd
   343   end;
   344 
   345 
   346 
   347 (**** simplification procedure for showing distinctness of constructors ****)
   348 
   349 fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
   350   | stripT p = p;
   351 
   352 fun stripC (i, f $ x) = stripC (i + 1, f)
   353   | stripC p = p;
   354 
   355 val distinctN = "constr_distinct";
   356 
   357 exception ConstrDistinct of term;
   358 
   359 fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
   360   (case (stripC (0, t1), stripC (0, t2)) of
   361      ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
   362          (case (stripT (0, T1), stripT (0, T2)) of
   363             ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
   364                 if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
   365                    (case (get_datatype_descr thy) tname1 of
   366                       SOME (_, (_, constrs)) => let val cnames = map fst constrs
   367                         in if cname1 mem cnames andalso cname2 mem cnames then
   368                              let val eq_t = Logic.mk_equals (t, Const ("False", HOLogic.boolT));
   369                                  val eq_ct = cterm_of thy eq_t;
   370                                  val Datatype_thy = ThyInfo.the_theory "Datatype" thy;
   371                                  val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
   372                                    map (get_thm Datatype_thy o Name)
   373                                      ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"]
   374                              in (case (#distinct (the_datatype thy tname1)) of
   375                                  QuickAndDirty => SOME (Thm.invoke_oracle
   376                                    Datatype_thy distinctN (thy, ConstrDistinct eq_t))
   377                                | FewConstrs thms => SOME (Goal.prove thy [] [] eq_t (K
   378                                    (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
   379                                     atac 2, resolve_tac thms 1, etac FalseE 1])))
   380                                | ManyConstrs (thm, simpset) => SOME (Goal.prove thy [] [] eq_t (K
   381                                    (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
   382                                     full_simp_tac (Simplifier.inherit_context ss simpset) 1,
   383                                     REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   384                                     eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
   385                                     etac FalseE 1]))))
   386                              end
   387                            else NONE
   388                         end
   389                     | NONE => NONE)
   390                 else NONE
   391           | _ => NONE)
   392    | _ => NONE)
   393   | distinct_proc thy _ _ = NONE;
   394 
   395 val distinct_simproc =
   396   Simplifier.simproc HOL.thy distinctN ["s = t"] distinct_proc;
   397 
   398 val dist_ss = HOL_ss addsimprocs [distinct_simproc];
   399 
   400 val simproc_setup =
   401   Theory.add_oracle (distinctN, fn (_, ConstrDistinct t) => t) #>
   402   (fn thy => ((change_simpset_of thy) (fn ss => ss addsimprocs [distinct_simproc]); thy));
   403 
   404 
   405 (**** translation rules for case ****)
   406 
   407 fun find_first f = Library.find_first f;
   408 
   409 fun case_tr context [t, u] =
   410     let
   411       val thy = Context.theory_of context;
   412       fun case_error s name ts = raise TERM ("Error in case expression" ^
   413         getOpt (Option.map (curry op ^ " for datatype ") name, "") ^ ":\n" ^ s, ts);
   414       fun dest_case1 (Const ("_case1", _) $ t $ u) = (case strip_comb t of
   415             (Const (s, _), ts) => (Sign.intern_const thy s, ts)
   416           | (Free (s, _), ts) => (Sign.intern_const thy s, ts)
   417           | _ => case_error "Head is not a constructor" NONE [t, u], u)
   418         | dest_case1 t = raise TERM ("dest_case1", [t]);
   419       fun dest_case2 (Const ("_case2", _) $ t $ u) = t :: dest_case2 u
   420         | dest_case2 t = [t];
   421       val cases as ((cname, _), _) :: _ = map dest_case1 (dest_case2 u);
   422       val tab = Symtab.dest (get_datatypes thy);
   423       val (cases', default) = (case split_last cases of
   424           (cases', (("dummy_pattern", []), t)) => (cases', SOME t)
   425         | _ => (cases, NONE))
   426       fun abstr (Free (x, T), body) = Term.absfree (x, T, body)
   427         | abstr (Const ("_constrain", _) $ Free (x, T) $ tT, body) =
   428             Syntax.const Syntax.constrainAbsC $ Term.absfree (x, T, body) $ tT
   429         | abstr (Const ("Pair", _) $ x $ y, body) =
   430             Syntax.const "split" $ abstr (x, abstr (y, body))
   431         | abstr (t, _) = case_error "Illegal pattern" NONE [t];
   432     in case find_first (fn (_, {descr, index, ...}) =>
   433       exists (equal cname o fst) (#3 (snd (List.nth (descr, index))))) tab of
   434         NONE => case_error ("Not a datatype constructor: " ^ cname) NONE [u]
   435       | SOME (tname, {descr, sorts, case_name, index, ...}) =>
   436         let
   437           val _ = if exists (equal "dummy_pattern" o fst o fst) cases' then
   438             case_error "Illegal occurrence of '_' dummy pattern" (SOME tname) [u] else ();
   439           val (_, (_, dts, constrs)) = List.nth (descr, index);
   440           fun find_case (cases, (s, dt)) =
   441             (case find_first (equal s o fst o fst) cases' of
   442                NONE => (case default of
   443                    NONE => case_error ("No clause for constructor " ^ s) (SOME tname) [u]
   444                  | SOME t => (cases, list_abs (map (rpair dummyT) (DatatypeProp.make_tnames
   445                      (map (typ_of_dtyp descr sorts) dt)), t)))
   446              | SOME (c as ((_, vs), t)) =>
   447                  if length dt <> length vs then
   448                     case_error ("Wrong number of arguments for constructor " ^ s)
   449                       (SOME tname) vs
   450                  else (cases \ c, foldr abstr t vs))
   451           val (cases'', fs) = foldl_map find_case (cases', constrs)
   452         in case (cases'', length constrs = length cases', default) of
   453             ([], true, SOME _) =>
   454               case_error "Extra '_' dummy pattern" (SOME tname) [u]
   455           | (_ :: _, _, _) =>
   456               let val extra = distinct (op =) (map (fst o fst) cases'')
   457               in case extra \\ map fst constrs of
   458                   [] => case_error ("More than one clause for constructor(s) " ^
   459                     commas extra) (SOME tname) [u]
   460                 | extra' => case_error ("Illegal constructor(s): " ^ commas extra')
   461                     (SOME tname) [u]
   462               end
   463           | _ => list_comb (Syntax.const case_name, fs) $ t
   464         end
   465     end
   466   | case_tr _ ts = raise TERM ("case_tr", ts);
   467 
   468 fun case_tr' constrs context ts =
   469   if length ts <> length constrs + 1 then raise Match else
   470   let
   471     val (fs, x) = split_last ts;
   472     fun strip_abs 0 t = ([], t)
   473       | strip_abs i (Abs p) =
   474         let val (x, u) = Syntax.atomic_abs_tr' p
   475         in apfst (cons x) (strip_abs (i-1) u) end
   476       | strip_abs i (Const ("split", _) $ t) = (case strip_abs (i+1) t of
   477           (v :: v' :: vs, u) => (Syntax.const "Pair" $ v $ v' :: vs, u));
   478     fun is_dependent i t =
   479       let val k = length (strip_abs_vars t) - i
   480       in k < 0 orelse exists (fn j => j >= k)
   481         (loose_bnos (strip_abs_body t))
   482       end;
   483     val cases = map (fn ((cname, dts), t) =>
   484       (Sign.extern_const (Context.theory_of context) cname,
   485        strip_abs (length dts) t, is_dependent (length dts) t))
   486       (constrs ~~ fs);
   487     fun count_cases (cs, (_, _, true)) = cs
   488       | count_cases (cs, (cname, (_, body), false)) = (case AList.lookup (op =) cs body of
   489           NONE => (body, [cname]) :: cs
   490         | SOME cnames => AList.update (op =) (body, cnames @ [cname]) cs);
   491     val cases' = sort (int_ord o Library.swap o pairself (length o snd))
   492       (Library.foldl count_cases ([], cases));
   493     fun mk_case1 (cname, (vs, body), _) = Syntax.const "_case1" $
   494       list_comb (Syntax.const cname, vs) $ body;
   495   in
   496     Syntax.const "_case_syntax" $ x $
   497       foldr1 (fn (t, u) => Syntax.const "_case2" $ t $ u) (map mk_case1
   498         (case cases' of
   499            [] => cases
   500          | (default, cnames) :: _ =>
   501            if length cnames = 1 then cases
   502            else if length cnames = length constrs then
   503              [hd cases, ("dummy_pattern", ([], default), false)]
   504            else
   505              filter_out (fn (cname, _, _) => cname mem cnames) cases @
   506              [("dummy_pattern", ([], default), false)]))
   507   end;
   508 
   509 fun make_case_tr' case_names descr = List.concat (map
   510   (fn ((_, (_, _, constrs)), case_name) => map (rpair (case_tr' constrs))
   511     (NameSpace.accesses' case_name)) (descr ~~ case_names));
   512 
   513 val trfun_setup =
   514   Theory.add_advanced_trfuns ([], [("_case_syntax", case_tr)], [], []);
   515 
   516 
   517 (* prepare types *)
   518 
   519 fun read_typ sign ((Ts, sorts), str) =
   520   let
   521     val T = Type.no_tvars (Sign.read_typ (sign, AList.lookup (op =)
   522       (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
   523   in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
   524 
   525 fun cert_typ sign ((Ts, sorts), raw_T) =
   526   let
   527     val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
   528       TYPE (msg, _, _) => error msg;
   529     val sorts' = add_typ_tfrees (T, sorts)
   530   in (Ts @ [T],
   531       case duplicates (op =) (map fst sorts') of
   532          [] => sorts'
   533        | dups => error ("Inconsistent sort constraints for " ^ commas dups))
   534   end;
   535 
   536 
   537 (**** make datatype info ****)
   538 
   539 fun make_dt_info descr sorts induct reccomb_names rec_thms
   540     (((((((((i, (_, (tname, _, _))), case_name), case_thms),
   541       exhaustion_thm), distinct_thm), inject), nchotomy), case_cong), weak_case_cong) =
   542   (tname,
   543    {index = i,
   544     descr = descr,
   545     sorts = sorts,
   546     rec_names = reccomb_names,
   547     rec_rewrites = rec_thms,
   548     case_name = case_name,
   549     case_rewrites = case_thms,
   550     induction = induct,
   551     exhaustion = exhaustion_thm,
   552     distinct = distinct_thm,
   553     inject = inject,
   554     nchotomy = nchotomy,
   555     case_cong = case_cong,
   556     weak_case_cong = weak_case_cong});
   557 
   558 
   559 (********************* axiomatic introduction of datatypes ********************)
   560 
   561 fun add_and_get_axioms_atts label tnames attss ts thy =
   562   foldr (fn (((tname, atts), t), (thy', axs)) =>
   563     let
   564       val ([ax], thy'') =
   565         thy'
   566         |> Theory.add_path tname
   567         |> PureThy.add_axioms_i [((label, t), atts)];
   568     in (Theory.parent_path thy'', ax::axs)
   569     end) (thy, []) (tnames ~~ attss ~~ ts) |> swap;
   570 
   571 fun add_and_get_axioms label tnames =
   572   add_and_get_axioms_atts label tnames (replicate (length tnames) []);
   573 
   574 fun add_and_get_axiomss label tnames tss thy =
   575   foldr (fn ((tname, ts), (thy', axss)) =>
   576     let
   577       val ([axs], thy'') =
   578         thy'
   579         |> Theory.add_path tname
   580         |> PureThy.add_axiomss_i [((label, ts), [])];
   581     in (Theory.parent_path thy'', axs::axss)
   582     end) (thy, []) (tnames ~~ tss) |> swap;
   583 
   584 fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   585     case_names_induct case_names_exhausts thy =
   586   let
   587     val descr' = List.concat descr;
   588     val recTs = get_rec_types descr' sorts;
   589     val used = foldr add_typ_tfree_names [] recTs;
   590     val newTs = Library.take (length (hd descr), recTs);
   591 
   592     val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists
   593       (fn dt => is_rec_type dt andalso not (null (fst (strip_dtyp dt))))
   594         cargs) constrs) descr';
   595 
   596     (**** declare new types and constants ****)
   597 
   598     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
   599 
   600     val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
   601       map (fn ((_, cargs), (cname, mx)) =>
   602         (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   603           (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
   604 
   605     val (rec_result_Ts, reccomb_fn_Ts) = DatatypeProp.make_primrec_Ts descr sorts used;
   606 
   607     val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
   608     val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
   609       (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
   610         (1 upto (length descr')));
   611 
   612     val size_names = DatatypeProp.indexify_names
   613       (map (fn T => name_of_typ T ^ "_size") (Library.drop (length (hd descr), recTs)));
   614 
   615     val freeT = TFree (variant used "'t", HOLogic.typeS);
   616     val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
   617       map (fn (_, cargs) =>
   618         let val Ts = map (typ_of_dtyp descr' sorts) cargs
   619         in Ts ---> freeT end) constrs) (hd descr);
   620 
   621     val case_names = map (fn s => (s ^ "_case")) new_type_names;
   622 
   623     val thy2' = thy |>
   624 
   625       (** new types **)
   626 
   627       curry (Library.foldr (fn (((name, mx), tvs), thy') => thy' |>
   628           TypedefPackage.add_typedecls [(name, tvs, mx)]))
   629         (types_syntax ~~ tyvars) |>
   630       add_path flat_names (space_implode "_" new_type_names) |>
   631 
   632       (** primrec combinators **)
   633 
   634       Theory.add_consts_i (map (fn ((name, T), T') =>
   635         (name, reccomb_fn_Ts @ [T] ---> T', NoSyn))
   636           (reccomb_names ~~ recTs ~~ rec_result_Ts)) |>
   637 
   638       (** case combinators **)
   639 
   640       Theory.add_consts_i (map (fn ((name, T), Ts) =>
   641         (name, Ts @ [T] ---> freeT, NoSyn))
   642           (case_names ~~ newTs ~~ case_fn_Ts));
   643 
   644     val reccomb_names' = map (Sign.intern_const thy2') reccomb_names;
   645     val case_names' = map (Sign.intern_const thy2') case_names;
   646 
   647     val thy2 = thy2' |>
   648 
   649       (** size functions **)
   650 
   651       (if no_size then I else Theory.add_consts_i (map (fn (s, T) =>
   652         (Sign.base_name s, T --> HOLogic.natT, NoSyn))
   653           (size_names ~~ Library.drop (length (hd descr), recTs)))) |>
   654 
   655       (** constructors **)
   656 
   657       parent_path flat_names |>
   658       curry (Library.foldr (fn (((((_, (_, _, constrs)), T), tname),
   659         constr_syntax'), thy') => thy' |>
   660           add_path flat_names tname |>
   661             Theory.add_consts_i (map (fn ((_, cargs), (cname, mx)) =>
   662               (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   663                 (constrs ~~ constr_syntax')) |>
   664           parent_path flat_names))
   665             (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
   666 
   667     (**** introduction of axioms ****)
   668 
   669     val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
   670     val size_axs = if no_size then [] else DatatypeProp.make_size descr sorts thy2;
   671 
   672     val ((([induct], [rec_thms]), inject), thy3) =
   673       thy2
   674       |> Theory.add_path (space_implode "_" new_type_names)
   675       |> PureThy.add_axioms_i [(("induct", DatatypeProp.make_ind descr sorts),
   676           [case_names_induct])]
   677       ||>> PureThy.add_axiomss_i [(("recs", rec_axs), [])]
   678       ||> (if no_size then I else snd o PureThy.add_axiomss_i [(("size", size_axs), [])])
   679       ||> Theory.parent_path
   680       ||>> add_and_get_axiomss "inject" new_type_names
   681             (DatatypeProp.make_injs descr sorts);
   682     val size_thms = if no_size then [] else get_thms thy3 (Name "size");
   683     val (distinct, thy4) = add_and_get_axiomss "distinct" new_type_names
   684       (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
   685 
   686     val exhaust_ts = DatatypeProp.make_casedists descr sorts;
   687     val (exhaustion, thy5) = add_and_get_axioms_atts "exhaust" new_type_names
   688       (map Library.single case_names_exhausts) exhaust_ts thy4;
   689     val (case_thms, thy6) = add_and_get_axiomss "cases" new_type_names
   690       (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
   691     val (split_ts, split_asm_ts) = ListPair.unzip
   692       (DatatypeProp.make_splits new_type_names descr sorts thy6);
   693     val (split, thy7) = add_and_get_axioms "split" new_type_names split_ts thy6;
   694     val (split_asm, thy8) = add_and_get_axioms "split_asm" new_type_names
   695       split_asm_ts thy7;
   696     val (nchotomys, thy9) = add_and_get_axioms "nchotomy" new_type_names
   697       (DatatypeProp.make_nchotomys descr sorts) thy8;
   698     val (case_congs, thy10) = add_and_get_axioms "case_cong" new_type_names
   699       (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
   700     val (weak_case_congs, thy11) = add_and_get_axioms "weak_case_cong" new_type_names
   701       (DatatypeProp.make_weak_case_congs new_type_names descr sorts thy10) thy10;
   702 
   703     val dt_infos = map (make_dt_info descr' sorts induct reccomb_names' rec_thms)
   704       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
   705         exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
   706           nchotomys ~~ case_congs ~~ weak_case_congs);
   707 
   708     val simps = List.concat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   709     val split_thms = split ~~ split_asm;
   710 
   711     val thy12 =
   712       thy11
   713       |> Theory.add_advanced_trfuns ([], [], make_case_tr' case_names' (hd descr), [])
   714       |> Theory.add_path (space_implode "_" new_type_names)
   715       |> add_rules simps case_thms size_thms rec_thms inject distinct
   716           weak_case_congs Simplifier.cong_add
   717       |> put_datatypes (fold Symtab.update dt_infos dt_info)
   718       |> add_cases_induct dt_infos induct
   719       |> Theory.parent_path
   720       |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
   721       |> DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos)
   722       |> fold (CodegenPackage.add_case_const_i get_case_const_data) case_names';
   723   in
   724     ({distinct = distinct,
   725       inject = inject,
   726       exhaustion = exhaustion,
   727       rec_thms = rec_thms,
   728       case_thms = case_thms,
   729       split_thms = split_thms,
   730       induction = induct,
   731       size = size_thms,
   732       simps = simps}, thy12)
   733   end;
   734 
   735 
   736 (******************* definitional introduction of datatypes *******************)
   737 
   738 fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   739     case_names_induct case_names_exhausts thy =
   740   let
   741     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   742 
   743     val ((inject, distinct, dist_rewrites, simproc_dists, induct), thy2) = thy |>
   744       DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
   745         types_syntax constr_syntax case_names_induct;
   746 
   747     val (casedist_thms, thy3) = DatatypeAbsProofs.prove_casedist_thms new_type_names descr
   748       sorts induct case_names_exhausts thy2;
   749     val ((reccomb_names, rec_thms), thy4) = DatatypeAbsProofs.prove_primrec_thms
   750       flat_names new_type_names descr sorts dt_info inject dist_rewrites dist_ss induct thy3;
   751     val ((case_thms, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
   752       flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
   753     val (split_thms, thy7) = DatatypeAbsProofs.prove_split_thms new_type_names
   754       descr sorts inject dist_rewrites casedist_thms case_thms thy6;
   755     val (nchotomys, thy8) = DatatypeAbsProofs.prove_nchotomys new_type_names
   756       descr sorts casedist_thms thy7;
   757     val (case_congs, thy9) = DatatypeAbsProofs.prove_case_congs new_type_names
   758       descr sorts nchotomys case_thms thy8;
   759     val (weak_case_congs, thy10) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   760       descr sorts thy9;
   761     val (size_thms, thy11) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
   762       descr sorts reccomb_names rec_thms thy10;
   763 
   764     val dt_infos = map (make_dt_info (List.concat descr) sorts induct reccomb_names rec_thms)
   765       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
   766         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
   767 
   768     val simps = List.concat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   769 
   770     val thy12 =
   771       thy11
   772       |> Theory.add_advanced_trfuns ([], [], make_case_tr' case_names (hd descr), [])
   773       |> Theory.add_path (space_implode "_" new_type_names)
   774       |> add_rules simps case_thms size_thms rec_thms inject distinct
   775           weak_case_congs (Simplifier.attrib (op addcongs))
   776       |> put_datatypes (fold Symtab.update dt_infos dt_info)
   777       |> add_cases_induct dt_infos induct
   778       |> Theory.parent_path
   779       |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
   780       |> DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos)
   781       |> fold (CodegenPackage.add_case_const_i get_case_const_data) case_names;
   782   in
   783     ({distinct = distinct,
   784       inject = inject,
   785       exhaustion = casedist_thms,
   786       rec_thms = rec_thms,
   787       case_thms = case_thms,
   788       split_thms = split_thms,
   789       induction = induct,
   790       size = size_thms,
   791       simps = simps}, thy12)
   792   end;
   793 
   794 
   795 (*********************** declare existing type as datatype *********************)
   796 
   797 fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
   798   let
   799     val _ = Theory.requires thy0 "Inductive" "datatype representations";
   800 
   801     val (((distinct, inject), [induction]), thy1) =
   802       thy0
   803       |> fold_map apply_theorems raw_distinct
   804       ||>> fold_map apply_theorems raw_inject
   805       ||>> apply_theorems [raw_induction];
   806     val sign = Theory.sign_of thy1;
   807 
   808     val induction' = freezeT induction;
   809 
   810     fun err t = error ("Ill-formed predicate in induction rule: " ^
   811       Sign.string_of_term sign t);
   812 
   813     fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
   814           ((tname, map dest_TFree Ts) handle TERM _ => err t)
   815       | get_typ t = err t;
   816 
   817     val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induction')));
   818     val new_type_names = getOpt (alt_names, map fst dtnames);
   819 
   820     fun get_constr t = (case Logic.strip_assums_concl t of
   821         _ $ (_ $ t') => (case head_of t' of
   822             Const (cname, cT) => (case strip_type cT of
   823                 (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
   824               | _ => err t)
   825           | _ => err t)
   826       | _ => err t);
   827 
   828     fun make_dt_spec [] _ _ = []
   829       | make_dt_spec ((tname, tvs)::dtnames') i constrs =
   830           let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
   831           in (i, (tname, map DtTFree tvs, map snd constrs'))::
   832             (make_dt_spec dtnames' (i + 1) constrs'')
   833           end;
   834 
   835     val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
   836     val sorts = add_term_tfrees (concl_of induction', []);
   837     val dt_info = get_datatypes thy1;
   838 
   839     val case_names_induct = mk_case_names_induct descr;
   840     val case_names_exhausts = mk_case_names_exhausts descr (map #1 dtnames);
   841     
   842 
   843     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   844 
   845     val (casedist_thms, thy2) = thy1 |>
   846       DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction
   847         case_names_exhausts;
   848     val ((reccomb_names, rec_thms), thy3) = DatatypeAbsProofs.prove_primrec_thms
   849       false new_type_names [descr] sorts dt_info inject distinct dist_ss induction thy2;
   850     val ((case_thms, case_names), thy4) = DatatypeAbsProofs.prove_case_thms false
   851       new_type_names [descr] sorts reccomb_names rec_thms thy3;
   852     val (split_thms, thy5) = DatatypeAbsProofs.prove_split_thms
   853       new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
   854     val (nchotomys, thy6) = DatatypeAbsProofs.prove_nchotomys new_type_names
   855       [descr] sorts casedist_thms thy5;
   856     val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
   857       [descr] sorts nchotomys case_thms thy6;
   858     val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   859       [descr] sorts thy7;
   860     val (size_thms, thy9) =
   861       if Context.exists_name "NatArith" thy8 then
   862         DatatypeAbsProofs.prove_size_thms false new_type_names
   863           [descr] sorts reccomb_names rec_thms thy8
   864       else ([], thy8);
   865 
   866     val ((_, [induction']), thy10) =
   867       thy9
   868       |> store_thmss "inject" new_type_names inject
   869       ||>> store_thmss "distinct" new_type_names distinct
   870       ||> Theory.add_path (space_implode "_" new_type_names)
   871       ||>> PureThy.add_thms [(("induct", induction), [case_names_induct])];
   872 
   873     val dt_infos = map (make_dt_info descr sorts induction' reccomb_names rec_thms)
   874       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
   875         map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
   876 
   877     val simps = List.concat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   878 
   879     val thy11 = thy10 |>
   880       Theory.add_advanced_trfuns ([], [], make_case_tr' case_names descr, []) |>
   881       add_rules simps case_thms size_thms rec_thms inject distinct
   882         weak_case_congs (Simplifier.attrib (op addcongs)) |> 
   883       put_datatypes (fold Symtab.update dt_infos dt_info) |>
   884       add_cases_induct dt_infos induction' |>
   885       Theory.parent_path |>
   886       (snd o store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)) |>
   887       DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos);
   888   in
   889     ({distinct = distinct,
   890       inject = inject,
   891       exhaustion = casedist_thms,
   892       rec_thms = rec_thms,
   893       case_thms = case_thms,
   894       split_thms = split_thms,
   895       induction = induction',
   896       size = size_thms,
   897       simps = simps}, thy11)
   898   end;
   899 
   900 val rep_datatype = gen_rep_datatype IsarThy.apply_theorems;
   901 val rep_datatype_i = gen_rep_datatype IsarThy.apply_theorems_i;
   902 
   903 
   904 
   905 (******************************** add datatype ********************************)
   906 
   907 fun gen_add_datatype prep_typ err flat_names new_type_names dts thy =
   908   let
   909     val _ = Theory.requires thy "Datatype_Universe" "datatype definitions";
   910 
   911     (* this theory is used just for parsing *)
   912 
   913     val tmp_thy = thy |>
   914       Theory.copy |>
   915       Theory.add_types (map (fn (tvs, tname, mx, _) =>
   916         (tname, length tvs, mx)) dts);
   917 
   918     val sign = Theory.sign_of tmp_thy;
   919 
   920     val (tyvars, _, _, _)::_ = dts;
   921     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   922       let val full_tname = Sign.full_name sign (Syntax.type_name tname mx)
   923       in (case duplicates (op =) tvs of
   924             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   925                   else error ("Mutually recursive datatypes must have same type parameters")
   926           | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
   927               " : " ^ commas dups))
   928       end) dts);
   929 
   930     val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
   931       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   932 
   933     fun prep_dt_spec ((dts', constr_syntax, sorts, i), (tvs, tname, mx, constrs)) =
   934       let
   935         fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
   936           let
   937             val (cargs', sorts'') = Library.foldl (prep_typ sign) (([], sorts'), cargs);
   938             val _ = (case foldr add_typ_tfree_names [] cargs' \\ tvs of
   939                 [] => ()
   940               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   941           in (constrs @ [((if flat_names then Sign.full_name sign else
   942                 Sign.full_name_path sign tname) (Syntax.const_name cname mx'),
   943                    map (dtyp_of_typ new_dts) cargs')],
   944               constr_syntax' @ [(cname, mx')], sorts'')
   945           end handle ERROR msg =>
   946             cat_error msg ("The error above occured in constructor " ^ cname ^
   947               " of datatype " ^ tname);
   948 
   949         val (constrs', constr_syntax', sorts') =
   950           Library.foldl prep_constr (([], [], sorts), constrs)
   951 
   952       in
   953         case duplicates (op =) (map fst constrs') of
   954            [] =>
   955              (dts' @ [(i, (Sign.full_name sign (Syntax.type_name tname mx),
   956                 map DtTFree tvs, constrs'))],
   957               constr_syntax @ [constr_syntax'], sorts', i + 1)
   958          | dups => error ("Duplicate constructors " ^ commas dups ^
   959              " in datatype " ^ tname)
   960       end;
   961 
   962     val (dts', constr_syntax, sorts', i) = Library.foldl prep_dt_spec (([], [], [], 0), dts);
   963     val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
   964     val dt_info = get_datatypes thy;
   965     val (descr, _) = unfold_datatypes sign dts' sorts dt_info dts' i;
   966     val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
   967       if err then error ("Nonemptiness check failed for datatype " ^ s)
   968       else raise exn;
   969 
   970     val descr' = List.concat descr;
   971     val case_names_induct = mk_case_names_induct descr';
   972     val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
   973   in
   974     (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
   975       flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   976       case_names_induct case_names_exhausts thy
   977   end;
   978 
   979 val add_datatype_i = gen_add_datatype cert_typ;
   980 val add_datatype = gen_add_datatype read_typ true;
   981 
   982 
   983 
   984 (** package setup **)
   985 
   986 (* setup theory *)
   987 
   988 val setup =
   989   DatatypesData.init #> Method.add_methods tactic_emulations #> simproc_setup #> trfun_setup;
   990 
   991 
   992 (* outer syntax *)
   993 
   994 local structure P = OuterParse and K = OuterKeyword in
   995 
   996 val datatype_decl =
   997   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
   998     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
   999 
  1000 fun mk_datatype args =
  1001   let
  1002     val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
  1003     val specs = map (fn ((((_, vs), t), mx), cons) =>
  1004       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
  1005   in snd o add_datatype false names specs end;
  1006 
  1007 val datatypeP =
  1008   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
  1009     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
  1010 
  1011 
  1012 val rep_datatype_decl =
  1013   Scan.option (Scan.repeat1 P.name) --
  1014     Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 P.xthms1)) [[]] --
  1015     Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 P.xthms1)) [[]] --
  1016     (P.$$$ "induction" |-- P.!!! P.xthm);
  1017 
  1018 fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #2 o rep_datatype opt_ts dss iss ind;
  1019 
  1020 val rep_datatypeP =
  1021   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
  1022     (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
  1023 
  1024 
  1025 val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
  1026 val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
  1027 
  1028 end;
  1029 
  1030 
  1031 end;
  1032 
  1033 structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
  1034 open BasicDatatypePackage;
  1035