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