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