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