src/HOL/Codatatype/Tools/bnf_fp_sugar.ML
author blanchet
Wed Sep 05 16:17:53 2012 +0200 (2012-09-05)
changeset 49167 68623861e0f2
parent 49165 c6ccaf6df93c
child 49169 937a0fadddfb
permissions -rw-r--r--
print timing information
     1 (*  Title:      HOL/Codatatype/Tools/bnf_fp_sugar.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2012
     4 
     5 Sugar for constructing LFPs and GFPs.
     6 *)
     7 
     8 signature BNF_FP_SUGAR =
     9 sig
    10 end;
    11 
    12 structure BNF_FP_Sugar : BNF_FP_SUGAR =
    13 struct
    14 
    15 open BNF_Util
    16 open BNF_Wrap
    17 open BNF_FP_Util
    18 open BNF_LFP
    19 open BNF_GFP
    20 open BNF_FP_Sugar_Tactics
    21 
    22 val caseN = "case";
    23 
    24 fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
    25 
    26 fun merge_type_arg_constrained ctxt (T, c) (T', c') =
    27   if T = T' then
    28     (case (c, c') of
    29       (_, NONE) => (T, c)
    30     | (NONE, _) => (T, c')
    31     | _ =>
    32       if c = c' then
    33         (T, c)
    34       else
    35         error ("Inconsistent sort constraints for type variable " ^
    36           quote (Syntax.string_of_typ ctxt T)))
    37   else
    38     cannot_merge_types ();
    39 
    40 fun merge_type_args_constrained ctxt (cAs, cAs') =
    41   if length cAs = length cAs' then map2 (merge_type_arg_constrained ctxt) cAs cAs'
    42   else cannot_merge_types ();
    43 
    44 fun type_args_constrained_of (((cAs, _), _), _) = cAs;
    45 val type_args_of = map fst o type_args_constrained_of;
    46 fun type_binder_of (((_, b), _), _) = b;
    47 fun mixfix_of_typ ((_, mx), _) = mx;
    48 fun ctr_specs_of (_, ctr_specs) = ctr_specs;
    49 
    50 fun disc_of (((disc, _), _), _) = disc;
    51 fun ctr_of (((_, ctr), _), _) = ctr;
    52 fun args_of ((_, args), _) = args;
    53 fun mixfix_of_ctr (_, mx) = mx;
    54 
    55 val uncurry_fs =
    56   map2 (fn f => fn xs => HOLogic.tupled_lambda (HOLogic.mk_tuple xs) (Term.list_comb (f, xs)));
    57 
    58 fun prepare_data prepare_typ gfp specs fake_lthy lthy =
    59   let
    60     val constrained_As =
    61       map (map (apfst (prepare_typ fake_lthy)) o type_args_constrained_of) specs
    62       |> Library.foldr1 (merge_type_args_constrained lthy);
    63     val As = map fst constrained_As;
    64     val As' = map dest_TFree As;
    65 
    66     val _ = (case duplicates (op =) As of [] => ()
    67       | A :: _ => error ("Duplicate type parameter " ^ quote (Syntax.string_of_typ lthy A)));
    68 
    69     (* TODO: use sort constraints on type args *)
    70     (* TODO: use mixfix *)
    71 
    72     val N = length specs;
    73 
    74     fun mk_T b =
    75       Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
    76         As);
    77 
    78     val bs = map type_binder_of specs;
    79     val Ts = map mk_T bs;
    80 
    81     val mixfixes = map mixfix_of_typ specs;
    82 
    83     val _ = (case duplicates Binding.eq_name bs of [] => ()
    84       | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
    85 
    86     val ctr_specss = map ctr_specs_of specs;
    87 
    88     val disc_binderss = map (map disc_of) ctr_specss;
    89     val ctr_binderss = map (map ctr_of) ctr_specss;
    90     val ctr_argsss = map (map args_of) ctr_specss;
    91     val ctr_mixfixess = map (map mixfix_of_ctr) ctr_specss;
    92 
    93     val sel_bindersss = map (map (map fst)) ctr_argsss;
    94     val ctr_Tsss = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
    95 
    96     val rhs_As' = fold (fold (fold Term.add_tfreesT)) ctr_Tsss [];
    97     val _ = (case subtract (op =) As' rhs_As' of
    98         [] => ()
    99       | A' :: _ => error ("Extra type variables on rhs: " ^
   100           quote (Syntax.string_of_typ lthy (TFree A'))));
   101 
   102     val (Bs, C) =
   103       lthy
   104       |> fold (fold (fn s => Variable.declare_typ (TFree (s, dummyS))) o type_args_of) specs
   105       |> mk_TFrees N
   106       ||> the_single o fst o mk_TFrees 1;
   107 
   108     fun is_same_rec (T as Type (s, Us)) (Type (s', Us')) =
   109         s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
   110           quote (Syntax.string_of_typ fake_lthy T)))
   111       | is_same_rec _ _ = false
   112 
   113     fun freeze_rec (T as Type (s, Us)) =
   114         (case find_index (is_same_rec T) Ts of
   115           ~1 => Type (s, map freeze_rec Us)
   116         | i => nth Bs i)
   117       | freeze_rec T = T;
   118 
   119     val ctr_TsssBs = map (map (map freeze_rec)) ctr_Tsss;
   120     val sum_prod_TsBs = map (mk_sumTN o map HOLogic.mk_tupleT) ctr_TsssBs;
   121 
   122     val eqs = map dest_TFree Bs ~~ sum_prod_TsBs;
   123 
   124     val ((raw_unfs, raw_flds, unf_flds, fld_unfs, fld_injects), lthy') =
   125       fp_bnf (if gfp then bnf_gfp else bnf_lfp) bs As' eqs lthy;
   126 
   127     val timer = time (Timer.startRealTimer ());
   128 
   129     fun mk_unf_or_fld get_foldedT Ts t =
   130       let val Type (_, Ts0) = get_foldedT (fastype_of t) in
   131         Term.subst_atomic_types (Ts0 ~~ Ts) t
   132       end;
   133 
   134     val mk_unf = mk_unf_or_fld domain_type;
   135     val mk_fld = mk_unf_or_fld range_type;
   136 
   137     val unfs = map (mk_unf As) raw_unfs;
   138     val flds = map (mk_fld As) raw_flds;
   139 
   140     fun pour_sugar_on_type ((((((((((b, T), fld), unf), fld_unf), unf_fld), fld_inject),
   141         ctr_binders), ctr_Tss), disc_binders), sel_binderss) no_defs_lthy =
   142       let
   143         val n = length ctr_binders;
   144         val ks = 1 upto n;
   145         val ms = map length ctr_Tss;
   146 
   147         val unf_T = domain_type (fastype_of fld);
   148         val prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
   149         val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
   150 
   151         val ((((fs, u), v), xss), _) =
   152           lthy
   153           |> mk_Frees "f" case_Ts
   154           ||>> yield_singleton (mk_Frees "u") unf_T
   155           ||>> yield_singleton (mk_Frees "v") T
   156           ||>> mk_Freess "x" ctr_Tss;
   157 
   158         val ctr_rhss =
   159           map2 (fn k => fn xs =>
   160             fold_rev Term.lambda xs (fld $ mk_InN prod_Ts (HOLogic.mk_tuple xs) k)) ks xss;
   161 
   162         val case_binder = Binding.suffix_name ("_" ^ caseN) b;
   163 
   164         val case_rhs =
   165           fold_rev Term.lambda (fs @ [v]) (mk_sum_caseN (uncurry_fs fs xss) $ (unf $ v));
   166 
   167         val (((raw_ctrs, raw_ctr_defs), (raw_case, raw_case_def)), (lthy', lthy)) = no_defs_lthy
   168           |> apfst split_list o fold_map2 (fn b => fn rhs =>
   169                Local_Theory.define ((b, NoSyn), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
   170              ctr_binders ctr_rhss
   171           ||>> (Local_Theory.define ((case_binder, NoSyn), ((Thm.def_binding case_binder, []),
   172              case_rhs)) #>> apsnd snd)
   173           ||> `Local_Theory.restore;
   174 
   175         (*transforms defined frees into consts (and more)*)
   176         val phi = Proof_Context.export_morphism lthy lthy';
   177 
   178         val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
   179         val case_def = Morphism.thm phi raw_case_def;
   180 
   181         val ctrs = map (Morphism.term phi) raw_ctrs;
   182         val casex = Morphism.term phi raw_case;
   183 
   184         fun exhaust_tac {context = ctxt, ...} =
   185           let
   186             val fld_iff_unf_thm =
   187               let
   188                 val goal =
   189                   fold_rev Logic.all [u, v]
   190                     (mk_Trueprop_eq (HOLogic.mk_eq (v, fld $ u), HOLogic.mk_eq (unf $ v, u)));
   191               in
   192                 Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
   193                   mk_fld_iff_unf_tac ctxt (map (SOME o certifyT lthy) [unf_T, T]) (certify lthy fld)
   194                     (certify lthy unf) fld_unf unf_fld)
   195                 |> Thm.close_derivation
   196                 |> Morphism.thm phi
   197               end;
   198 
   199             val sumEN_thm' =
   200               Local_Defs.unfold lthy @{thms all_unit_eq}
   201                 (Drule.instantiate' (map (SOME o certifyT lthy) prod_Ts) [] (mk_sumEN n))
   202               |> Morphism.thm phi;
   203           in
   204             mk_exhaust_tac ctxt n ctr_defs fld_iff_unf_thm sumEN_thm'
   205           end;
   206 
   207         val inject_tacss =
   208           map2 (fn 0 => K []
   209                  | _ => fn ctr_def => [fn {context = ctxt, ...} =>
   210                      mk_inject_tac ctxt ctr_def fld_inject])
   211             ms ctr_defs;
   212 
   213         val half_distinct_tacss =
   214           map (map (fn (def, def') => fn {context = ctxt, ...} =>
   215             mk_half_distinct_tac ctxt fld_inject [def, def'])) (mk_half_pairss ctr_defs);
   216 
   217         val case_tacs =
   218           map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
   219             mk_case_tac ctxt n k m case_def ctr_def unf_fld) ks ms ctr_defs;
   220 
   221         val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
   222 
   223         fun sugar_lfp lthy =
   224           let
   225 (*###
   226             val fld_iter = @{term True}; (*###*)
   227 
   228             val iter_Tss = map (fn Ts => Ts) (*###*) ctr_Tss;
   229             val iter_Ts = map (fn Ts => Ts ---> C) iter_Tss;
   230 
   231             val iter_fs = map2 (fn Free (s, _) => fn T => Free (s, T)) fs iter_Ts
   232 
   233             val iter_rhs =
   234               fold_rev Term.lambda fs (fld_iter $ mk_sum_caseN (uncurry_fs fs xss) $ (unf $ v));
   235 
   236 
   237             val uncurried_fs =
   238               map2 (fn f => fn xs =>
   239                 HOLogic.tupled_lambda (HOLogic.mk_tuple xs) (Term.list_comb (f, xs))) fs xss;
   240 *)
   241           in
   242             lthy
   243           end;
   244 
   245         fun sugar_gfp lthy = lthy;
   246       in
   247         wrap_data tacss ((ctrs, casex), (disc_binders, sel_binderss)) lthy'
   248         |> (if gfp then sugar_gfp else sugar_lfp)
   249       end;
   250 
   251     val lthy'' =
   252       fold pour_sugar_on_type (bs ~~ Ts ~~ flds ~~ unfs ~~ fld_unfs ~~ unf_flds ~~ fld_injects ~~
   253         ctr_binderss ~~ ctr_Tsss ~~ disc_binderss ~~ sel_bindersss) lthy'
   254 
   255     val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
   256       (if gfp then "co" else "") ^ "datatype"));
   257   in
   258     (timer; lthy'')
   259   end;
   260 
   261 fun data_cmd info specs lthy =
   262   let
   263     val fake_lthy =
   264       Proof_Context.theory_of lthy
   265       |> Theory.copy
   266       |> Sign.add_types_global (map (fn spec =>
   267         (type_binder_of spec, length (type_args_constrained_of spec), mixfix_of_typ spec)) specs)
   268       |> Proof_Context.init_global
   269   in
   270     prepare_data Syntax.read_typ info specs fake_lthy lthy
   271   end;
   272 
   273 val parse_opt_binding_colon = Scan.optional (Parse.binding --| Parse.$$$ ":") no_binder
   274 
   275 val parse_ctr_arg =
   276   Parse.$$$ "(" |-- parse_opt_binding_colon -- Parse.typ --| Parse.$$$ ")" ||
   277   (Parse.typ >> pair no_binder);
   278 
   279 val parse_single_spec =
   280   Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
   281   (@{keyword "="} |-- Parse.enum1 "|" (parse_opt_binding_colon -- Parse.binding --
   282     Scan.repeat parse_ctr_arg -- Parse.opt_mixfix));
   283 
   284 val _ =
   285   Outer_Syntax.local_theory @{command_spec "data"} "define BNF-based inductive datatypes"
   286     (Parse.and_list1 parse_single_spec >> data_cmd false);
   287 
   288 val _ =
   289   Outer_Syntax.local_theory @{command_spec "codata"} "define BNF-based coinductive datatypes"
   290     (Parse.and_list1 parse_single_spec >> data_cmd true);
   291 
   292 end;