src/HOL/BNF/Tools/bnf_wrap.ML
author blanchet
Fri Apr 26 12:09:51 2013 +0200 (2013-04-26)
changeset 51790 22517d04d20b
parent 51787 1267c28c7bdd
permissions -rw-r--r--
more intuitive syntax for equality-style discriminators of nullary constructors
     1 (*  Title:      HOL/BNF/Tools/bnf_wrap.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2012
     4 
     5 Wrapping existing datatypes.
     6 *)
     7 
     8 signature BNF_WRAP =
     9 sig
    10   val rep_compat_prefix: string
    11 
    12   val mk_half_pairss: 'a list * 'a list -> ('a * 'a) list list
    13   val join_halves: int -> 'a list list -> 'a list list -> 'a list * 'a list list list
    14 
    15   val mk_ctr: typ list -> term -> term
    16   val mk_disc_or_sel: typ list -> term -> term
    17 
    18   val name_of_ctr: term -> string
    19   val name_of_disc: term -> string
    20 
    21   val wrap_free_constructors: ({prems: thm list, context: Proof.context} -> tactic) list list ->
    22     (((bool * bool) * term list) * term) *
    23       (binding list * (binding list list * (binding * term) list list)) -> local_theory ->
    24     (term list * term list list * thm * thm list * thm list * thm list * thm list list * thm list *
    25      thm list list) * local_theory
    26   val parse_wrap_options: (bool * bool) parser
    27   val parse_bound_term: (binding * string) parser
    28 end;
    29 
    30 structure BNF_Wrap : BNF_WRAP =
    31 struct
    32 
    33 open BNF_Util
    34 open BNF_Wrap_Tactics
    35 
    36 val rep_compat_prefix = "new";
    37 
    38 val isN = "is_";
    39 val unN = "un_";
    40 fun mk_unN 1 1 suf = unN ^ suf
    41   | mk_unN _ l suf = unN ^ suf ^ string_of_int l;
    42 
    43 val caseN = "case";
    44 val case_congN = "case_cong";
    45 val case_convN = "case_conv";
    46 val collapseN = "collapse";
    47 val disc_excludeN = "disc_exclude";
    48 val disc_exhaustN = "disc_exhaust";
    49 val discsN = "discs";
    50 val distinctN = "distinct";
    51 val exhaustN = "exhaust";
    52 val expandN = "expand";
    53 val injectN = "inject";
    54 val nchotomyN = "nchotomy";
    55 val selsN = "sels";
    56 val splitN = "split";
    57 val splitsN = "splits";
    58 val split_asmN = "split_asm";
    59 val weak_case_cong_thmsN = "weak_case_cong";
    60 
    61 val induct_simp_attrs = @{attributes [induct_simp]};
    62 val cong_attrs = @{attributes [cong]};
    63 val iff_attrs = @{attributes [iff]};
    64 val safe_elim_attrs = @{attributes [elim!]};
    65 val simp_attrs = @{attributes [simp]};
    66 
    67 fun unflat_lookup eq ys zs = map (map (fn x => nth zs (find_index (curry eq x) ys)));
    68 
    69 fun mk_half_pairss' _ ([], []) = []
    70   | mk_half_pairss' indent (x :: xs, _ :: ys) =
    71     indent @ fold_rev (cons o single o pair x) ys (mk_half_pairss' ([] :: indent) (xs, ys));
    72 
    73 fun mk_half_pairss p = mk_half_pairss' [[]] p;
    74 
    75 fun join_halves n half_xss other_half_xss =
    76   let
    77     val xsss =
    78       map2 (map2 append) (Library.chop_groups n half_xss)
    79         (transpose (Library.chop_groups n other_half_xss))
    80     val xs = splice (flat half_xss) (flat other_half_xss);
    81   in (xs, xsss) end;
    82 
    83 fun mk_undefined T = Const (@{const_name undefined}, T);
    84 
    85 fun mk_ctr Ts t =
    86   let val Type (_, Ts0) = body_type (fastype_of t) in
    87     Term.subst_atomic_types (Ts0 ~~ Ts) t
    88   end;
    89 
    90 fun mk_disc_or_sel Ts t =
    91   Term.subst_atomic_types (snd (Term.dest_Type (domain_type (fastype_of t))) ~~ Ts) t;
    92 
    93 fun mk_case Ts T t =
    94   let val (Type (_, Ts0), body) = strip_type (fastype_of t) |>> List.last in
    95     Term.subst_atomic_types ((body, T) :: (Ts0 ~~ Ts)) t
    96   end;
    97 
    98 fun name_of_const what t =
    99   (case head_of t of
   100     Const (s, _) => s
   101   | Free (s, _) => s
   102   | _ => error ("Cannot extract name of " ^ what));
   103 
   104 val name_of_ctr = name_of_const "constructor";
   105 
   106 val notN = "not_";
   107 val eqN = "eq_";
   108 val neqN = "neq_";
   109 
   110 fun name_of_disc t =
   111   (case head_of t of
   112     Abs (_, _, @{const Not} $ (t' $ Bound 0)) =>
   113     Long_Name.map_base_name (prefix notN) (name_of_disc t')
   114   | Abs (_, _, Const (@{const_name HOL.eq}, _) $ Bound 0 $ t') =>
   115     Long_Name.map_base_name (prefix eqN) (name_of_disc t')
   116   | Abs (_, _, @{const Not} $ (Const (@{const_name HOL.eq}, _) $ Bound 0 $ t')) =>
   117     Long_Name.map_base_name (prefix neqN) (name_of_disc t')
   118   | t' => name_of_const "destructor" t');
   119 
   120 val base_name_of_ctr = Long_Name.base_name o name_of_ctr;
   121 
   122 fun eta_expand_arg xs f_xs = fold_rev Term.lambda xs f_xs;
   123 
   124 fun prepare_wrap_free_constructors prep_term ((((no_dests, rep_compat), raw_ctrs), raw_case),
   125     (raw_disc_bindings, (raw_sel_bindingss, raw_sel_defaultss))) no_defs_lthy =
   126   let
   127     (* TODO: sanity checks on arguments *)
   128 
   129     val n = length raw_ctrs;
   130     val ks = 1 upto n;
   131 
   132     val _ = if n > 0 then () else error "No constructors specified";
   133 
   134     val ctrs0 = map (prep_term no_defs_lthy) raw_ctrs;
   135     val case0 = prep_term no_defs_lthy raw_case;
   136     val sel_defaultss =
   137       pad_list [] n (map (map (apsnd (prep_term no_defs_lthy))) raw_sel_defaultss);
   138 
   139     val case0T = fastype_of case0;
   140     val Type (dataT_name, As0) =
   141       domain_type (snd (strip_typeN (length (binder_types case0T) - 1) case0T));
   142     val data_b = Binding.qualified_name dataT_name;
   143     val data_b_name = Binding.name_of data_b;
   144 
   145     fun qualify mandatory =
   146       Binding.qualify mandatory data_b_name o
   147       (rep_compat ? Binding.qualify false rep_compat_prefix);
   148 
   149     val (As, B) =
   150       no_defs_lthy
   151       |> mk_TFrees' (map Type.sort_of_atyp As0)
   152       ||> the_single o fst o mk_TFrees 1;
   153 
   154     val dataT = Type (dataT_name, As);
   155     val ctrs = map (mk_ctr As) ctrs0;
   156     val ctr_Tss = map (binder_types o fastype_of) ctrs;
   157 
   158     val ms = map length ctr_Tss;
   159 
   160     val raw_disc_bindings' = pad_list Binding.empty n raw_disc_bindings;
   161 
   162     fun can_definitely_rely_on_disc k =
   163       not (Binding.is_empty (nth raw_disc_bindings' (k - 1)));
   164     fun can_rely_on_disc k =
   165       can_definitely_rely_on_disc k orelse (k = 1 andalso not (can_definitely_rely_on_disc 2));
   166     fun should_omit_disc_binding k =
   167       n = 1 orelse (n = 2 andalso can_rely_on_disc (3 - k));
   168 
   169     fun is_disc_binding_valid b =
   170       not (Binding.is_empty b orelse Binding.eq_name (b, equal_binding));
   171 
   172     val standard_disc_binding = qualify false o Binding.name o prefix isN o base_name_of_ctr;
   173 
   174     val disc_bindings =
   175       raw_disc_bindings'
   176       |> map4 (fn k => fn m => fn ctr => fn disc =>
   177         qualify false
   178           (if Binding.is_empty disc then
   179              if should_omit_disc_binding k then disc else standard_disc_binding ctr
   180            else if Binding.eq_name (disc, equal_binding) then
   181              if m = 0 then disc
   182              else error "Cannot use \"=\" syntax for discriminating nonnullary constructor"
   183            else if Binding.eq_name (disc, standard_binding) then
   184              standard_disc_binding ctr
   185            else
   186              disc)) ks ms ctrs0;
   187 
   188     fun standard_sel_binding m l = Binding.name o mk_unN m l o base_name_of_ctr;
   189 
   190     val sel_bindingss =
   191       pad_list [] n raw_sel_bindingss
   192       |> map3 (fn ctr => fn m => map2 (fn l => fn sel =>
   193         qualify false
   194           (if Binding.is_empty sel orelse Binding.eq_name (sel, standard_binding) then
   195             standard_sel_binding m l ctr
   196           else
   197             sel)) (1 upto m) o pad_list Binding.empty m) ctrs0 ms;
   198 
   199     val casex = mk_case As B case0;
   200     val case_Ts = map (fn Ts => Ts ---> B) ctr_Tss;
   201 
   202     val (((((((xss, xss'), yss), fs), gs), [u', v']), (p, p')), names_lthy) = no_defs_lthy |>
   203       mk_Freess' "x" ctr_Tss
   204       ||>> mk_Freess "y" ctr_Tss
   205       ||>> mk_Frees "f" case_Ts
   206       ||>> mk_Frees "g" case_Ts
   207       ||>> (apfst (map (rpair dataT)) oo Variable.variant_fixes) [data_b_name, data_b_name ^ "'"]
   208       ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "P") HOLogic.boolT;
   209 
   210     val u = Free u';
   211     val v = Free v';
   212     val q = Free (fst p', mk_pred1T B);
   213 
   214     val xctrs = map2 (curry Term.list_comb) ctrs xss;
   215     val yctrs = map2 (curry Term.list_comb) ctrs yss;
   216 
   217     val xfs = map2 (curry Term.list_comb) fs xss;
   218     val xgs = map2 (curry Term.list_comb) gs xss;
   219 
   220     val fcase = Term.list_comb (casex, fs);
   221 
   222     val ufcase = fcase $ u;
   223     val vfcase = fcase $ v;
   224 
   225     (* TODO: Eta-expension is for compatibility with the old datatype package (but it also provides
   226        nicer names). Consider removing. *)
   227     val eta_fs = map2 eta_expand_arg xss xfs;
   228     val eta_gs = map2 eta_expand_arg xss xgs;
   229 
   230     val eta_fcase = Term.list_comb (casex, eta_fs);
   231     val eta_gcase = Term.list_comb (casex, eta_gs);
   232 
   233     val eta_ufcase = eta_fcase $ u;
   234     val eta_vgcase = eta_gcase $ v;
   235 
   236     fun mk_uu_eq () = HOLogic.mk_eq (u, u);
   237 
   238     val uv_eq = mk_Trueprop_eq (u, v);
   239 
   240     val exist_xs_u_eq_ctrs =
   241       map2 (fn xctr => fn xs => list_exists_free xs (HOLogic.mk_eq (u, xctr))) xctrs xss;
   242 
   243     val unique_disc_no_def = TrueI; (*arbitrary marker*)
   244     val alternate_disc_no_def = FalseE; (*arbitrary marker*)
   245 
   246     fun alternate_disc_lhs get_udisc k =
   247       HOLogic.mk_not
   248         (let val b = nth disc_bindings (k - 1) in
   249            if is_disc_binding_valid b then get_udisc b (k - 1) else nth exist_xs_u_eq_ctrs (k - 1)
   250          end);
   251 
   252     val (all_sels_distinct, discs, selss, udiscs, uselss, vdiscs, vselss, disc_defs, sel_defs,
   253          sel_defss, lthy') =
   254       if no_dests then
   255         (true, [], [], [], [], [], [], [], [], [], no_defs_lthy)
   256       else
   257         let
   258           fun disc_free b = Free (Binding.name_of b, mk_pred1T dataT);
   259 
   260           fun disc_spec b exist_xs_u_eq_ctr = mk_Trueprop_eq (disc_free b $ u, exist_xs_u_eq_ctr);
   261 
   262           fun alternate_disc k =
   263             Term.lambda u (alternate_disc_lhs (K o rapp u o disc_free) (3 - k));
   264 
   265           fun mk_sel_case_args b proto_sels T =
   266             map2 (fn Ts => fn k =>
   267               (case AList.lookup (op =) proto_sels k of
   268                 NONE =>
   269                 (case AList.lookup Binding.eq_name (rev (nth sel_defaultss (k - 1))) b of
   270                   NONE => fold_rev (Term.lambda o curry Free Name.uu) Ts (mk_undefined T)
   271                 | SOME t => t |> Type.constraint (Ts ---> T) |> Syntax.check_term no_defs_lthy)
   272               | SOME (xs, x) => fold_rev Term.lambda xs x)) ctr_Tss ks;
   273 
   274           fun sel_spec b proto_sels =
   275             let
   276               val _ =
   277                 (case duplicates (op =) (map fst proto_sels) of
   278                    k :: _ => error ("Duplicate selector name " ^ quote (Binding.name_of b) ^
   279                      " for constructor " ^
   280                      quote (Syntax.string_of_term no_defs_lthy (nth ctrs (k - 1))))
   281                  | [] => ())
   282               val T =
   283                 (case distinct (op =) (map (fastype_of o snd o snd) proto_sels) of
   284                   [T] => T
   285                 | T :: T' :: _ => error ("Inconsistent range type for selector " ^
   286                     quote (Binding.name_of b) ^ ": " ^ quote (Syntax.string_of_typ no_defs_lthy T) ^
   287                     " vs. " ^ quote (Syntax.string_of_typ no_defs_lthy T')));
   288             in
   289               mk_Trueprop_eq (Free (Binding.name_of b, dataT --> T) $ u,
   290                 Term.list_comb (mk_case As T case0, mk_sel_case_args b proto_sels T) $ u)
   291             end;
   292 
   293           val sel_bindings = flat sel_bindingss;
   294           val uniq_sel_bindings = distinct Binding.eq_name sel_bindings;
   295           val all_sels_distinct = (length uniq_sel_bindings = length sel_bindings);
   296 
   297           val sel_binding_index =
   298             if all_sels_distinct then 1 upto length sel_bindings
   299             else map (fn b => find_index (curry Binding.eq_name b) uniq_sel_bindings) sel_bindings;
   300 
   301           val proto_sels = flat (map3 (fn k => fn xs => map (fn x => (k, (xs, x)))) ks xss xss);
   302           val sel_infos =
   303             AList.group (op =) (sel_binding_index ~~ proto_sels)
   304             |> sort (int_ord o pairself fst)
   305             |> map snd |> curry (op ~~) uniq_sel_bindings;
   306           val sel_bindings = map fst sel_infos;
   307 
   308           fun unflat_selss xs = unflat_lookup Binding.eq_name sel_bindings xs sel_bindingss;
   309 
   310           val (((raw_discs, raw_disc_defs), (raw_sels, raw_sel_defs)), (lthy', lthy)) =
   311             no_defs_lthy
   312             |> apfst split_list o fold_map4 (fn k => fn m => fn exist_xs_u_eq_ctr => fn b =>
   313                 if Binding.is_empty b then
   314                   if n = 1 then pair (Term.lambda u (mk_uu_eq ()), unique_disc_no_def)
   315                   else pair (alternate_disc k, alternate_disc_no_def)
   316                 else if Binding.eq_name (b, equal_binding) then
   317                   pair (Term.lambda u exist_xs_u_eq_ctr, refl)
   318                 else
   319                   Specification.definition (SOME (b, NONE, NoSyn),
   320                     ((Thm.def_binding b, []), disc_spec b exist_xs_u_eq_ctr)) #>> apsnd snd)
   321               ks ms exist_xs_u_eq_ctrs disc_bindings
   322             ||>> apfst split_list o fold_map (fn (b, proto_sels) =>
   323               Specification.definition (SOME (b, NONE, NoSyn),
   324                 ((Thm.def_binding b, []), sel_spec b proto_sels)) #>> apsnd snd) sel_infos
   325             ||> `Local_Theory.restore;
   326 
   327           val phi = Proof_Context.export_morphism lthy lthy';
   328 
   329           val disc_defs = map (Morphism.thm phi) raw_disc_defs;
   330           val sel_defs = map (Morphism.thm phi) raw_sel_defs;
   331           val sel_defss = unflat_selss sel_defs;
   332 
   333           val discs0 = map (Morphism.term phi) raw_discs;
   334           val selss0 = unflat_selss (map (Morphism.term phi) raw_sels);
   335 
   336           val discs = map (mk_disc_or_sel As) discs0;
   337           val selss = map (map (mk_disc_or_sel As)) selss0;
   338 
   339           val udiscs = map (rapp u) discs;
   340           val uselss = map (map (rapp u)) selss;
   341 
   342           val vdiscs = map (rapp v) discs;
   343           val vselss = map (map (rapp v)) selss;
   344         in
   345           (all_sels_distinct, discs, selss, udiscs, uselss, vdiscs, vselss, disc_defs, sel_defs,
   346            sel_defss, lthy')
   347         end;
   348 
   349     fun mk_imp_p Qs = Logic.list_implies (Qs, HOLogic.mk_Trueprop p);
   350 
   351     val exhaust_goal =
   352       let fun mk_prem xctr xs = fold_rev Logic.all xs (mk_imp_p [mk_Trueprop_eq (u, xctr)]) in
   353         fold_rev Logic.all [p, u] (mk_imp_p (map2 mk_prem xctrs xss))
   354       end;
   355 
   356     val inject_goalss =
   357       let
   358         fun mk_goal _ _ [] [] = []
   359           | mk_goal xctr yctr xs ys =
   360             [fold_rev Logic.all (xs @ ys) (mk_Trueprop_eq (HOLogic.mk_eq (xctr, yctr),
   361               Library.foldr1 HOLogic.mk_conj (map2 (curry HOLogic.mk_eq) xs ys)))];
   362       in
   363         map4 mk_goal xctrs yctrs xss yss
   364       end;
   365 
   366     val half_distinct_goalss =
   367       let
   368         fun mk_goal ((xs, xc), (xs', xc')) =
   369           fold_rev Logic.all (xs @ xs')
   370             (HOLogic.mk_Trueprop (HOLogic.mk_not (HOLogic.mk_eq (xc, xc'))));
   371       in
   372         map (map mk_goal) (mk_half_pairss (`I (xss ~~ xctrs)))
   373       end;
   374 
   375     val cases_goal =
   376       map3 (fn xs => fn xctr => fn xf =>
   377         fold_rev Logic.all (fs @ xs) (mk_Trueprop_eq (fcase $ xctr, xf))) xss xctrs xfs;
   378 
   379     val goalss = [exhaust_goal] :: inject_goalss @ half_distinct_goalss @ [cases_goal];
   380 
   381     fun after_qed thmss lthy =
   382       let
   383         val ([exhaust_thm], (inject_thmss, (half_distinct_thmss, [case_thms]))) =
   384           (hd thmss, apsnd (chop (n * n)) (chop n (tl thmss)));
   385 
   386         val inject_thms = flat inject_thmss;
   387 
   388         val Tinst = map (pairself (certifyT lthy)) (map Logic.varifyT_global As ~~ As);
   389 
   390         fun inst_thm t thm =
   391           Drule.instantiate' [] [SOME (certify lthy t)]
   392             (Thm.instantiate (Tinst, []) (Drule.zero_var_indexes thm));
   393 
   394         val uexhaust_thm = inst_thm u exhaust_thm;
   395 
   396         val exhaust_cases = map base_name_of_ctr ctrs;
   397 
   398         val other_half_distinct_thmss = map (map (fn thm => thm RS not_sym)) half_distinct_thmss;
   399 
   400         val (distinct_thms, (distinct_thmsss', distinct_thmsss)) =
   401           join_halves n half_distinct_thmss other_half_distinct_thmss ||> `transpose;
   402 
   403         val nchotomy_thm =
   404           let
   405             val goal =
   406               HOLogic.mk_Trueprop (HOLogic.mk_all (fst u', snd u',
   407                 Library.foldr1 HOLogic.mk_disj exist_xs_u_eq_ctrs));
   408           in
   409             Goal.prove_sorry lthy [] [] goal (fn _ => mk_nchotomy_tac n exhaust_thm)
   410             |> Thm.close_derivation
   411           end;
   412 
   413         val (all_sel_thms, sel_thmss, disc_thmss, disc_thms, discI_thms, disc_exclude_thms,
   414              disc_exhaust_thms, collapse_thms, expand_thms, case_conv_thms) =
   415           if no_dests then
   416             ([], [], [], [], [], [], [], [], [], [])
   417           else
   418             let
   419               fun make_sel_thm xs' case_thm sel_def =
   420                 zero_var_indexes (Drule.gen_all (Drule.rename_bvars' (map (SOME o fst) xs')
   421                     (Drule.forall_intr_vars (case_thm RS (sel_def RS trans)))));
   422 
   423               fun has_undefined_rhs thm =
   424                 (case snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of thm))) of
   425                   Const (@{const_name undefined}, _) => true
   426                 | _ => false);
   427 
   428               val sel_thmss = map3 (map oo make_sel_thm) xss' case_thms sel_defss;
   429 
   430               val all_sel_thms =
   431                 (if all_sels_distinct andalso forall null sel_defaultss then
   432                    flat sel_thmss
   433                  else
   434                    map_product (fn s => fn (xs', c) => make_sel_thm xs' c s) sel_defs
   435                      (xss' ~~ case_thms))
   436                 |> filter_out has_undefined_rhs;
   437 
   438               fun mk_unique_disc_def () =
   439                 let
   440                   val m = the_single ms;
   441                   val goal = mk_Trueprop_eq (mk_uu_eq (), the_single exist_xs_u_eq_ctrs);
   442                 in
   443                   Goal.prove_sorry lthy [] [] goal (fn _ => mk_unique_disc_def_tac m uexhaust_thm)
   444                   |> Thm.close_derivation
   445                   |> singleton (Proof_Context.export names_lthy lthy)
   446                 end;
   447 
   448               fun mk_alternate_disc_def k =
   449                 let
   450                   val goal =
   451                     mk_Trueprop_eq (alternate_disc_lhs (K (nth udiscs)) (3 - k),
   452                       nth exist_xs_u_eq_ctrs (k - 1));
   453                 in
   454                   Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   455                     mk_alternate_disc_def_tac ctxt k (nth disc_defs (2 - k))
   456                       (nth distinct_thms (2 - k)) uexhaust_thm)
   457                   |> Thm.close_derivation
   458                   |> singleton (Proof_Context.export names_lthy lthy)
   459                 end;
   460 
   461               val has_alternate_disc_def =
   462                 exists (fn def => Thm.eq_thm_prop (def, alternate_disc_no_def)) disc_defs;
   463 
   464               val disc_defs' =
   465                 map2 (fn k => fn def =>
   466                   if Thm.eq_thm_prop (def, unique_disc_no_def) then mk_unique_disc_def ()
   467                   else if Thm.eq_thm_prop (def, alternate_disc_no_def) then mk_alternate_disc_def k
   468                   else def) ks disc_defs;
   469 
   470               val discD_thms = map (fn def => def RS iffD1) disc_defs';
   471               val discI_thms =
   472                 map2 (fn m => fn def => funpow m (fn thm => exI RS thm) (def RS iffD2)) ms
   473                   disc_defs';
   474               val not_discI_thms =
   475                 map2 (fn m => fn def => funpow m (fn thm => allI RS thm)
   476                     (unfold_thms lthy @{thms not_ex} (def RS @{thm ssubst[of _ _ Not]})))
   477                   ms disc_defs';
   478 
   479               val (disc_thmss', disc_thmss) =
   480                 let
   481                   fun mk_thm discI _ [] = refl RS discI
   482                     | mk_thm _ not_discI [distinct] = distinct RS not_discI;
   483                   fun mk_thms discI not_discI distinctss = map (mk_thm discI not_discI) distinctss;
   484                 in
   485                   map3 mk_thms discI_thms not_discI_thms distinct_thmsss' |> `transpose
   486                 end;
   487 
   488               val disc_thms = flat (map2 (fn b => if is_disc_binding_valid b then I else K [])
   489                 disc_bindings disc_thmss);
   490 
   491               val (disc_exclude_thms, (disc_exclude_thmsss', disc_exclude_thmsss)) =
   492                 let
   493                   fun mk_goal [] = []
   494                     | mk_goal [((_, udisc), (_, udisc'))] =
   495                       [Logic.all u (Logic.mk_implies (HOLogic.mk_Trueprop udisc,
   496                          HOLogic.mk_Trueprop (HOLogic.mk_not udisc')))];
   497 
   498                   fun prove tac goal =
   499                     Goal.prove_sorry lthy [] [] goal (K tac)
   500                     |> Thm.close_derivation;
   501 
   502                   val half_pairss = mk_half_pairss (`I (ms ~~ discD_thms ~~ udiscs));
   503 
   504                   val half_goalss = map mk_goal half_pairss;
   505                   val half_thmss =
   506                     map3 (fn [] => K (K []) | [goal] => fn [(((m, discD), _), _)] =>
   507                         fn disc_thm => [prove (mk_half_disc_exclude_tac m discD disc_thm) goal])
   508                       half_goalss half_pairss (flat disc_thmss');
   509 
   510                   val other_half_goalss = map (mk_goal o map swap) half_pairss;
   511                   val other_half_thmss =
   512                     map2 (map2 (prove o mk_other_half_disc_exclude_tac)) half_thmss
   513                       other_half_goalss;
   514                 in
   515                   join_halves n half_thmss other_half_thmss ||> `transpose
   516                   |>> has_alternate_disc_def ? K []
   517                 end;
   518 
   519               val disc_exhaust_thm =
   520                 let
   521                   fun mk_prem udisc = mk_imp_p [HOLogic.mk_Trueprop udisc];
   522                   val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem udiscs));
   523                 in
   524                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   525                     mk_disc_exhaust_tac n exhaust_thm discI_thms)
   526                   |> Thm.close_derivation
   527                 end;
   528 
   529               val (collapse_thms, collapse_thm_opts) =
   530                 let
   531                   fun mk_goal ctr udisc usels =
   532                     let
   533                       val prem = HOLogic.mk_Trueprop udisc;
   534                       val concl =
   535                         mk_Trueprop_eq ((null usels ? swap) (Term.list_comb (ctr, usels), u));
   536                     in
   537                       if prem aconv concl then NONE
   538                       else SOME (Logic.all u (Logic.mk_implies (prem, concl)))
   539                     end;
   540                   val goals = map3 mk_goal ctrs udiscs uselss;
   541                 in
   542                   map4 (fn m => fn discD => fn sel_thms => Option.map (fn goal =>
   543                     Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   544                       mk_collapse_tac ctxt m discD sel_thms)
   545                     |> Thm.close_derivation
   546                     |> perhaps (try (fn thm => refl RS thm)))) ms discD_thms sel_thmss goals
   547                   |> `(map_filter I)
   548                 end;
   549 
   550               val expand_thms =
   551                 let
   552                   fun mk_prems k udisc usels vdisc vsels =
   553                     (if k = n then [] else [mk_Trueprop_eq (udisc, vdisc)]) @
   554                     (if null usels then
   555                        []
   556                      else
   557                        [Logic.list_implies
   558                           (if n = 1 then [] else map HOLogic.mk_Trueprop [udisc, vdisc],
   559                              HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
   560                                (map2 (curry HOLogic.mk_eq) usels vsels)))]);
   561 
   562                   val goal =
   563                     Library.foldr Logic.list_implies
   564                       (map5 mk_prems ks udiscs uselss vdiscs vselss, uv_eq);
   565                   val uncollapse_thms =
   566                     map2 (fn NONE => K asm_rl | SOME thm => fn [] => thm | _ => thm RS sym)
   567                       collapse_thm_opts uselss;
   568                 in
   569                   [Goal.prove_sorry lthy [] [] goal (fn _ =>
   570                      mk_expand_tac lthy n ms (inst_thm u disc_exhaust_thm)
   571                        (inst_thm v disc_exhaust_thm) uncollapse_thms disc_exclude_thmsss
   572                        disc_exclude_thmsss')]
   573                   |> map Thm.close_derivation
   574                   |> Proof_Context.export names_lthy lthy
   575                 end;
   576 
   577               val case_conv_thms =
   578                 let
   579                   fun mk_body f usels = Term.list_comb (f, usels);
   580                   val goal = mk_Trueprop_eq (ufcase, mk_IfN B udiscs (map2 mk_body fs uselss));
   581                 in
   582                   [Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   583                      mk_case_conv_tac ctxt n uexhaust_thm case_thms disc_thmss' sel_thmss)]
   584                   |> map Thm.close_derivation
   585                   |> Proof_Context.export names_lthy lthy
   586                 end;
   587             in
   588               (all_sel_thms, sel_thmss, disc_thmss, disc_thms, discI_thms, disc_exclude_thms,
   589                [disc_exhaust_thm], collapse_thms, expand_thms, case_conv_thms)
   590             end;
   591 
   592         val (case_cong_thm, weak_case_cong_thm) =
   593           let
   594             fun mk_prem xctr xs xf xg =
   595               fold_rev Logic.all xs (Logic.mk_implies (mk_Trueprop_eq (v, xctr),
   596                 mk_Trueprop_eq (xf, xg)));
   597 
   598             val goal =
   599               Logic.list_implies (uv_eq :: map4 mk_prem xctrs xss xfs xgs,
   600                  mk_Trueprop_eq (eta_ufcase, eta_vgcase));
   601             val weak_goal = Logic.mk_implies (uv_eq, mk_Trueprop_eq (ufcase, vfcase));
   602           in
   603             (Goal.prove_sorry lthy [] [] goal (fn _ => mk_case_cong_tac lthy uexhaust_thm case_thms),
   604              Goal.prove_sorry lthy [] [] weak_goal (K (etac arg_cong 1)))
   605             |> pairself (Thm.close_derivation #> singleton (Proof_Context.export names_lthy lthy))
   606           end;
   607 
   608         val (split_thm, split_asm_thm) =
   609           let
   610             fun mk_conjunct xctr xs f_xs =
   611               list_all_free xs (HOLogic.mk_imp (HOLogic.mk_eq (u, xctr), q $ f_xs));
   612             fun mk_disjunct xctr xs f_xs =
   613               list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr),
   614                 HOLogic.mk_not (q $ f_xs)));
   615 
   616             val lhs = q $ ufcase;
   617 
   618             val goal =
   619               mk_Trueprop_eq (lhs, Library.foldr1 HOLogic.mk_conj (map3 mk_conjunct xctrs xss xfs));
   620             val asm_goal =
   621               mk_Trueprop_eq (lhs, HOLogic.mk_not (Library.foldr1 HOLogic.mk_disj
   622                 (map3 mk_disjunct xctrs xss xfs)));
   623 
   624             val split_thm =
   625               Goal.prove_sorry lthy [] [] goal
   626                 (fn _ => mk_split_tac lthy uexhaust_thm case_thms inject_thmss distinct_thmsss)
   627               |> Thm.close_derivation
   628               |> singleton (Proof_Context.export names_lthy lthy);
   629             val split_asm_thm =
   630               Goal.prove_sorry lthy [] [] asm_goal (fn {context = ctxt, ...} =>
   631                 mk_split_asm_tac ctxt split_thm)
   632               |> Thm.close_derivation
   633               |> singleton (Proof_Context.export names_lthy lthy);
   634           in
   635             (split_thm, split_asm_thm)
   636           end;
   637 
   638         val exhaust_case_names_attr = Attrib.internal (K (Rule_Cases.case_names exhaust_cases));
   639         val cases_type_attr = Attrib.internal (K (Induct.cases_type dataT_name));
   640 
   641         val notes =
   642           [(caseN, case_thms, simp_attrs),
   643            (case_congN, [case_cong_thm], []),
   644            (case_convN, case_conv_thms, []),
   645            (collapseN, collapse_thms, simp_attrs),
   646            (discsN, disc_thms, simp_attrs),
   647            (disc_excludeN, disc_exclude_thms, []),
   648            (disc_exhaustN, disc_exhaust_thms, [exhaust_case_names_attr]),
   649            (distinctN, distinct_thms, simp_attrs @ induct_simp_attrs),
   650            (exhaustN, [exhaust_thm], [exhaust_case_names_attr, cases_type_attr]),
   651            (expandN, expand_thms, []),
   652            (injectN, inject_thms, iff_attrs @ induct_simp_attrs),
   653            (nchotomyN, [nchotomy_thm], []),
   654            (selsN, all_sel_thms, simp_attrs),
   655            (splitN, [split_thm], []),
   656            (split_asmN, [split_asm_thm], []),
   657            (splitsN, [split_thm, split_asm_thm], []),
   658            (weak_case_cong_thmsN, [weak_case_cong_thm], cong_attrs)]
   659           |> filter_out (null o #2)
   660           |> map (fn (thmN, thms, attrs) =>
   661             ((qualify true (Binding.name thmN), attrs), [(thms, [])]));
   662 
   663         val notes' =
   664           [(map (fn th => th RS notE) distinct_thms, safe_elim_attrs)]
   665           |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
   666       in
   667         ((discs, selss, exhaust_thm, inject_thms, distinct_thms, case_thms, disc_thmss, discI_thms,
   668           sel_thmss),
   669           lthy
   670           |> not rep_compat ?
   671              (Local_Theory.declaration {syntax = false, pervasive = true}
   672                (fn phi => Case_Translation.register
   673                  (Morphism.term phi casex) (map (Morphism.term phi) ctrs)))
   674           |> Local_Theory.notes (notes' @ notes) |> snd)
   675       end;
   676   in
   677     (goalss, after_qed, lthy')
   678   end;
   679 
   680 fun wrap_free_constructors tacss = (fn (goalss, after_qed, lthy) =>
   681   map2 (map2 (Thm.close_derivation oo Goal.prove_sorry lthy [] [])) goalss tacss
   682   |> (fn thms => after_qed thms lthy)) oo prepare_wrap_free_constructors (K I);
   683 
   684 val wrap_free_constructors_cmd = (fn (goalss, after_qed, lthy) =>
   685   Proof.theorem NONE (snd oo after_qed) (map (map (rpair [])) goalss) lthy) oo
   686   prepare_wrap_free_constructors Syntax.read_term;
   687 
   688 fun parse_bracket_list parser = @{keyword "["} |-- Parse.list parser --|  @{keyword "]"};
   689 
   690 val parse_bindings = parse_bracket_list parse_binding;
   691 val parse_bindingss = parse_bracket_list parse_bindings;
   692 
   693 val parse_bound_term = (parse_binding --| @{keyword ":"}) -- Parse.term;
   694 val parse_bound_terms = parse_bracket_list parse_bound_term;
   695 val parse_bound_termss = parse_bracket_list parse_bound_terms;
   696 
   697 val parse_wrap_options =
   698   Scan.optional (@{keyword "("} |-- Parse.list1 ((@{keyword "no_dests"} >> K (true, false)) ||
   699       (@{keyword "rep_compat"} >> K (false, true))) --| @{keyword ")"}
   700     >> (pairself (exists I) o split_list)) (false, false);
   701 
   702 val _ =
   703   Outer_Syntax.local_theory_to_proof @{command_spec "wrap_free_constructors"}
   704     "wrap an existing (co)datatype's constructors"
   705     ((parse_wrap_options -- (@{keyword "["} |-- Parse.list Parse.term --| @{keyword "]"}) --
   706       Parse.term -- Scan.optional (parse_bindings -- Scan.optional (parse_bindingss --
   707         Scan.optional parse_bound_termss []) ([], [])) ([], ([], [])))
   708      >> wrap_free_constructors_cmd);
   709 
   710 end;