src/HOL/Tools/enriched_type.ML
author huffman
Fri Mar 30 12:32:35 2012 +0200 (2012-03-30)
changeset 47220 52426c62b5d0
parent 46961 5c6955f487e5
child 51551 88d1d19fb74f
permissions -rw-r--r--
replace lemmas eval_nat_numeral with a simpler reformulation
haftmann@41505
     1
(*  Title:      HOL/Tools/enriched_type.ML
haftmann@40582
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@40582
     3
haftmann@40968
     4
Functorial structure of types.
haftmann@40582
     5
*)
haftmann@40582
     6
haftmann@41505
     7
signature ENRICHED_TYPE =
haftmann@40582
     8
sig
haftmann@41388
     9
  val find_atomic: Proof.context -> typ -> (typ * (bool * bool)) list
haftmann@41388
    10
  val construct_mapper: Proof.context -> (string * bool -> term)
haftmann@40582
    11
    -> bool -> typ -> typ -> term
haftmann@41505
    12
  val enriched_type: string option -> term -> local_theory -> Proof.state
haftmann@40582
    13
  type entry
haftmann@41390
    14
  val entries: Proof.context -> entry list Symtab.table
haftmann@40582
    15
end;
haftmann@40582
    16
haftmann@41505
    17
structure Enriched_Type : ENRICHED_TYPE =
haftmann@40582
    18
struct
haftmann@40582
    19
haftmann@41395
    20
(* bookkeeping *)
haftmann@41395
    21
haftmann@41371
    22
val compN = "comp";
haftmann@41371
    23
val idN = "id";
haftmann@40611
    24
val compositionalityN = "compositionality";
haftmann@40594
    25
val identityN = "identity";
haftmann@40594
    26
haftmann@41387
    27
type entry = { mapper: term, variances: (sort * (bool * bool)) list,
haftmann@41371
    28
  comp: thm, id: thm };
haftmann@40582
    29
wenzelm@41472
    30
structure Data = Generic_Data
wenzelm@41472
    31
(
haftmann@41390
    32
  type T = entry list Symtab.table
haftmann@40582
    33
  val empty = Symtab.empty
haftmann@40582
    34
  val extend = I
wenzelm@41472
    35
  fun merge data = Symtab.merge (K true) data
haftmann@40582
    36
);
haftmann@40582
    37
haftmann@41388
    38
val entries = Data.get o Context.Proof;
haftmann@40582
    39
haftmann@40582
    40
haftmann@40582
    41
(* type analysis *)
haftmann@40582
    42
haftmann@41389
    43
fun term_with_typ ctxt T t = Envir.subst_term_types
wenzelm@42361
    44
  (Type.typ_match (Proof_Context.tsig_of ctxt) (fastype_of t, T) Vartab.empty) t;
haftmann@41389
    45
haftmann@41388
    46
fun find_atomic ctxt T =
haftmann@40582
    47
  let
haftmann@41390
    48
    val variances_of = Option.map #variances o try hd o Symtab.lookup_list (entries ctxt);
haftmann@40582
    49
    fun add_variance is_contra T =
haftmann@40582
    50
      AList.map_default (op =) (T, (false, false))
haftmann@40582
    51
        ((if is_contra then apsnd else apfst) (K true));
haftmann@40582
    52
    fun analyze' is_contra (_, (co, contra)) T =
haftmann@40582
    53
      (if co then analyze is_contra T else I)
haftmann@40582
    54
      #> (if contra then analyze (not is_contra) T else I)
