src/HOL/Tools/Datatype/datatype_aux.ML
author haftmann
Mon Sep 28 14:54:15 2009 +0200 (2009-09-28)
changeset 32730 3958b45b29e4
parent 32727 9072201cd69d
child 32733 71618deaf777
permissions -rw-r--r--
tuned
     1 (*  Title:      HOL/Tools/datatype_aux.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Auxiliary functions for defining datatypes.
     5 *)
     6 
     7 signature DATATYPE_COMMON =
     8 sig
     9   type config
    10   val default_config : config
    11   datatype dtyp =
    12       DtTFree of string
    13     | DtType of string * (dtyp list)
    14     | DtRec of int;
    15   type descr
    16   type info
    17 end
    18 
    19 signature DATATYPE_AUX =
    20 sig
    21   include DATATYPE_COMMON
    22 
    23   val message : config -> string -> unit
    24   
    25   val store_thmss_atts : string -> string list -> attribute list list -> thm list list
    26     -> theory -> thm list list * theory
    27   val store_thmss : string -> string list -> thm list list -> theory -> thm list list * theory
    28   val store_thms_atts : string -> string list -> attribute list list -> thm list
    29     -> theory -> thm list * theory
    30   val store_thms : string -> string list -> thm list -> theory -> thm list * theory
    31 
    32   val split_conj_thm : thm -> thm list
    33   val mk_conj : term list -> term
    34   val mk_disj : term list -> term
    35 
    36   val app_bnds : term -> int -> term
    37 
    38   val cong_tac : int -> tactic
    39   val indtac : thm -> string list -> int -> tactic
    40   val exh_tac : (string -> thm) -> int -> tactic
    41 
    42   datatype simproc_dist = FewConstrs of thm list
    43                         | ManyConstrs of thm * simpset;
    44 
    45 
    46   exception Datatype
    47   exception Datatype_Empty of string
    48   val name_of_typ : typ -> string
    49   val dtyp_of_typ : (string * string list) list -> typ -> dtyp
    50   val mk_Free : string -> typ -> int -> term
    51   val is_rec_type : dtyp -> bool
    52   val typ_of_dtyp : descr -> (string * sort) list -> dtyp -> typ
    53   val dest_DtTFree : dtyp -> string
    54   val dest_DtRec : dtyp -> int
    55   val strip_dtyp : dtyp -> dtyp list * dtyp
    56   val body_index : dtyp -> int
    57   val mk_fun_dtyp : dtyp list -> dtyp -> dtyp
    58   val get_nonrec_types : descr -> (string * sort) list -> typ list
    59   val get_branching_types : descr -> (string * sort) list -> typ list
    60   val get_arities : descr -> int list
    61   val get_rec_types : descr -> (string * sort) list -> typ list
    62   val interpret_construction : descr -> (string * sort) list
    63     -> { atyp: typ -> 'a, dtyp: typ list -> int * bool -> string * typ list -> 'a }
    64     -> ((string * Term.typ list) * (string * 'a list) list) list
    65   val check_nonempty : descr list -> unit
    66   val unfold_datatypes : 
    67     theory -> descr -> (string * sort) list -> info Symtab.table ->
    68       descr -> int -> descr list * int
    69 end;
    70 
    71 structure DatatypeAux : DATATYPE_AUX =
    72 struct
    73 
    74 (* datatype option flags *)
    75 
    76 type config = { strict: bool, quiet: bool };
    77 val default_config : config =
    78   { strict = true, quiet = false };
    79 fun message ({ quiet, ...} : config) s =
    80   if quiet then () else writeln s;
    81 
    82 
    83 (* store theorems in theory *)
    84 
    85 fun store_thmss_atts label tnames attss thmss =
    86   fold_map (fn ((tname, atts), thms) =>
    87     Sign.add_path tname
    88     #> PureThy.add_thmss [((Binding.name label, thms), atts)]
    89     #-> (fn thm::_ => Sign.parent_path #> pair thm)) (tnames ~~ attss ~~ thmss)
    90   ##> Theory.checkpoint;
    91 
    92 fun store_thmss label tnames = store_thmss_atts label tnames (replicate (length tnames) []);
    93 
    94 fun store_thms_atts label tnames attss thmss =
    95   fold_map (fn ((tname, atts), thms) =>
    96     Sign.add_path tname
    97     #> PureThy.add_thms [((Binding.name label, thms), atts)]
    98     #-> (fn thm::_ => Sign.parent_path #> pair thm)) (tnames ~~ attss ~~ thmss)
    99   ##> Theory.checkpoint;
   100 
   101 fun store_thms label tnames = store_thms_atts label tnames (replicate (length tnames) []);
   102 
   103 
   104 (* split theorem thm_1 & ... & thm_n into n theorems *)
   105 
   106 fun split_conj_thm th =
   107   ((th RS conjunct1)::(split_conj_thm (th RS conjunct2))) handle THM _ => [th];
   108 
   109 val mk_conj = foldr1 (HOLogic.mk_binop "op &");
   110 val mk_disj = foldr1 (HOLogic.mk_binop "op |");
   111 
   112 fun app_bnds t i = list_comb (t, map Bound (i - 1 downto 0));
   113 
   114 
   115 fun cong_tac i st = (case Logic.strip_assums_concl
   116   (List.nth (prems_of st, i - 1)) of
   117     _ $ (_ $ (f $ x) $ (g $ y)) =>
   118       let
   119         val cong' = Thm.lift_rule (Thm.cprem_of st i) cong;
   120         val _ $ (_ $ (f' $ x') $ (g' $ y')) =
   121           Logic.strip_assums_concl (prop_of cong');
   122         val insts = map (pairself (cterm_of (Thm.theory_of_thm st)) o
   123           apsnd (curry list_abs (Logic.strip_params (concl_of cong'))) o
   124             apfst head_of) [(f', f), (g', g), (x', x), (y', y)]
   125       in compose_tac (false, cterm_instantiate insts cong', 2) i st
   126         handle THM _ => no_tac st
   127       end
   128   | _ => no_tac st);
   129 
   130 (* instantiate induction rule *)
   131 
   132 fun indtac indrule indnames i st =
   133   let
   134     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
   135     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop
   136       (Logic.strip_imp_concl (List.nth (prems_of st, i - 1))));
   137     val getP = if can HOLogic.dest_imp (hd ts) then
   138       (apfst SOME) o HOLogic.dest_imp else pair NONE;
   139     val flt = if null indnames then I else
   140       filter (fn Free (s, _) => s mem indnames | _ => false);
   141     fun abstr (t1, t2) = (case t1 of
   142         NONE => (case flt (OldTerm.term_frees t2) of
   143             [Free (s, T)] => SOME (absfree (s, T, t2))
   144           | _ => NONE)
   145       | SOME (_ $ t') => SOME (Abs ("x", fastype_of t', abstract_over (t', t2))))
   146     val cert = cterm_of (Thm.theory_of_thm st);
   147     val insts = List.mapPartial (fn (t, u) => case abstr (getP u) of
   148         NONE => NONE
   149       | SOME u' => SOME (t |> getP |> snd |> head_of |> cert, cert u')) (ts ~~ ts');
   150     val indrule' = cterm_instantiate insts indrule
   151   in
   152     rtac indrule' i st
   153   end;
   154 
   155 (* perform exhaustive case analysis on last parameter of subgoal i *)
   156 
   157 fun exh_tac exh_thm_of i state =
   158   let
   159     val thy = Thm.theory_of_thm state;
   160     val prem = nth (prems_of state) (i - 1);
   161     val params = Logic.strip_params prem;
   162     val (_, Type (tname, _)) = hd (rev params);
   163     val exhaustion = Thm.lift_rule (Thm.cprem_of state i) (exh_thm_of tname);
   164     val prem' = hd (prems_of exhaustion);
   165     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
   166     val exhaustion' = cterm_instantiate [(cterm_of thy (head_of lhs),
   167       cterm_of thy (List.foldr (fn ((_, T), t) => Abs ("z", T, t))
   168         (Bound 0) params))] exhaustion
   169   in compose_tac (false, exhaustion', nprems_of exhaustion) i state
   170   end;
   171 
   172 (* handling of distinctness theorems *)
   173 
   174 datatype simproc_dist = FewConstrs of thm list
   175                       | ManyConstrs of thm * simpset;
   176 
   177 (********************** Internal description of datatypes *********************)
   178 
   179 datatype dtyp =
   180     DtTFree of string
   181   | DtType of string * (dtyp list)
   182   | DtRec of int;
   183 
   184 (* information about datatypes *)
   185 
   186 (* index, datatype name, type arguments, constructor name, types of constructor's arguments *)
   187 type descr = (int * (string * dtyp list * (string * dtyp list) list)) list;
   188 
   189 type info =
   190   {index : int,
   191    alt_names : string list option,
   192    descr : descr,
   193    sorts : (string * sort) list,
   194    inject : thm list,
   195    distinct : simproc_dist,
   196    induct : thm,
   197    inducts : thm list,
   198    exhaust : thm,
   199    nchotomy : thm,
   200    rec_names : string list,
   201    rec_rewrites : thm list,
   202    case_name : string,
   203    case_rewrites : thm list,
   204    case_cong : thm,
   205    weak_case_cong : thm,
   206    split : thm,
   207    split_asm: thm};
   208 
   209 fun mk_Free s T i = Free (s ^ (string_of_int i), T);
   210 
   211 fun subst_DtTFree _ substs (T as (DtTFree name)) =
   212       AList.lookup (op =) substs name |> the_default T
   213   | subst_DtTFree i substs (DtType (name, ts)) =
   214       DtType (name, map (subst_DtTFree i substs) ts)
   215   | subst_DtTFree i _ (DtRec j) = DtRec (i + j);
   216 
   217 exception Datatype;
   218 exception Datatype_Empty of string;
   219 
   220 fun dest_DtTFree (DtTFree a) = a
   221   | dest_DtTFree _ = raise Datatype;
   222 
   223 fun dest_DtRec (DtRec i) = i
   224   | dest_DtRec _ = raise Datatype;
   225 
   226 fun is_rec_type (DtType (_, dts)) = exists is_rec_type dts
   227   | is_rec_type (DtRec _) = true
   228   | is_rec_type _ = false;
   229 
   230 fun strip_dtyp (DtType ("fun", [T, U])) = apfst (cons T) (strip_dtyp U)
   231   | strip_dtyp T = ([], T);
   232 
   233 val body_index = dest_DtRec o snd o strip_dtyp;
   234 
   235 fun mk_fun_dtyp [] U = U
   236   | mk_fun_dtyp (T :: Ts) U = DtType ("fun", [T, mk_fun_dtyp Ts U]);
   237 
   238 fun name_of_typ (Type (s, Ts)) =
   239       let val s' = Long_Name.base_name s
   240       in space_implode "_" (List.filter (not o equal "") (map name_of_typ Ts) @
   241         [if Syntax.is_identifier s' then s' else "x"])
   242       end
   243   | name_of_typ _ = "";
   244 
   245 fun dtyp_of_typ _ (TFree (n, _)) = DtTFree n
   246   | dtyp_of_typ _ (TVar _) = error "Illegal schematic type variable(s)"
   247   | dtyp_of_typ new_dts (Type (tname, Ts)) =
   248       (case AList.lookup (op =) new_dts tname of
   249          NONE => DtType (tname, map (dtyp_of_typ new_dts) Ts)
   250        | SOME vs => if map (try (fst o dest_TFree)) Ts = map SOME vs then
   251              DtRec (find_index (curry op = tname o fst) new_dts)
   252            else error ("Illegal occurrence of recursive type " ^ tname));
   253 
   254 fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, (the o AList.lookup (op =) sorts) a)
   255   | typ_of_dtyp descr sorts (DtRec i) =
   256       let val (s, ds, _) = (the o AList.lookup (op =) descr) i
   257       in Type (s, map (typ_of_dtyp descr sorts) ds) end
   258   | typ_of_dtyp descr sorts (DtType (s, ds)) =
   259       Type (s, map (typ_of_dtyp descr sorts) ds);
   260 
   261 (* find all non-recursive types in datatype description *)
   262 
   263 fun get_nonrec_types descr sorts =
   264   map (typ_of_dtyp descr sorts) (Library.foldl (fn (Ts, (_, (_, _, constrs))) =>
   265     Library.foldl (fn (Ts', (_, cargs)) =>
   266       filter_out is_rec_type cargs union Ts') (Ts, constrs)) ([], descr));
   267 
   268 (* get all recursive types in datatype description *)
   269 
   270 fun get_rec_types descr sorts = map (fn (_ , (s, ds, _)) =>
   271   Type (s, map (typ_of_dtyp descr sorts) ds)) descr;
   272 
   273 (* get all branching types *)
   274 
   275 fun get_branching_types descr sorts =
   276   map (typ_of_dtyp descr sorts) (fold (fn (_, (_, _, constrs)) =>
   277     fold (fn (_, cargs) => fold (strip_dtyp #> fst #> fold (insert op =)) cargs)
   278       constrs) descr []);
   279 
   280 fun get_arities descr = fold (fn (_, (_, _, constrs)) =>
   281   fold (fn (_, cargs) => fold (insert op =) (map (length o fst o strip_dtyp)
   282     (List.filter is_rec_type cargs))) constrs) descr [];
   283 
   284 (* interpret construction of datatype *)
   285 
   286 fun interpret_construction descr vs { atyp, dtyp } =
   287   let
   288     val typ_of_dtyp = typ_of_dtyp descr vs;
   289     fun interpT dT = case strip_dtyp dT
   290      of (dTs, DtRec l) =>
   291           let
   292             val (tyco, dTs', _) = (the o AList.lookup (op =) descr) l;
   293             val Ts = map typ_of_dtyp dTs;
   294             val Ts' = map typ_of_dtyp dTs';
   295             val is_proper = forall (can dest_TFree) Ts';
   296           in dtyp Ts (l, is_proper) (tyco, Ts') end
   297       | _ => atyp (typ_of_dtyp dT);
   298     fun interpC (c, dTs) = (c, map interpT dTs);
   299     fun interpD (_, (tyco, dTs, cs)) = ((tyco, map typ_of_dtyp dTs), map interpC cs);
   300   in map interpD descr end;
   301 
   302 (* nonemptiness check for datatypes *)
   303 
   304 fun check_nonempty descr =
   305   let
   306     val descr' = List.concat descr;
   307     fun is_nonempty_dt is i =
   308       let
   309         val (_, _, constrs) = (the o AList.lookup (op =) descr') i;
   310         fun arg_nonempty (_, DtRec i) = if i mem is then false
   311               else is_nonempty_dt (i::is) i
   312           | arg_nonempty _ = true;
   313       in exists ((forall (arg_nonempty o strip_dtyp)) o snd) constrs
   314       end
   315   in assert_all (fn (i, _) => is_nonempty_dt [i] i) (hd descr)
   316     (fn (_, (s, _, _)) => raise Datatype_Empty s)
   317   end;
   318 
   319 (* unfold a list of mutually recursive datatype specifications *)
   320 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   321 (* need to be unfolded                                         *)
   322 
   323 fun unfold_datatypes sign orig_descr sorts (dt_info : info Symtab.table) descr i =
   324   let
   325     fun typ_error T msg = error ("Non-admissible type expression\n" ^
   326       Syntax.string_of_typ_global sign (typ_of_dtyp (orig_descr @ descr) sorts T) ^ "\n" ^ msg);
   327 
   328     fun get_dt_descr T i tname dts =
   329       (case Symtab.lookup dt_info tname of
   330          NONE => typ_error T (tname ^ " is not a datatype - can't use it in\
   331            \ nested recursion")
   332        | (SOME {index, descr, ...}) =>
   333            let val (_, vars, _) = (the o AList.lookup (op =) descr) index;
   334                val subst = ((map dest_DtTFree vars) ~~ dts) handle Library.UnequalLengths =>
   335                  typ_error T ("Type constructor " ^ tname ^ " used with wrong\
   336                   \ number of arguments")
   337            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
   338              (tn, map (subst_DtTFree i subst) args,
   339               map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   340            end);
   341 
   342     (* unfold a single constructor argument *)
   343 
   344     fun unfold_arg ((i, Ts, descrs), T) =
   345       if is_rec_type T then
   346         let val (Us, U) = strip_dtyp T
   347         in if exists is_rec_type Us then
   348             typ_error T "Non-strictly positive recursive occurrence of type"
   349           else (case U of
   350               DtType (tname, dts) =>  
   351                 let
   352                   val (index, descr) = get_dt_descr T i tname dts;
   353                   val (descr', i') = unfold_datatypes sign orig_descr sorts
   354                     dt_info descr (i + length descr)
   355                 in (i', Ts @ [mk_fun_dtyp Us (DtRec index)], descrs @ descr') end
   356             | _ => (i, Ts @ [T], descrs))
   357         end
   358       else (i, Ts @ [T], descrs);
   359 
   360     (* unfold a constructor *)
   361 
   362     fun unfold_constr ((i, constrs, descrs), (cname, cargs)) =
   363       let val (i', cargs', descrs') = Library.foldl unfold_arg ((i, [], descrs), cargs)
   364       in (i', constrs @ [(cname, cargs')], descrs') end;
   365 
   366     (* unfold a single datatype *)
   367 
   368     fun unfold_datatype ((i, dtypes, descrs), (j, (tname, tvars, constrs))) =
   369       let val (i', constrs', descrs') =
   370         Library.foldl unfold_constr ((i, [], descrs), constrs)
   371       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs')
   372       end;
   373 
   374     val (i', descr', descrs) = Library.foldl unfold_datatype ((i, [],[]), descr);
   375 
   376   in (descr' :: descrs, i') end;
   377 
   378 end;