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