haftmann@40582
    55
    and analyze is_contra (T as Type (tyco, Ts)) = (case variances_of tyco
haftmann@40582
    56
          of NONE => add_variance is_contra T
haftmann@40582
    57
           | SOME variances => fold2 (analyze' is_contra) variances Ts)
haftmann@40582
    58
      | analyze is_contra T = add_variance is_contra T;
haftmann@40582
    59
  in analyze false T [] end;
haftmann@40582
    60
haftmann@41388
    61
fun construct_mapper ctxt atomic =
haftmann@40582
    62
  let
haftmann@41390
    63
    val lookup = hd o Symtab.lookup_list (entries ctxt);
haftmann@40582
    64
    fun constructs is_contra (_, (co, contra)) T T' =
haftmann@40582
    65
      (if co then [construct is_contra T T'] else [])
haftmann@40582
    66
      @ (if contra then [construct (not is_contra) T T'] else [])
haftmann@40582
    67
    and construct is_contra (T as Type (tyco, Ts)) (T' as Type (_, Ts')) =
haftmann@40582
    68
          let
haftmann@41388
    69
            val { mapper = raw_mapper, variances, ... } = lookup tyco;
haftmann@40582
    70
            val args = maps (fn (arg_pattern, (T, T')) =>
haftmann@40582
    71
              constructs is_contra arg_pattern T T')
haftmann@40582
    72
                (variances ~~ (Ts ~~ Ts'));
haftmann@40582
    73
            val (U, U') = if is_contra then (T', T) else (T, T');
haftmann@41388
    74
            val mapper = term_with_typ ctxt (map fastype_of args ---> U --> U') raw_mapper;
haftmann@41388
    75
          in list_comb (mapper, args) end
haftmann@40582
    76
      | construct is_contra (TFree (v, _)) (TFree _) = atomic (v, is_contra);
haftmann@40582
    77
  in construct end;
haftmann@40582
    78
haftmann@40582
    79
haftmann@40582
    80
(* mapper properties *)
haftmann@40582
    81
haftmann@41387
    82
val compositionality_ss = Simplifier.add_simp (Simpdata.mk_eq @{thm comp_def}) HOL_basic_ss;
haftmann@41387
    83
haftmann@41371
    84
fun make_comp_prop ctxt variances (tyco, mapper) =
haftmann@40582
    85
  let
haftmann@41371
    86
    val sorts = map fst variances
haftmann@41371
    87
    val (((vs3, vs2), vs1), _) = ctxt
haftmann@41371
    88
      |> Variable.invent_types sorts
haftmann@41371
    89
      ||>> Variable.invent_types sorts
haftmann@41371
    90
      ||>> Variable.invent_types sorts
haftmann@41371
    91
    val (Ts1, Ts2, Ts3) = (map TFree vs1, map TFree vs2, map TFree vs3);
haftmann@40582
    92
    fun mk_argT ((T, T'), (_, (co, contra))) =
haftmann@40582
    93
      (if co then [(T --> T')] else [])
haftmann@40582
    94
      @ (if contra then [(T' --> T)] else []);
haftmann@40582
    95
    val contras = maps (fn (_, (co, contra)) =>
haftmann@40582
    96
      (if co then [false] else []) @ (if contra then [true] else [])) variances;
haftmann@40582
    97
    val Ts21 = maps mk_argT ((Ts2 ~~ Ts1) ~~ variances);
haftmann@40582
    98
    val Ts32 = maps mk_argT ((Ts3 ~~ Ts2) ~~ variances);
haftmann@41371
    99
    fun invents n k nctxt =
haftmann@41371
   100
      let
wenzelm@43329
   101
        val names = Name.invent nctxt n k;
haftmann@41371
   102
      in (names, fold Name.declare names nctxt) end;
haftmann@41371
   103
    val ((names21, names32), nctxt) = Variable.names_of ctxt
haftmann@40582
   104
      |> invents "f" (length Ts21)
haftmann@40582
   105
      ||>> invents "f" (length Ts32);
haftmann@40582
   106
    val T1 = Type (tyco, Ts1);
haftmann@40582
   107
    val T2 = Type (tyco, Ts2);
haftmann@40582
   108
    val T3 = Type (tyco, Ts3);
haftmann@40582
   109
    val (args21, args32) = (names21 ~~ Ts21, names32 ~~ Ts32);
haftmann@40582
   110
    val args31 = map2 (fn is_contra => fn ((f21, T21), (f32, T32)) =>
haftmann@40582
   111
      if not is_contra then
haftmann@41371
   112
        HOLogic.mk_comp (Free (f21, T21), Free (f32, T32))
haftmann@40582
   113
      else
haftmann@41371
   114
        HOLogic.mk_comp (Free (f32, T32), Free (f21, T21))
haftmann@40582
   115
      ) contras (args21 ~~ args32)
haftmann@41395
   116
    fun mk_mapper T T' args = list_comb
haftmann@41395
   117
      (term_with_typ ctxt (map fastype_of args ---> T --> T') mapper, args);
haftmann@41387
   118
    val mapper21 = mk_mapper T2 T1 (map Free args21);
haftmann@41387
   119
    val mapper32 = mk_mapper T3 T2 (map Free args32);
haftmann@41387
   120
    val mapper31 = mk_mapper T3 T1 args31;
haftmann@41395
   121
    val eq1 = (HOLogic.mk_Trueprop o HOLogic.mk_eq)
haftmann@41395
   122
      (HOLogic.mk_comp (mapper21, mapper32), mapper31);
wenzelm@43329
   123
    val x = Free (the_single (Name.invent nctxt (Long_Name.base_name tyco) 1), T3)
haftmann@41395
   124
    val eq2 = (HOLogic.mk_Trueprop o HOLogic.mk_eq)
haftmann@41395
   125
      (mapper21 $ (mapper32 $ x), mapper31 $ x);
haftmann@41387
   126
    val comp_prop = fold_rev Logic.all (map Free (args21 @ args32)) eq1;
haftmann@41387
   127
    val compositionality_prop = fold_rev Logic.all (map Free (args21 @ args32) @ [x]) eq2;
haftmann@41387
   128
    fun prove_compositionality ctxt comp_thm = Skip_Proof.prove ctxt [] [] compositionality_prop
haftmann@41387
   129
      (K (ALLGOALS (Method.insert_tac [@{thm fun_cong} OF [comp_thm]]
haftmann@41387
   130
        THEN' Simplifier.asm_lr_simp_tac compositionality_ss
haftmann@41387
   131
        THEN_ALL_NEW (Goal.assume_rule_tac ctxt))));
haftmann@41387
   132
  in (comp_prop, prove_compositionality) end;
haftmann@41387
   133
haftmann@41387
   134
val identity_ss = Simplifier.add_simp (Simpdata.mk_eq @{thm id_def}) HOL_basic_ss;
haftmann@40582
   135
haftmann@41371
   136
fun make_id_prop ctxt variances (tyco, mapper) =
haftmann@40582
   137
  let
haftmann@46810
   138
    val (vs, _) = Variable.invent_types (map fst variances) ctxt;
haftmann@41371
   139
    val Ts = map TFree vs;
haftmann@40582
   140
    fun bool_num b = if b then 1 else 0;
haftmann@40582
   141
    fun mk_argT (T, (_, (co, contra))) =
haftmann@41387
   142
      replicate (bool_num co + bool_num contra) T
haftmann@41387
   143
    val arg_Ts = maps mk_argT (Ts ~~ variances)
haftmann@40582
   144
    val T = Type (tyco, Ts);
haftmann@41387
   145
    val head = term_with_typ ctxt (map (fn T => T --> T) arg_Ts ---> T --> T) mapper;
haftmann@41387
   146
    val lhs1 = list_comb (head, map (HOLogic.id_const) arg_Ts);
haftmann@41387
   147
    val lhs2 = list_comb (head, map (fn arg_T => Abs ("x", arg_T, Bound 0)) arg_Ts);
haftmann@41387
   148
    val rhs = HOLogic.id_const T;
haftmann@41395
   149
    val (id_prop, identity_prop) = pairself
haftmann@41395
   150
      (HOLogic.mk_Trueprop o HOLogic.mk_eq o rpair rhs) (lhs1, lhs2);
haftmann@41387
   151
    fun prove_identity ctxt id_thm = Skip_Proof.prove ctxt [] [] identity_prop
haftmann@41387
   152
      (K (ALLGOALS (Method.insert_tac [id_thm] THEN' Simplifier.asm_lr_simp_tac identity_ss)));
haftmann@41387
   153
  in (id_prop, prove_identity) end;
haftmann@40582
   154
haftmann@40582
   155
haftmann@40597
   156
(* analyzing and registering mappers *)
haftmann@40582
   157
haftmann@40594
   158
fun consume eq x [] = (false, [])
haftmann@40594
   159
  | consume eq x (ys as z :: zs) = if eq (x, z) then (true, zs) else (false, ys);
haftmann@40594
   160
haftmann@40587
   161
fun split_mapper_typ "fun" T =
haftmann@40587
   162
      let
haftmann@40587
   163
        val (Ts', T') = strip_type T;
haftmann@40587
   164
        val (Ts'', T'') = split_last Ts';
haftmann@40587
   165
        val (Ts''', T''') = split_last Ts'';
haftmann@40587
   166
      in (Ts''', T''', T'' --> T') end
haftmann@46810
   167
  | split_mapper_typ _ T =
haftmann@40587
   168
      let
haftmann@40587
   169
        val (Ts', T') = strip_type T;
haftmann@40587
   170
        val (Ts'', T'') = split_last Ts';
haftmann@40587
   171
      in (Ts'', T'', T') end;
haftmann@40587
   172
haftmann@46852
   173
fun analyze_mapper ctxt input_mapper =
haftmann@46852
   174
  let
haftmann@46852
   175
    val T = fastype_of input_mapper;
haftmann@46852
   176
    val _ = Type.no_tvars T;
haftmann@46852
   177
    val _ =
haftmann@46852
   178
      if null (subtract (op =) (Term.add_tfreesT T []) (Term.add_tfrees input_mapper []))
haftmann@46852
   179
      then ()
haftmann@46852
   180
      else error ("Illegal additional type variable(s) in term: " ^ Syntax.string_of_term ctxt input_mapper);
haftmann@46852
   181
    val _ =
haftmann@46852
   182
      if null (Term.add_vars (singleton
haftmann@46852
   183
        (Variable.export_terms (Variable.auto_fixes input_mapper ctxt) ctxt) input_mapper) [])
haftmann@46852
   184
      then ()
haftmann@46852
   185
      else error ("Illegal locally free variable(s) in term: "
haftmann@46852
   186
        ^ Syntax.string_of_term ctxt input_mapper);;
haftmann@46852
   187
    val mapper = singleton (Variable.polymorphic ctxt) input_mapper;
haftmann@46852
   188
    val _ =
haftmann@46852
   189
      if null (Term.add_tfreesT (fastype_of mapper) []) then ()
haftmann@46852
   190
      else error ("Illegal locally fixed type variable(s) in type: " ^ Syntax.string_of_typ ctxt T);
haftmann@46852
   191
    fun add_tycos (Type (tyco, Ts)) = insert (op =) tyco #> fold add_tycos Ts
haftmann@46852
   192
      | add_tycos _ = I;
haftmann@46852
   193
    val tycos = add_tycos T [];
haftmann@46852
   194
    val tyco = if tycos = ["fun"] then "fun"
haftmann@46852
   195
      else case remove (op =) "fun" tycos
haftmann@46852
   196
       of [tyco] => tyco
haftmann@46852
   197
        | _ => error ("Bad number of type constructors: " ^ Syntax.string_of_typ ctxt T);
haftmann@46852
   198
  in (mapper, T, tyco) end;
haftmann@46852
   199
haftmann@41390
   200
fun analyze_variances ctxt tyco T =
haftmann@40587
   201
  let
haftmann@41390
   202
    fun bad_typ () = error ("Bad mapper type: " ^ Syntax.string_of_typ ctxt T);
haftmann@40587
   203
    val (Ts, T1, T2) = split_mapper_typ tyco T
haftmann@40587
   204
      handle List.Empty => bad_typ ();
haftmann@40587
   205
    val _ = pairself
haftmann@40587
   206
      ((fn tyco' => if tyco' = tyco then () else bad_typ ()) o fst o dest_Type) (T1, T2)
haftmann@41387
   207
      handle TYPE _ => bad_typ ();
haftmann@40587
   208
    val (vs1, vs2) = pairself (map dest_TFree o snd o dest_Type) (T1, T2)
haftmann@40587
   209
      handle TYPE _ => bad_typ ();
haftmann@40587
   210
    val _ = if has_duplicates (eq_fst (op =)) (vs1 @ vs2)
haftmann@40587
   211
      then bad_typ () else ();
haftmann@46810
   212
    fun check_variance_pair (var1 as (_, sort1), var2 as (_, sort2)) =
haftmann@40594
   213
      let
haftmann@40594
   214
        val coT = TFree var1 --> TFree var2;
haftmann@40594
   215
        val contraT = TFree var2 --> TFree var1;
wenzelm@42361
   216
        val sort = Sign.inter_sort (Proof_Context.theory_of ctxt) (sort1, sort2);
haftmann@40594
   217
      in
haftmann@40594
   218
        consume (op =) coT
haftmann@40594
   219
        ##>> consume (op =) contraT
haftmann@40594
   220
        #>> pair sort
haftmann@40594
   221
      end;
haftmann@40594
   222
    val (variances, left_variances) = fold_map check_variance_pair (vs1 ~~ vs2) Ts;
haftmann@40594
   223
    val _ = if null left_variances then () else bad_typ ();
haftmann@40594
   224
  in variances end;
haftmann@40587
   225
haftmann@41505
   226
fun gen_enriched_type prep_term some_prfx raw_mapper lthy =
haftmann@40583
   227
  let
haftmann@46852
   228
    val (mapper, T, tyco) = analyze_mapper lthy (prep_term lthy raw_mapper);
haftmann@41371
   229
    val prfx = the_default (Long_Name.base_name tyco) some_prfx;
haftmann@41390
   230
    val variances = analyze_variances lthy tyco T;
haftmann@41390
   231
    val (comp_prop, prove_compositionality) = make_comp_prop lthy variances (tyco, mapper);
haftmann@41390
   232
    val (id_prop, prove_identity) = make_id_prop lthy variances (tyco, mapper);
haftmann@40856
   233
    val qualify = Binding.qualify true prfx o Binding.name;
haftmann@41389
   234
    fun mapper_declaration comp_thm id_thm phi context =
haftmann@41389
   235
      let
wenzelm@42388
   236
        val typ_instance = Sign.typ_instance (Context.theory_of context);
haftmann@41389
   237
        val mapper' = Morphism.term phi mapper;
haftmann@41389
   238
        val T_T' = pairself fastype_of (mapper, mapper');
haftmann@46852
   239
        val vars = Term.add_vars mapper' [];
wenzelm@42388
   240
      in
haftmann@46852
   241
        if null vars andalso typ_instance T_T' andalso typ_instance (swap T_T')
haftmann@41390
   242
        then (Data.map o Symtab.cons_list) (tyco,
haftmann@41389
   243
          { mapper = mapper', variances = variances,
haftmann@41390
   244
            comp = Morphism.thm phi comp_thm, id = Morphism.thm phi id_thm }) context
haftmann@41389
   245
        else context
haftmann@41389
   246
      end;
haftmann@41387
   247
    fun after_qed [single_comp_thm, single_id_thm] lthy =
haftmann@40587
   248
      lthy
haftmann@41387
   249
      |> Local_Theory.note ((qualify compN, []), single_comp_thm)
haftmann@41387
   250
      ||>> Local_Theory.note ((qualify idN, []), single_id_thm)
haftmann@41387
   251
      |-> (fn ((_, [comp_thm]), (_, [id_thm])) => fn lthy =>
haftmann@41371
   252
        lthy
haftmann@41388
   253
        |> Local_Theory.note ((qualify compositionalityN, []),
haftmann@41388
   254
            [prove_compositionality lthy comp_thm])
haftmann@41371
   255
        |> snd
haftmann@41388
   256
        |> Local_Theory.note ((qualify identityN, []),
haftmann@41388
   257
            [prove_identity lthy id_thm])
haftmann@41388
   258
        |> snd
wenzelm@45291
   259
        |> Local_Theory.declaration {syntax = false, pervasive = false}
wenzelm@45291
   260
          (mapper_declaration comp_thm id_thm))
haftmann@40583
   261
  in
haftmann@41390
   262
    lthy
haftmann@41371
   263
    |> Proof.theorem NONE after_qed (map (fn t => [(t, [])]) [comp_prop, id_prop])
haftmann@40583
   264
  end
haftmann@40583
   265
haftmann@41505
   266
val enriched_type = gen_enriched_type Syntax.check_term;
haftmann@41505
   267
val enriched_type_cmd = gen_enriched_type Syntax.read_term;
haftmann@40583
   268
wenzelm@46961
   269
val _ =
wenzelm@46961
   270
  Outer_Syntax.local_theory_to_proof @{command_spec "enriched_type"}
wenzelm@46961
   271
    "register operations managing the functorial structure of a type"
wenzelm@46961
   272
    (Scan.option (Parse.name --| @{keyword ":"}) -- Parse.term
wenzelm@46961
   273
      >> (fn (prfx, t) => enriched_type_cmd prfx t));
haftmann@40583
   274
haftmann@40582
   275
end;