src/HOL/Tools/datatype_aux.ML
author wenzelm
Wed Mar 17 16:53:46 1999 +0100 (1999-03-17)
changeset 6394 3d9fd50fcc43
parent 6092 d9db67970c73
child 7015 85be09eb136c
permissions -rw-r--r--
Theory.sign_of;
     1 (*  Title:      HOL/Tools/datatype_aux.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer
     4     Copyright   1998  TU Muenchen
     5 
     6 Auxiliary functions for defining datatypes
     7 *)
     8 
     9 signature DATATYPE_AUX =
    10 sig
    11   val quiet_mode : bool ref
    12   val message : string -> unit
    13   
    14   val foldl1 : ('a * 'a -> 'a) -> 'a list -> 'a
    15 
    16   val get_thy : string -> theory -> theory option
    17 
    18   val add_path : bool -> string -> theory -> theory
    19   val parent_path : bool -> theory -> theory
    20 
    21   val store_thmss : string -> string list -> thm list list -> theory -> theory
    22   val store_thms : string -> string list -> thm list -> theory -> theory
    23 
    24   val split_conj_thm : thm -> thm list
    25   val mk_conj : term list -> term
    26   val mk_disj : term list -> term
    27 
    28   val indtac : thm -> int -> tactic
    29   val exh_tac : (string -> thm) -> int -> tactic
    30 
    31   datatype dtyp =
    32       DtTFree of string
    33     | DtType of string * (dtyp list)
    34     | DtRec of int;
    35 
    36   type datatype_info
    37 
    38   val dtyp_of_typ : (string * string list) list -> typ -> dtyp
    39   val mk_Free : string -> typ -> int -> term
    40   val is_rec_type : dtyp -> bool
    41   val typ_of_dtyp : (int * (string * dtyp list *
    42     (string * dtyp list) list)) list -> (string * sort) list -> dtyp -> typ
    43   val dest_DtTFree : dtyp -> string
    44   val dest_DtRec : dtyp -> int
    45   val dest_TFree : typ -> string
    46   val dest_conj : term -> term list
    47   val get_nonrec_types : (int * (string * dtyp list *
    48     (string * dtyp list) list)) list -> (string * sort) list -> typ list
    49   val get_rec_types : (int * (string * dtyp list *
    50     (string * dtyp list) list)) list -> (string * sort) list -> typ list
    51   val check_nonempty : (int * (string * dtyp list *
    52     (string * dtyp list) list)) list list -> unit
    53   val unfold_datatypes : 
    54     datatype_info Symtab.table ->
    55       (int * (string * dtyp list *
    56         (string * dtyp list) list)) list -> int ->
    57           (int * (string * dtyp list *
    58             (string * dtyp list) list)) list list * int
    59 end;
    60 
    61 structure DatatypeAux : DATATYPE_AUX =
    62 struct
    63 
    64 val quiet_mode = ref false;
    65 fun message s = if !quiet_mode then () else writeln s;
    66 
    67 (* FIXME: move to library ? *)
    68 fun foldl1 f (x::xs) = foldl f (x, xs);
    69 
    70 fun get_thy name thy = find_first
    71   (equal name o Sign.name_of o Theory.sign_of) (Theory.ancestors_of thy);
    72 
    73 fun add_path flat_names s = if flat_names then I else Theory.add_path s;
    74 fun parent_path flat_names = if flat_names then I else Theory.parent_path;
    75 
    76 (* store theorems in theory *)
    77 
    78 fun store_thmss label tnames thmss thy =
    79   foldr (fn ((tname, thms), thy') => thy' |>
    80     Theory.add_path tname |>
    81     PureThy.add_thmss [((label, thms), [])] |>
    82     Theory.parent_path)
    83       (tnames ~~ thmss, thy);
    84 
    85 fun store_thms label tnames thms thy =
    86   foldr (fn ((tname, thm), thy') => thy' |>
    87     Theory.add_path tname |>
    88     PureThy.add_thms [((label, thm), [])] |>
    89     Theory.parent_path)
    90       (tnames ~~ thms, thy);
    91 
    92 (* split theorem thm_1 & ... & thm_n into n theorems *)
    93 
    94 fun split_conj_thm th =
    95   ((th RS conjunct1)::(split_conj_thm (th RS conjunct2))) handle _ => [th];
    96 
    97 val mk_conj = foldr1 (HOLogic.mk_binop "op &");
    98 val mk_disj = foldr1 (HOLogic.mk_binop "op |");
    99 
   100 fun dest_conj (Const ("op &", _) $ t $ t') = t::(dest_conj t')
   101   | dest_conj t = [t];
   102 
   103 (* instantiate induction rule *)
   104 
   105 fun indtac indrule i st =
   106   let
   107     val ts = dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
   108     val ts' = dest_conj (HOLogic.dest_Trueprop
   109       (Logic.strip_imp_concl (nth_elem (i - 1, prems_of st))));
   110     val getP = if can HOLogic.dest_imp (hd ts) then
   111       (apfst Some) o HOLogic.dest_imp else pair None;
   112     fun abstr (t1, t2) = (case t1 of
   113         None => let val [Free (s, T)] = add_term_frees (t2, [])
   114           in absfree (s, T, t2) end
   115       | Some (_ $ t' $ _) => Abs ("x", fastype_of t', abstract_over (t', t2)))
   116     val cert = cterm_of (Thm.sign_of_thm st);
   117     val Ps = map (cert o head_of o snd o getP) ts;
   118     val indrule' = cterm_instantiate (Ps ~~
   119       (map (cert o abstr o getP) ts')) indrule
   120   in
   121     rtac indrule' i st
   122   end;
   123 
   124 (* perform exhaustive case analysis on last parameter of subgoal i *)
   125 
   126 fun exh_tac exh_thm_of i state =
   127   let
   128     val sg = Thm.sign_of_thm state;
   129     val prem = nth_elem (i - 1, prems_of state);
   130     val params = Logic.strip_params prem;
   131     val (_, Type (tname, _)) = hd (rev params);
   132     val exhaustion = lift_rule (state, i) (exh_thm_of tname);
   133     val prem' = hd (prems_of exhaustion);
   134     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
   135     val exhaustion' = cterm_instantiate [(cterm_of sg (head_of lhs),
   136       cterm_of sg (foldr (fn ((_, T), t) => Abs ("z", T, t))
   137         (params, Bound 0)))] exhaustion
   138   in compose_tac (false, exhaustion', nprems_of exhaustion) i state
   139   end;
   140 
   141 (********************** Internal description of datatypes *********************)
   142 
   143 datatype dtyp =
   144     DtTFree of string
   145   | DtType of string * (dtyp list)
   146   | DtRec of int;
   147 
   148 (* information about datatypes *)
   149 
   150 type datatype_info =
   151   {index : int,
   152    descr : (int * (string * dtyp list *
   153      (string * dtyp list) list)) list,
   154    rec_names : string list,
   155    rec_rewrites : thm list,
   156    case_name : string,
   157    case_rewrites : thm list,
   158    induction : thm,
   159    exhaustion : thm,
   160    distinct : thm list,
   161    inject : thm list,
   162    nchotomy : thm,
   163    case_cong : thm};
   164 
   165 fun mk_Free s T i = Free (s ^ (string_of_int i), T);
   166 
   167 fun subst_DtTFree _ substs (T as (DtTFree name)) =
   168       (case assoc (substs, name) of
   169          None => T
   170        | Some U => U)
   171   | subst_DtTFree i substs (DtType (name, ts)) =
   172       DtType (name, map (subst_DtTFree i substs) ts)
   173   | subst_DtTFree i _ (DtRec j) = DtRec (i + j);
   174 
   175 fun dest_DtTFree (DtTFree a) = a;
   176 fun dest_DtRec (DtRec i) = i;
   177 
   178 fun is_rec_type (DtType (_, dts)) = exists is_rec_type dts
   179   | is_rec_type (DtRec _) = true
   180   | is_rec_type _ = false;
   181 
   182 fun dest_TFree (TFree (n, _)) = n;
   183 
   184 fun dtyp_of_typ _ (TFree (n, _)) = DtTFree n
   185   | dtyp_of_typ _ (TVar _) = error "Illegal schematic type variable(s)"
   186   | dtyp_of_typ new_dts (Type (tname, Ts)) =
   187       (case assoc (new_dts, tname) of
   188          None => DtType (tname, map (dtyp_of_typ new_dts) Ts)
   189        | Some vs => if map (try dest_TFree) Ts = map Some vs then
   190              DtRec (find_index (curry op = tname o fst) new_dts)
   191            else error ("Illegal occurence of recursive type " ^ tname));
   192 
   193 fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, the (assoc (sorts, a)))
   194   | typ_of_dtyp descr sorts (DtRec i) =
   195       let val (s, ds, _) = the (assoc (descr, i))
   196       in Type (s, map (typ_of_dtyp descr sorts) ds) end
   197   | typ_of_dtyp descr sorts (DtType (s, ds)) =
   198       Type (s, map (typ_of_dtyp descr sorts) ds);
   199 
   200 (* find all non-recursive types in datatype description *)
   201 
   202 fun get_nonrec_types descr sorts =
   203   let fun add (Ts, T as DtTFree _) = T ins Ts
   204         | add (Ts, T as DtType _) = T ins Ts
   205         | add (Ts, _) = Ts
   206   in map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
   207     foldl (fn (Ts', (_, cargs)) =>
   208       foldl add (Ts', cargs)) (Ts, constrs)) ([], descr))
   209   end;
   210 
   211 (* get all recursive types in datatype description *)
   212 
   213 fun get_rec_types descr sorts = map (fn (_ , (s, ds, _)) =>
   214   Type (s, map (typ_of_dtyp descr sorts) ds)) descr;
   215 
   216 (* nonemptiness check for datatypes *)
   217 
   218 fun check_nonempty descr =
   219   let
   220     val descr' = flat descr;
   221     fun is_nonempty_dt is i =
   222       let
   223         val (_, _, constrs) = the (assoc (descr', i));
   224         fun arg_nonempty (DtRec i) = if i mem is then false
   225               else is_nonempty_dt (i::is) i
   226           | arg_nonempty _ = true;
   227       in exists ((forall arg_nonempty) o snd) constrs
   228       end
   229   in assert_all (fn (i, _) => is_nonempty_dt [i] i) (hd descr)
   230     (fn (_, (s, _, _)) => "Nonemptiness check failed for datatype " ^ s)
   231   end;
   232 
   233 (* unfold a list of mutually recursive datatype specifications *)
   234 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   235 (* need to be unfolded                                         *)
   236 
   237 fun unfold_datatypes (dt_info : datatype_info Symtab.table) descr i =
   238   let
   239     fun get_dt_descr i tname dts =
   240       (case Symtab.lookup (dt_info, tname) of
   241          None => error (tname ^ " is not a datatype - can't use it in\
   242            \ indirect recursion")
   243        | (Some {index, descr, ...}) =>
   244            let val (_, vars, _) = the (assoc (descr, index));
   245                val subst = ((map dest_DtTFree vars) ~~ dts) handle _ =>
   246                  error ("Type constructor " ^ tname ^ " used with wrong\
   247                   \ number of arguments")
   248            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
   249              (tn, map (subst_DtTFree i subst) args,
   250               map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   251            end);
   252 
   253     (* unfold a single constructor argument *)
   254 
   255     fun unfold_arg ((i, Ts, descrs), T as (DtType (tname, dts))) =
   256           if is_rec_type T then
   257             let val (index, descr) = get_dt_descr i tname dts;
   258                 val (descr', i') = unfold_datatypes dt_info descr (i + length descr)
   259             in (i', Ts @ [DtRec index], descrs @ descr') end
   260           else (i, Ts @ [T], descrs)
   261       | unfold_arg ((i, Ts, descrs), T) = (i, Ts @ [T], descrs);
   262 
   263     (* unfold a constructor *)
   264 
   265     fun unfold_constr ((i, constrs, descrs), (cname, cargs)) =
   266       let val (i', cargs', descrs') = foldl unfold_arg ((i, [], descrs), cargs)
   267       in (i', constrs @ [(cname, cargs')], descrs') end;
   268 
   269     (* unfold a single datatype *)
   270 
   271     fun unfold_datatype ((i, dtypes, descrs), (j, (tname, tvars, constrs))) =
   272       let val (i', constrs', descrs') =
   273         foldl unfold_constr ((i, [], descrs), constrs)
   274       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs')
   275       end;
   276 
   277     val (i', descr', descrs) = foldl unfold_datatype ((i, [],[]), descr);
   278 
   279   in (descr' :: descrs, i') end;
   280 
   281 end;