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