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