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