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