src/Tools/subtyping.ML
author traytel
Wed Aug 17 19:49:07 2011 +0200 (2011-08-17)
changeset 45059 28d3e387f22e
parent 44338 700008399ee5
child 45060 9c2568c0a504
permissions -rw-r--r--
printing and deleting of coercions
wenzelm@40281
     1
(*  Title:      Tools/subtyping.ML
wenzelm@40281
     2
    Author:     Dmitriy Traytel, TU Muenchen
wenzelm@40281
     3
wenzelm@40281
     4
Coercive subtyping via subtype constraints.
wenzelm@40281
     5
*)
wenzelm@40281
     6
wenzelm@40281
     7
signature SUBTYPING =
wenzelm@40281
     8
sig
wenzelm@40939
     9
  val coercion_enabled: bool Config.T
wenzelm@40284
    10
  val add_type_map: term -> Context.generic -> Context.generic
wenzelm@40284
    11
  val add_coercion: term -> Context.generic -> Context.generic
traytel@45059
    12
  val print_coercions: Proof.context -> unit
traytel@45059
    13
  val print_coercion_maps: Proof.context -> unit
wenzelm@40283
    14
  val setup: theory -> theory
wenzelm@40281
    15
end;
wenzelm@40281
    16
wenzelm@40283
    17
structure Subtyping: SUBTYPING =
wenzelm@40281
    18
struct
wenzelm@40281
    19
wenzelm@40281
    20
(** coercions data **)
wenzelm@40281
    21
traytel@41353
    22
datatype variance = COVARIANT | CONTRAVARIANT | INVARIANT | INVARIANT_TO of typ;
wenzelm@40281
    23
wenzelm@40281
    24
datatype data = Data of
traytel@45059
    25
  {coes: (term * term list) Symreltab.table,  (*coercions table*)
wenzelm@40282
    26
   coes_graph: unit Graph.T,  (*coercions graph*)
wenzelm@40282
    27
   tmaps: (term * variance list) Symtab.table};  (*map functions*)
wenzelm@40281
    28
wenzelm@40281
    29
fun make_data (coes, coes_graph, tmaps) =
wenzelm@40281
    30
  Data {coes = coes, coes_graph = coes_graph, tmaps = tmaps};
wenzelm@40281
    31
wenzelm@40281
    32
structure Data = Generic_Data
wenzelm@40281
    33
(
wenzelm@40281
    34
  type T = data;
wenzelm@40281
    35
  val empty = make_data (Symreltab.empty, Graph.empty, Symtab.empty);
wenzelm@40281
    36
  val extend = I;
wenzelm@40281
    37
  fun merge
wenzelm@40281
    38
    (Data {coes = coes1, coes_graph = coes_graph1, tmaps = tmaps1},
wenzelm@40281
    39
      Data {coes = coes2, coes_graph = coes_graph2, tmaps = tmaps2}) =
traytel@45059
    40
    make_data (Symreltab.merge (eq_pair (op aconv) (eq_list (op aconv))) (coes1, coes2),
wenzelm@40281
    41
      Graph.merge (op =) (coes_graph1, coes_graph2),
wenzelm@40281
    42
      Symtab.merge (eq_pair (op aconv) (op =)) (tmaps1, tmaps2));
wenzelm@40281
    43
);
wenzelm@40281
    44
wenzelm@40281
    45
fun map_data f =
wenzelm@40281
    46
  Data.map (fn Data {coes, coes_graph, tmaps} =>
wenzelm@40281
    47
    make_data (f (coes, coes_graph, tmaps)));
wenzelm@40281
    48
wenzelm@40281
    49
fun map_coes f =
wenzelm@40281
    50
  map_data (fn (coes, coes_graph, tmaps) =>
wenzelm@40281
    51
    (f coes, coes_graph, tmaps));
wenzelm@40281
    52
wenzelm@40281
    53
fun map_coes_graph f =
wenzelm@40281
    54
  map_data (fn (coes, coes_graph, tmaps) =>
wenzelm@40281
    55
    (coes, f coes_graph, tmaps));
wenzelm@40281
    56
wenzelm@40281
    57
fun map_coes_and_graph f =
wenzelm@40281
    58
  map_data (fn (coes, coes_graph, tmaps) =>
wenzelm@40281
    59
    let val (coes', coes_graph') = f (coes, coes_graph);
wenzelm@40281
    60
    in (coes', coes_graph', tmaps) end);
wenzelm@40281
    61
wenzelm@40281
    62
fun map_tmaps f =
wenzelm@40281
    63
  map_data (fn (coes, coes_graph, tmaps) =>
wenzelm@40281
    64
    (coes, coes_graph, f tmaps));
wenzelm@40281
    65
wenzelm@40285
    66
val rep_data = (fn Data args => args) o Data.get o Context.Proof;
wenzelm@40281
    67
wenzelm@40281
    68
val coes_of = #coes o rep_data;
wenzelm@40281
    69
val coes_graph_of = #coes_graph o rep_data;
wenzelm@40281
    70
val tmaps_of = #tmaps o rep_data;
wenzelm@40281
    71
wenzelm@40281
    72
wenzelm@40281
    73
wenzelm@40281
    74
(** utils **)
wenzelm@40281
    75
wenzelm@40281
    76
fun nameT (Type (s, [])) = s;
wenzelm@40281
    77
fun t_of s = Type (s, []);
wenzelm@40286
    78
wenzelm@40281
    79
fun sort_of (TFree (_, S)) = SOME S
wenzelm@40281
    80
  | sort_of (TVar (_, S)) = SOME S
wenzelm@40281
    81
  | sort_of _ = NONE;
wenzelm@40281
    82
wenzelm@40281
    83
val is_typeT = fn (Type _) => true | _ => false;
traytel@41353
    84
val is_stypeT = fn (Type (_, [])) => true | _ => false;
wenzelm@40282
    85
val is_compT = fn (Type (_, _ :: _)) => true | _ => false;
wenzelm@40281
    86
val is_freeT = fn (TFree _) => true | _ => false;
wenzelm@40286
    87
val is_fixedvarT = fn (TVar (xi, _)) => not (Type_Infer.is_param xi) | _ => false;
traytel@41353
    88
val is_funtype = fn (Type ("fun", [_, _])) => true | _ => false;
traytel@43591
    89
val is_identity = fn (Abs (_, _, Bound 0)) => true | _ => false;
wenzelm@40281
    90
wenzelm@40281
    91
traytel@40836
    92
(* unification *)
wenzelm@40281
    93
traytel@40836
    94
exception TYPE_INFERENCE_ERROR of unit -> string;
wenzelm@40281
    95
exception NO_UNIFIER of string * typ Vartab.table;
wenzelm@40281
    96
wenzelm@40281
    97
fun unify weak ctxt =
wenzelm@40281
    98
  let
wenzelm@42361
    99
    val thy = Proof_Context.theory_of ctxt;
wenzelm@42386
   100
    val arity_sorts = Type.arity_sorts (Context.pretty ctxt) (Sign.tsig_of thy);
wenzelm@40281
   101
wenzelm@40282
   102
wenzelm@40281
   103
    (* adjust sorts of parameters *)
wenzelm@40281
   104
wenzelm@40281
   105
    fun not_of_sort x S' S =
wenzelm@40281
   106
      "Variable " ^ x ^ "::" ^ Syntax.string_of_sort ctxt S' ^ " not of sort " ^
wenzelm@40281
   107
        Syntax.string_of_sort ctxt S;
wenzelm@40281
   108
wenzelm@40281
   109
    fun meet (_, []) tye_idx = tye_idx
wenzelm@40281
   110
      | meet (Type (a, Ts), S) (tye_idx as (tye, _)) =
wenzelm@40281
   111
          meets (Ts, arity_sorts a S handle ERROR msg => raise NO_UNIFIER (msg, tye)) tye_idx
wenzelm@40281
   112
      | meet (TFree (x, S'), S) (tye_idx as (tye, _)) =
wenzelm@40281
   113
          if Sign.subsort thy (S', S) then tye_idx
wenzelm@40281
   114
          else raise NO_UNIFIER (not_of_sort x S' S, tye)
wenzelm@40281
   115
      | meet (TVar (xi, S'), S) (tye_idx as (tye, idx)) =
wenzelm@40281
   116
          if Sign.subsort thy (S', S) then tye_idx
wenzelm@40281
   117
          else if Type_Infer.is_param xi then
wenzelm@40286
   118
            (Vartab.update_new
wenzelm@40286
   119
              (xi, Type_Infer.mk_param idx (Sign.inter_sort thy (S', S))) tye, idx + 1)
wenzelm@40281
   120
          else raise NO_UNIFIER (not_of_sort (Term.string_of_vname xi) S' S, tye)
wenzelm@40281
   121
    and meets (T :: Ts, S :: Ss) (tye_idx as (tye, _)) =
wenzelm@40286
   122
          meets (Ts, Ss) (meet (Type_Infer.deref tye T, S) tye_idx)
wenzelm@40281
   123
      | meets _ tye_idx = tye_idx;
wenzelm@40281
   124
wenzelm@40281
   125
    val weak_meet = if weak then fn _ => I else meet
wenzelm@40281
   126
wenzelm@40281
   127
wenzelm@40281
   128
    (* occurs check and assignment *)
wenzelm@40281
   129
wenzelm@40281
   130
    fun occurs_check tye xi (TVar (xi', _)) =
wenzelm@40281
   131
          if xi = xi' then raise NO_UNIFIER ("Occurs check!", tye)
wenzelm@40281
   132
          else
wenzelm@40281
   133
            (case Vartab.lookup tye xi' of
wenzelm@40281
   134
              NONE => ()
wenzelm@40281
   135
            | SOME T => occurs_check tye xi T)
wenzelm@40281
   136
      | occurs_check tye xi (Type (_, Ts)) = List.app (occurs_check tye xi) Ts
wenzelm@40281
   137
      | occurs_check _ _ _ = ();
wenzelm@40281
   138
wenzelm@40281
   139
    fun assign xi (T as TVar (xi', _)) S env =
wenzelm@40281
   140
          if xi = xi' then env
wenzelm@40281
   141
          else env |> weak_meet (T, S) |>> Vartab.update_new (xi, T)
wenzelm@40281
   142
      | assign xi T S (env as (tye, _)) =
wenzelm@40281
   143
          (occurs_check tye xi T; env |> weak_meet (T, S) |>> Vartab.update_new (xi, T));
wenzelm@40281
   144
wenzelm@40281
   145
wenzelm@40281
   146
    (* unification *)
wenzelm@40281
   147
wenzelm@40281
   148
    fun show_tycon (a, Ts) =
wenzelm@40281
   149
      quote (Syntax.string_of_typ ctxt (Type (a, replicate (length Ts) dummyT)));
wenzelm@40281
   150
wenzelm@40281
   151
    fun unif (T1, T2) (env as (tye, _)) =
wenzelm@40286
   152
      (case pairself (`Type_Infer.is_paramT o Type_Infer.deref tye) (T1, T2) of
wenzelm@40281
   153
        ((true, TVar (xi, S)), (_, T)) => assign xi T S env
wenzelm@40281
   154
      | ((_, T), (true, TVar (xi, S))) => assign xi T S env
wenzelm@40281
   155
      | ((_, Type (a, Ts)), (_, Type (b, Us))) =>
wenzelm@40281
   156
          if weak andalso null Ts andalso null Us then env
wenzelm@40281
   157
          else if a <> b then
wenzelm@40281
   158
            raise NO_UNIFIER
wenzelm@40281
   159
              ("Clash of types " ^ show_tycon (a, Ts) ^ " and " ^ show_tycon (b, Us), tye)
wenzelm@40281
   160
          else fold unif (Ts ~~ Us) env
wenzelm@40281
   161
      | ((_, T), (_, U)) => if T = U then env else raise NO_UNIFIER ("", tye));
wenzelm@40281
   162
wenzelm@40281
   163
  in unif end;
wenzelm@40281
   164
wenzelm@40281
   165
val weak_unify = unify true;
wenzelm@40281
   166
val strong_unify = unify false;
wenzelm@40281
   167
wenzelm@40281
   168
wenzelm@40281
   169
(* Typ_Graph shortcuts *)
wenzelm@40281
   170
wenzelm@40281
   171
fun get_preds G T = Typ_Graph.all_preds G [T];
wenzelm@40281
   172
fun get_succs G T = Typ_Graph.all_succs G [T];
wenzelm@40281
   173
fun maybe_new_typnode T G = perhaps (try (Typ_Graph.new_node (T, ()))) G;
wenzelm@40281
   174
fun maybe_new_typnodes Ts G = fold maybe_new_typnode Ts G;
wenzelm@44338
   175
fun new_imm_preds G Ts =  (* FIXME inefficient *)
wenzelm@44338
   176
  subtract (op =) Ts (distinct (op =) (maps (Typ_Graph.immediate_preds G) Ts));
wenzelm@44338
   177
fun new_imm_succs G Ts =  (* FIXME inefficient *)
wenzelm@44338
   178
  subtract (op =) Ts (distinct (op =) (maps (Typ_Graph.immediate_succs G) Ts));
wenzelm@40281
   179
wenzelm@40281
   180
wenzelm@40281
   181
(* Graph shortcuts *)
wenzelm@40281
   182
wenzelm@40281
   183
fun maybe_new_node s G = perhaps (try (Graph.new_node (s, ()))) G
wenzelm@40281
   184
fun maybe_new_nodes ss G = fold maybe_new_node ss G
wenzelm@40281
   185
wenzelm@40281
   186
wenzelm@40281
   187
wenzelm@40281
   188
(** error messages **)
wenzelm@40281
   189
wenzelm@42383
   190
fun gen_msg err msg =
wenzelm@42383
   191
  err () ^ "\nNow trying to infer coercions:\n\nCoercion inference failed" ^
traytel@40836
   192
  (if msg = "" then "" else ": " ^ msg) ^ "\n";
traytel@40836
   193
wenzelm@40281
   194
fun prep_output ctxt tye bs ts Ts =
wenzelm@40281
   195
  let
wenzelm@40281
   196
    val (Ts_bTs', ts') = Type_Infer.finish ctxt tye (Ts @ map snd bs, ts);
wenzelm@40281
   197
    val (Ts', Ts'') = chop (length Ts) Ts_bTs';
wenzelm@40281
   198
    fun prep t =
wenzelm@40281
   199
      let val xs = rev (Term.variant_frees t (rev (map fst bs ~~ Ts'')))
wenzelm@42284
   200
      in Term.subst_bounds (map Syntax_Trans.mark_boundT xs, t) end;
wenzelm@40281
   201
  in (map prep ts', Ts') end;
wenzelm@40281
   202
wenzelm@40281
   203
fun err_loose i = error ("Loose bound variable: B." ^ string_of_int i);
wenzelm@42383
   204
traytel@40836
   205
fun unif_failed msg =
traytel@40836
   206
  "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n\n";
wenzelm@42383
   207
traytel@40836
   208
fun err_appl_msg ctxt msg tye bs t T u U () =
traytel@40836
   209
  let val ([t', u'], [T', U']) = prep_output ctxt tye bs [t, u] [T, U]
wenzelm@42383
   210
  in unif_failed msg ^ Type.appl_error ctxt t' T' u' U' ^ "\n" end;
wenzelm@40281
   211
wenzelm@40281
   212
fun err_list ctxt msg tye Ts =
wenzelm@40281
   213
  let
wenzelm@40281
   214
    val (_, Ts') = prep_output ctxt tye [] [] Ts;
wenzelm@42383
   215
    val text =
wenzelm@42383
   216
      msg ^ "\n" ^ "Cannot unify a list of types that should be the same:" ^ "\n" ^
wenzelm@42383
   217
        Pretty.string_of (Pretty.list "[" "]" (map (Syntax.pretty_typ ctxt) Ts'));
wenzelm@40281
   218
  in
wenzelm@40281
   219
    error text
wenzelm@40281
   220
  end;
wenzelm@40281
   221
wenzelm@40281
   222
fun err_bound ctxt msg tye packs =
wenzelm@40281
   223
  let
wenzelm@40281
   224
    val (ts, Ts) = fold
wenzelm@40281
   225
      (fn (bs, t $ u, U, _, U') => fn (ts, Ts) =>
traytel@40836
   226
        let val (t', T') = prep_output ctxt tye bs [t, u] [U', U]
wenzelm@40282
   227
        in (t' :: ts, T' :: Ts) end)
wenzelm@40281
   228
      packs ([], []);
traytel@40836
   229
    val text = cat_lines ([msg, "Cannot fulfil subtype constraints:"] @
wenzelm@40281
   230
        (map2 (fn [t, u] => fn [T, U] => Pretty.string_of (
wenzelm@40281
   231
          Pretty.block [
wenzelm@42383
   232
            Syntax.pretty_typ ctxt T, Pretty.brk 2, Pretty.str "<:", Pretty.brk 2,
wenzelm@42383
   233
            Syntax.pretty_typ ctxt U, Pretty.brk 3,
wenzelm@42383
   234
            Pretty.str "from function application", Pretty.brk 2,
wenzelm@42383
   235
            Pretty.block [Syntax.pretty_term ctxt (t $ u)]]))
wenzelm@40281
   236
        ts Ts))
wenzelm@40281
   237
  in
wenzelm@40281
   238
    error text
wenzelm@40281
   239
  end;
wenzelm@40281
   240
wenzelm@40281
   241
wenzelm@40281
   242
wenzelm@40281
   243
(** constraint generation **)
wenzelm@40281
   244
traytel@40836
   245
fun generate_constraints ctxt err =
wenzelm@40281
   246
  let
wenzelm@40281
   247
    fun gen cs _ (Const (_, T)) tye_idx = (T, tye_idx, cs)
wenzelm@40281
   248
      | gen cs _ (Free (_, T)) tye_idx = (T, tye_idx, cs)
wenzelm@40281
   249
      | gen cs _ (Var (_, T)) tye_idx = (T, tye_idx, cs)
wenzelm@40281
   250
      | gen cs bs (Bound i) tye_idx =
wenzelm@43278
   251
          (snd (nth bs i handle General.Subscript => err_loose i), tye_idx, cs)
wenzelm@40281
   252
      | gen cs bs (Abs (x, T, t)) tye_idx =
wenzelm@40281
   253
          let val (U, tye_idx', cs') = gen cs ((x, T) :: bs) t tye_idx
wenzelm@40281
   254
          in (T --> U, tye_idx', cs') end
wenzelm@40281
   255
      | gen cs bs (t $ u) tye_idx =
wenzelm@40281
   256
          let
wenzelm@40281
   257
            val (T, tye_idx', cs') = gen cs bs t tye_idx;
wenzelm@40281
   258
            val (U', (tye, idx), cs'') = gen cs' bs u tye_idx';
wenzelm@40286
   259
            val U = Type_Infer.mk_param idx [];
wenzelm@40286
   260
            val V = Type_Infer.mk_param (idx + 1) [];
wenzelm@40281
   261
            val tye_idx''= strong_unify ctxt (U --> V, T) (tye, idx + 2)
traytel@41353
   262
              handle NO_UNIFIER (msg, _) => error (gen_msg err msg);
wenzelm@40281
   263
            val error_pack = (bs, t $ u, U, V, U');
wenzelm@40281
   264
          in (V, tye_idx'', ((U', U), error_pack) :: cs'') end;
wenzelm@40281
   265
  in
wenzelm@40281
   266
    gen [] []
wenzelm@40281
   267
  end;
wenzelm@40281
   268
wenzelm@40281
   269
wenzelm@40281
   270
wenzelm@40281
   271
(** constraint resolution **)
wenzelm@40281
   272
wenzelm@40281
   273
exception BOUND_ERROR of string;
wenzelm@40281
   274
traytel@40836
   275
fun process_constraints ctxt err cs tye_idx =
wenzelm@40281
   276
  let
wenzelm@42388
   277
    val thy = Proof_Context.theory_of ctxt;
wenzelm@42388
   278
wenzelm@40285
   279
    val coes_graph = coes_graph_of ctxt;
wenzelm@40285
   280
    val tmaps = tmaps_of ctxt;
wenzelm@42388
   281
    val arity_sorts = Type.arity_sorts (Context.pretty ctxt) (Sign.tsig_of thy);
wenzelm@40281
   282
wenzelm@40281
   283
    fun split_cs _ [] = ([], [])
wenzelm@40282
   284
      | split_cs f (c :: cs) =
wenzelm@40281
   285
          (case pairself f (fst c) of
wenzelm@40281
   286
            (false, false) => apsnd (cons c) (split_cs f cs)
wenzelm@40281
   287
          | _ => apfst (cons c) (split_cs f cs));
wenzelm@42383
   288
traytel@41353
   289
    fun unify_list (T :: Ts) tye_idx =
wenzelm@42383
   290
      fold (fn U => fn tye_idx' => strong_unify ctxt (T, U) tye_idx') Ts tye_idx;
wenzelm@40281
   291
wenzelm@40282
   292
wenzelm@40281
   293
    (* check whether constraint simplification will terminate using weak unification *)
wenzelm@40282
   294
traytel@41353
   295
    val _ = fold (fn (TU, _) => fn tye_idx =>
traytel@41353
   296
      weak_unify ctxt TU tye_idx handle NO_UNIFIER (msg, _) =>
traytel@40836
   297
        error (gen_msg err ("weak unification of subtype constraints fails\n" ^ msg))) cs tye_idx;
wenzelm@40281
   298
wenzelm@40281
   299
wenzelm@40281
   300
    (* simplify constraints *)
wenzelm@40282
   301
wenzelm@40281
   302
    fun simplify_constraints cs tye_idx =
wenzelm@40281
   303
      let
wenzelm@40281
   304
        fun contract a Ts Us error_pack done todo tye idx =
wenzelm@40281
   305
          let
wenzelm@40281
   306
            val arg_var =
wenzelm@40281
   307
              (case Symtab.lookup tmaps a of
wenzelm@40281
   308
                (*everything is invariant for unknown constructors*)
wenzelm@40281
   309
                NONE => replicate (length Ts) INVARIANT
wenzelm@40281
   310
              | SOME av => snd av);
wenzelm@40281
   311
            fun new_constraints (variance, constraint) (cs, tye_idx) =
wenzelm@40281
   312
              (case variance of
wenzelm@40281
   313
                COVARIANT => (constraint :: cs, tye_idx)
wenzelm@40281
   314
              | CONTRAVARIANT => (swap constraint :: cs, tye_idx)
traytel@41353
   315
              | INVARIANT_TO T => (cs, unify_list [T, fst constraint, snd constraint] tye_idx
wenzelm@42383
   316
                  handle NO_UNIFIER (msg, _) =>
wenzelm@42383
   317
                    err_list ctxt (gen_msg err
traytel@45059
   318
                      "failed to unify invariant arguments w.r.t. to the known map function" ^ msg)
traytel@41353
   319
                      (fst tye_idx) Ts)
wenzelm@40281
   320
              | INVARIANT => (cs, strong_unify ctxt constraint tye_idx
wenzelm@42383
   321
                  handle NO_UNIFIER (msg, _) =>
traytel@41353
   322
                    error (gen_msg err ("failed to unify invariant arguments" ^ msg))));
wenzelm@40281
   323
            val (new, (tye', idx')) = apfst (fn cs => (cs ~~ replicate (length cs) error_pack))
wenzelm@40281
   324
              (fold new_constraints (arg_var ~~ (Ts ~~ Us)) ([], (tye, idx)));
wenzelm@40281
   325
            val test_update = is_compT orf is_freeT orf is_fixedvarT;
wenzelm@40281
   326
            val (ch, done') =
wenzelm@40286
   327
              if not (null new) then ([], done)
wenzelm@40286
   328
              else split_cs (test_update o Type_Infer.deref tye') done;
wenzelm@40281
   329
            val todo' = ch @ todo;
wenzelm@40281
   330
          in
wenzelm@40281
   331
            simplify done' (new @ todo') (tye', idx')
wenzelm@40281
   332
          end
wenzelm@40281
   333
        (*xi is definitely a parameter*)
wenzelm@40281
   334
        and expand varleq xi S a Ts error_pack done todo tye idx =
wenzelm@40281
   335
          let
wenzelm@40281
   336
            val n = length Ts;
wenzelm@40286
   337
            val args = map2 Type_Infer.mk_param (idx upto idx + n - 1) (arity_sorts a S);
wenzelm@40281
   338
            val tye' = Vartab.update_new (xi, Type(a, args)) tye;
wenzelm@40286
   339
            val (ch, done') = split_cs (is_compT o Type_Infer.deref tye') done;
wenzelm@40281
   340
            val todo' = ch @ todo;
wenzelm@40281
   341
            val new =
wenzelm@40281
   342
              if varleq then (Type(a, args), Type (a, Ts))
wenzelm@40286
   343
              else (Type (a, Ts), Type (a, args));
wenzelm@40281
   344
          in
wenzelm@40281
   345
            simplify done' ((new, error_pack) :: todo') (tye', idx + n)
wenzelm@40281
   346
          end
wenzelm@40281
   347
        (*TU is a pair of a parameter and a free/fixed variable*)
traytel@41353
   348
        and eliminate TU done todo tye idx =
wenzelm@40281
   349
          let
wenzelm@40286
   350
            val [TVar (xi, S)] = filter Type_Infer.is_paramT TU;
wenzelm@40286
   351
            val [T] = filter_out Type_Infer.is_paramT TU;
wenzelm@40281
   352
            val SOME S' = sort_of T;
wenzelm@40281
   353
            val test_update = if is_freeT T then is_freeT else is_fixedvarT;
wenzelm@40281
   354
            val tye' = Vartab.update_new (xi, T) tye;
wenzelm@40286
   355
            val (ch, done') = split_cs (test_update o Type_Infer.deref tye') done;
wenzelm@40281
   356
            val todo' = ch @ todo;
wenzelm@40281
   357
          in
wenzelm@42388
   358
            if Sign.subsort thy (S', S) (*TODO check this*)
wenzelm@40281
   359
            then simplify done' todo' (tye', idx)
traytel@40836
   360
            else error (gen_msg err "sort mismatch")
wenzelm@40281
   361
          end
wenzelm@40281
   362
        and simplify done [] tye_idx = (done, tye_idx)
wenzelm@40281
   363
          | simplify done (((T, U), error_pack) :: todo) (tye_idx as (tye, idx)) =
wenzelm@40286
   364
              (case (Type_Infer.deref tye T, Type_Infer.deref tye U) of
wenzelm@40281
   365
                (Type (a, []), Type (b, [])) =>
wenzelm@40281
   366
                  if a = b then simplify done todo tye_idx
wenzelm@40281
   367
                  else if Graph.is_edge coes_graph (a, b) then simplify done todo tye_idx
traytel@40836
   368
                  else error (gen_msg err (a ^ " is not a subtype of " ^ b))
wenzelm@40281
   369
              | (Type (a, Ts), Type (b, Us)) =>
traytel@40836
   370
                  if a <> b then error (gen_msg err "different constructors")
traytel@40836
   371
                    (fst tye_idx) error_pack
wenzelm@40281
   372
                  else contract a Ts Us error_pack done todo tye idx
wenzelm@40282
   373
              | (TVar (xi, S), Type (a, Ts as (_ :: _))) =>
wenzelm@40281
   374
                  expand true xi S a Ts error_pack done todo tye idx
wenzelm@40282
   375
              | (Type (a, Ts as (_ :: _)), TVar (xi, S)) =>
wenzelm@40281
   376
                  expand false xi S a Ts error_pack done todo tye idx
wenzelm@40281
   377
              | (T, U) =>
wenzelm@40281
   378
                  if T = U then simplify done todo tye_idx
wenzelm@40282
   379
                  else if exists (is_freeT orf is_fixedvarT) [T, U] andalso
wenzelm@40286
   380
                    exists Type_Infer.is_paramT [T, U]
traytel@41353
   381
                  then eliminate [T, U] done todo tye idx
wenzelm@40281
   382
                  else if exists (is_freeT orf is_fixedvarT) [T, U]
traytel@40836
   383
                  then error (gen_msg err "not eliminated free/fixed variables")
wenzelm@40282
   384
                  else simplify (((T, U), error_pack) :: done) todo tye_idx);
wenzelm@40281
   385
      in
wenzelm@40281
   386
        simplify [] cs tye_idx
wenzelm@40281
   387
      end;
wenzelm@40281
   388
wenzelm@40281
   389
wenzelm@40281
   390
    (* do simplification *)
wenzelm@40282
   391
wenzelm@40281
   392
    val (cs', tye_idx') = simplify_constraints cs tye_idx;
wenzelm@42383
   393
wenzelm@42383
   394
    fun find_error_pack lower T' = map_filter
traytel@40836
   395
      (fn ((T, U), pack) => if if lower then T' = U else T' = T then SOME pack else NONE) cs';
wenzelm@42383
   396
wenzelm@42383
   397
    fun find_cycle_packs nodes =
traytel@40836
   398
      let
traytel@40836
   399
        val (but_last, last) = split_last nodes
traytel@40836
   400
        val pairs = (last, hd nodes) :: (but_last ~~ tl nodes);
traytel@40836
   401
      in
traytel@40836
   402
        map_filter
wenzelm@40838
   403
          (fn (TU, pack) => if member (op =) pairs TU then SOME pack else NONE)
traytel@40836
   404
          cs'
traytel@40836
   405
      end;
wenzelm@40281
   406
wenzelm@40281
   407
    (*styps stands either for supertypes or for subtypes of a type T
wenzelm@40281
   408
      in terms of the subtype-relation (excluding T itself)*)
wenzelm@40282
   409
    fun styps super T =
wenzelm@44338
   410
      (if super then Graph.immediate_succs else Graph.immediate_preds) coes_graph T
wenzelm@40281
   411
        handle Graph.UNDEF _ => [];
wenzelm@40281
   412
wenzelm@40282
   413
    fun minmax sup (T :: Ts) =
wenzelm@40281
   414
      let
wenzelm@40281
   415
        fun adjust T U = if sup then (T, U) else (U, T);
wenzelm@40281
   416
        fun extract T [] = T
wenzelm@40282
   417
          | extract T (U :: Us) =
wenzelm@40281
   418
              if Graph.is_edge coes_graph (adjust T U) then extract T Us
wenzelm@40281
   419
              else if Graph.is_edge coes_graph (adjust U T) then extract U Us
traytel@40836
   420
              else raise BOUND_ERROR "uncomparable types in type list";
wenzelm@40281
   421
      in
wenzelm@40281
   422
        t_of (extract T Ts)
wenzelm@40281
   423
      end;
wenzelm@40281
   424
wenzelm@40282
   425
    fun ex_styp_of_sort super T styps_and_sorts =
wenzelm@40281
   426
      let
wenzelm@40281
   427
        fun adjust T U = if super then (T, U) else (U, T);
wenzelm@40282
   428
        fun styp_test U Ts = forall
wenzelm@40281
   429
          (fn T => T = U orelse Graph.is_edge coes_graph (adjust U T)) Ts;
wenzelm@42388
   430
        fun fitting Ts S U = Sign.of_sort thy (t_of U, S) andalso styp_test U Ts
wenzelm@40281
   431
      in
wenzelm@40281
   432
        forall (fn (Ts, S) => exists (fitting Ts S) (T :: styps super T)) styps_and_sorts
wenzelm@40281
   433
      end;
wenzelm@40281
   434
wenzelm@40281
   435
    (* computes the tightest possible, correct assignment for 'a::S
wenzelm@40281
   436
       e.g. in the supremum case (sup = true):
wenzelm@40281
   437
               ------- 'a::S---
wenzelm@40281
   438
              /        /    \  \
wenzelm@40281
   439
             /        /      \  \
wenzelm@40281
   440
        'b::C1   'c::C2 ...  T1 T2 ...
wenzelm@40281
   441
wenzelm@40281
   442
       sorts - list of sorts [C1, C2, ...]
wenzelm@40281
   443
       T::Ts - non-empty list of base types [T1, T2, ...]
wenzelm@40281
   444
    *)
wenzelm@40282
   445
    fun tightest sup S styps_and_sorts (T :: Ts) =
wenzelm@40281
   446
      let
wenzelm@42388
   447
        fun restriction T = Sign.of_sort thy (t_of T, S)
wenzelm@40281
   448
          andalso ex_styp_of_sort (not sup) T styps_and_sorts;
wenzelm@40281
   449
        fun candidates T = inter (op =) (filter restriction (T :: styps sup T));
wenzelm@40281
   450
      in
wenzelm@40281
   451
        (case fold candidates Ts (filter restriction (T :: styps sup T)) of
traytel@40836
   452
          [] => raise BOUND_ERROR ("no " ^ (if sup then "supremum" else "infimum"))
wenzelm@40281
   453
        | [T] => t_of T
wenzelm@40281
   454
        | Ts => minmax sup Ts)
wenzelm@40281
   455
      end;
wenzelm@40281
   456
wenzelm@40281
   457
    fun build_graph G [] tye_idx = (G, tye_idx)
wenzelm@40282
   458
      | build_graph G ((T, U) :: cs) tye_idx =
wenzelm@40281
   459
        if T = U then build_graph G cs tye_idx
wenzelm@40281
   460
        else
wenzelm@40281
   461
          let
wenzelm@40281
   462
            val G' = maybe_new_typnodes [T, U] G;
traytel@45059
   463
            val (G'', tye_idx') = (Typ_Graph.add_edge_acyclic (T, U) G', tye_idx)
wenzelm@40281
   464
              handle Typ_Graph.CYCLES cycles =>
wenzelm@40281
   465
                let
wenzelm@42383
   466
                  val (tye, idx) =
wenzelm@42383
   467
                    fold
traytel@40836
   468
                      (fn cycle => fn tye_idx' => (unify_list cycle tye_idx'
wenzelm@42383
   469
                        handle NO_UNIFIER (msg, _) =>
wenzelm@42383
   470
                          err_bound ctxt
traytel@40836
   471
                            (gen_msg err ("constraint cycle not unifiable" ^ msg)) (fst tye_idx)
traytel@40836
   472
                            (find_cycle_packs cycle)))
traytel@40836
   473
                      cycles tye_idx
wenzelm@40281
   474
                in
traytel@40836
   475
                  collapse (tye, idx) cycles G
traytel@40836
   476
                end
wenzelm@40281
   477
          in
wenzelm@40281
   478
            build_graph G'' cs tye_idx'
wenzelm@40281
   479
          end
traytel@40836
   480
    and collapse (tye, idx) cycles G = (*nodes non-empty list*)
wenzelm@40281
   481
      let
traytel@40836
   482
        (*all cycles collapse to one node,
traytel@40836
   483
          because all of them share at least the nodes x and y*)
traytel@40836
   484
        val nodes = (distinct (op =) (flat cycles));
traytel@40836
   485
        val T = Type_Infer.deref tye (hd nodes);
wenzelm@40281
   486
        val P = new_imm_preds G nodes;
wenzelm@40281
   487
        val S = new_imm_succs G nodes;
wenzelm@40281
   488
        val G' = Typ_Graph.del_nodes (tl nodes) G;
traytel@40836
   489
        fun check_and_gen super T' =
traytel@40836
   490
          let val U = Type_Infer.deref tye T';
traytel@40836
   491
          in
traytel@40836
   492
            if not (is_typeT T) orelse not (is_typeT U) orelse T = U
traytel@40836
   493
            then if super then (hd nodes, T') else (T', hd nodes)
wenzelm@42383
   494
            else
wenzelm@42383
   495
              if super andalso
traytel@40836
   496
                Graph.is_edge coes_graph (nameT T, nameT U) then (hd nodes, T')
wenzelm@42383
   497
              else if not super andalso
traytel@40836
   498
                Graph.is_edge coes_graph (nameT U, nameT T) then (T', hd nodes)
traytel@40836
   499
              else err_bound ctxt (gen_msg err "cycle elimination produces inconsistent graph")
wenzelm@42383
   500
                    (fst tye_idx)
traytel@40836
   501
                    (maps find_cycle_packs cycles @ find_error_pack super T')
traytel@40836
   502
          end;
wenzelm@40281
   503
      in
traytel@40836
   504
        build_graph G' (map (check_and_gen false) P @ map (check_and_gen true) S) (tye, idx)
wenzelm@40281
   505
      end;
wenzelm@40281
   506
wenzelm@40281
   507
    fun assign_bound lower G key (tye_idx as (tye, _)) =
wenzelm@40286
   508
      if Type_Infer.is_paramT (Type_Infer.deref tye key) then
wenzelm@40281
   509
        let
wenzelm@40286
   510
          val TVar (xi, S) = Type_Infer.deref tye key;
wenzelm@40281
   511
          val get_bound = if lower then get_preds else get_succs;
wenzelm@40281
   512
          val raw_bound = get_bound G key;
wenzelm@40286
   513
          val bound = map (Type_Infer.deref tye) raw_bound;
wenzelm@40286
   514
          val not_params = filter_out Type_Infer.is_paramT bound;
wenzelm@40282
   515
          fun to_fulfil T =
wenzelm@40281
   516
            (case sort_of T of
wenzelm@40281
   517
              NONE => NONE
wenzelm@40282
   518
            | SOME S =>
wenzelm@40286
   519
                SOME
wenzelm@40286
   520
                  (map nameT
wenzelm@42405
   521
                    (filter_out Type_Infer.is_paramT
wenzelm@42405
   522
                      (map (Type_Infer.deref tye) (get_bound G T))), S));
wenzelm@40281
   523
          val styps_and_sorts = distinct (op =) (map_filter to_fulfil raw_bound);
wenzelm@40281
   524
          val assignment =
wenzelm@40281
   525
            if null bound orelse null not_params then NONE
wenzelm@40281
   526
            else SOME (tightest lower S styps_and_sorts (map nameT not_params)
wenzelm@42383
   527
                handle BOUND_ERROR msg =>
traytel@40836
   528
                  err_bound ctxt (gen_msg err msg) tye (find_error_pack lower key))
wenzelm@40281
   529
        in
wenzelm@40281
   530
          (case assignment of
wenzelm@40281
   531
            NONE => tye_idx
wenzelm@40281
   532
          | SOME T =>
wenzelm@40286
   533
              if Type_Infer.is_paramT T then tye_idx
wenzelm@40281
   534
              else if lower then (*upper bound check*)
wenzelm@40281
   535
                let
wenzelm@40286
   536
                  val other_bound = map (Type_Infer.deref tye) (get_succs G key);
wenzelm@40281
   537
                  val s = nameT T;
wenzelm@40281
   538
                in
wenzelm@40281
   539
                  if subset (op = o apfst nameT) (filter is_typeT other_bound, s :: styps true s)
wenzelm@40281
   540
                  then apfst (Vartab.update (xi, T)) tye_idx
traytel@40836
   541
                  else err_bound ctxt (gen_msg err ("assigned simple type " ^ s ^
wenzelm@40281
   542
                    " clashes with the upper bound of variable " ^
traytel@40836
   543
                    Syntax.string_of_typ ctxt (TVar(xi, S)))) tye (find_error_pack (not lower) key)
wenzelm@40281
   544
                end
wenzelm@40281
   545
              else apfst (Vartab.update (xi, T)) tye_idx)
wenzelm@40281
   546
        end
wenzelm@40281
   547
      else tye_idx;
wenzelm@40281
   548
wenzelm@40281
   549
    val assign_lb = assign_bound true;
wenzelm@40281
   550
    val assign_ub = assign_bound false;
wenzelm@40281
   551
wenzelm@40281
   552
    fun assign_alternating ts' ts G tye_idx =
wenzelm@40281
   553
      if ts' = ts then tye_idx
wenzelm@40281
   554
      else
wenzelm@40281
   555
        let
wenzelm@40281
   556
          val (tye_idx' as (tye, _)) = fold (assign_lb G) ts tye_idx
wenzelm@40281
   557
            |> fold (assign_ub G) ts;
wenzelm@40281
   558
        in
wenzelm@42383
   559
          assign_alternating ts
traytel@40836
   560
            (filter (Type_Infer.is_paramT o Type_Infer.deref tye) ts) G tye_idx'
wenzelm@40281
   561
        end;
wenzelm@40281
   562
wenzelm@40281
   563
    (*Unify all weakly connected components of the constraint forest,
wenzelm@40282
   564
      that contain only params. These are the only WCCs that contain
wenzelm@40281
   565
      params anyway.*)
wenzelm@40281
   566
    fun unify_params G (tye_idx as (tye, _)) =
wenzelm@40281
   567
      let
wenzelm@40286
   568
        val max_params =
wenzelm@40286
   569
          filter (Type_Infer.is_paramT o Type_Infer.deref tye) (Typ_Graph.maximals G);
wenzelm@40281
   570
        val to_unify = map (fn T => T :: get_preds G T) max_params;
wenzelm@40281
   571
      in
wenzelm@42383
   572
        fold
traytel@40836
   573
          (fn Ts => fn tye_idx' => unify_list Ts tye_idx'
traytel@41353
   574
            handle NO_UNIFIER (msg, _) => err_list ctxt (gen_msg err msg) (fst tye_idx) Ts)
traytel@40836
   575
          to_unify tye_idx
wenzelm@40281
   576
      end;
wenzelm@40281
   577
wenzelm@40281
   578
    fun solve_constraints G tye_idx = tye_idx
wenzelm@40281
   579
      |> assign_alternating [] (Typ_Graph.keys G) G
wenzelm@40281
   580
      |> unify_params G;
wenzelm@40281
   581
  in
wenzelm@40281
   582
    build_graph Typ_Graph.empty (map fst cs') tye_idx'
wenzelm@40281
   583
      |-> solve_constraints
wenzelm@40281
   584
  end;
wenzelm@40281
   585
wenzelm@40281
   586
wenzelm@40281
   587
wenzelm@40281
   588
(** coercion insertion **)
wenzelm@40281
   589
traytel@40836
   590
fun gen_coercion ctxt tye (T1, T2) =
traytel@40836
   591
  (case pairself (Type_Infer.deref tye) (T1, T2) of
traytel@40836
   592
    ((Type (a, [])), (Type (b, []))) =>
traytel@40836
   593
        if a = b
traytel@40836
   594
        then Abs (Name.uu, Type (a, []), Bound 0)
traytel@40836
   595
        else
traytel@40836
   596
          (case Symreltab.lookup (coes_of ctxt) (a, b) of
traytel@40836
   597
            NONE => raise Fail (a ^ " is not a subtype of " ^ b)
traytel@45059
   598
          | SOME (co, _) => co)
traytel@40836
   599
  | ((Type (a, Ts)), (Type (b, Us))) =>
traytel@40836
   600
        if a <> b
traytel@40836
   601
        then raise Fail ("Different constructors: " ^ a ^ " and " ^ b)
traytel@40836
   602
        else
traytel@40836
   603
          let
traytel@40836
   604
            fun inst t Ts =
traytel@40836
   605
              Term.subst_vars
traytel@40836
   606
                (((Term.add_tvar_namesT (fastype_of t) []) ~~ rev Ts), []) t;
traytel@41353
   607
            fun sub_co (COVARIANT, TU) = SOME (gen_coercion ctxt tye TU)
traytel@41353
   608
              | sub_co (CONTRAVARIANT, TU) = SOME (gen_coercion ctxt tye (swap TU))
traytel@45059
   609
              | sub_co (INVARIANT_TO _, _) = NONE;
traytel@40836
   610
            fun ts_of [] = []
traytel@40836
   611
              | ts_of (Type ("fun", [x1, x2]) :: xs) = x1 :: x2 :: (ts_of xs);
traytel@40836
   612
          in
traytel@40836
   613
            (case Symtab.lookup (tmaps_of ctxt) a of
traytel@40836
   614
              NONE => raise Fail ("No map function for " ^ a ^ " known")
traytel@40836
   615
            | SOME tmap =>
traytel@40836
   616
                let
traytel@41353
   617
                  val used_coes = map_filter sub_co ((snd tmap) ~~ (Ts ~~ Us));
traytel@40836
   618
                in
traytel@43591
   619
                  if null (filter (not o is_identity) used_coes)
traytel@43591
   620
                  then Abs (Name.uu, Type (a, Ts), Bound 0)
traytel@43591
   621
                  else Term.list_comb
traytel@40836
   622
                    (inst (fst tmap) (ts_of (map fastype_of used_coes)), used_coes)
traytel@40836
   623
                end)
traytel@40836
   624
          end
traytel@40836
   625
  | (T, U) =>
traytel@40836
   626
        if Type.could_unify (T, U)
traytel@40836
   627
        then Abs (Name.uu, T, Bound 0)
traytel@40836
   628
        else raise Fail ("Cannot generate coercion from "
traytel@40836
   629
          ^ Syntax.string_of_typ ctxt T ^ " to " ^ Syntax.string_of_typ ctxt U));
traytel@40836
   630
wenzelm@40281
   631
fun insert_coercions ctxt tye ts =
wenzelm@40281
   632
  let
wenzelm@40281
   633
    fun insert _ (Const (c, T)) =
traytel@40836
   634
          let val T' = T;
wenzelm@40281
   635
          in (Const (c, T'), T') end
wenzelm@40281
   636
      | insert _ (Free (x, T)) =
traytel@40836
   637
          let val T' = T;
wenzelm@40281
   638
          in (Free (x, T'), T') end
wenzelm@40281
   639
      | insert _ (Var (xi, T)) =
traytel@40836
   640
          let val T' = T;
wenzelm@40281
   641
          in (Var (xi, T'), T') end
wenzelm@40281
   642
      | insert bs (Bound i) =
wenzelm@43278
   643
          let val T = nth bs i handle General.Subscript => err_loose i;
wenzelm@40281
   644
          in (Bound i, T) end
wenzelm@40281
   645
      | insert bs (Abs (x, T, t)) =
wenzelm@40281
   646
          let
traytel@40836
   647
            val T' = T;
wenzelm@40282
   648
            val (t', T'') = insert (T' :: bs) t;
wenzelm@40281
   649
          in
wenzelm@40281
   650
            (Abs (x, T', t'), T' --> T'')
wenzelm@40281
   651
          end
wenzelm@40281
   652
      | insert bs (t $ u) =
wenzelm@40281
   653
          let
wenzelm@42405
   654
            val (t', Type ("fun", [U, T])) =
wenzelm@42405
   655
              apsnd (Type_Infer.deref tye) (insert bs t);
wenzelm@40281
   656
            val (u', U') = insert bs u;
wenzelm@40281
   657
          in
traytel@40836
   658
            if can (fn TU => strong_unify ctxt TU (tye, 0)) (U, U')
traytel@40836
   659
            then (t' $ u', T)
traytel@40836
   660
            else (t' $ (gen_coercion ctxt tye (U', U) $ u'), T)
wenzelm@40281
   661
          end
wenzelm@40281
   662
  in
wenzelm@40281
   663
    map (fst o insert []) ts
wenzelm@40281
   664
  end;
wenzelm@40281
   665
wenzelm@40281
   666
wenzelm@40281
   667
wenzelm@40281
   668
(** assembling the pipeline **)
wenzelm@40281
   669
wenzelm@42398
   670
fun coercion_infer_types ctxt raw_ts =
wenzelm@40281
   671
  let
wenzelm@42405
   672
    val (idx, ts) = Type_Infer_Context.prepare ctxt raw_ts;
wenzelm@40281
   673
traytel@40836
   674
    fun inf _ (t as (Const (_, T))) tye_idx = (t, T, tye_idx)
traytel@40836
   675
      | inf _ (t as (Free (_, T))) tye_idx = (t, T, tye_idx)
traytel@40836
   676
      | inf _ (t as (Var (_, T))) tye_idx = (t, T, tye_idx)
traytel@40836
   677
      | inf bs (t as (Bound i)) tye_idx =
wenzelm@43278
   678
          (t, snd (nth bs i handle General.Subscript => err_loose i), tye_idx)
traytel@40836
   679
      | inf bs (Abs (x, T, t)) tye_idx =
traytel@40836
   680
          let val (t', U, tye_idx') = inf ((x, T) :: bs) t tye_idx
traytel@40836
   681
          in (Abs (x, T, t'), T --> U, tye_idx') end
traytel@40836
   682
      | inf bs (t $ u) tye_idx =
traytel@40836
   683
          let
traytel@40836
   684
            val (t', T, tye_idx') = inf bs t tye_idx;
traytel@40836
   685
            val (u', U, (tye, idx)) = inf bs u tye_idx';
traytel@40836
   686
            val V = Type_Infer.mk_param idx [];
traytel@40836
   687
            val (tu, tye_idx'') = (t' $ u', strong_unify ctxt (U --> V, T) (tye, idx + 1))
wenzelm@42383
   688
              handle NO_UNIFIER (msg, tye') =>
traytel@40836
   689
                raise TYPE_INFERENCE_ERROR (err_appl_msg ctxt msg tye' bs t T u U);
traytel@40836
   690
          in (tu, V, tye_idx'') end;
wenzelm@40281
   691
wenzelm@42383
   692
    fun infer_single t tye_idx =
traytel@40836
   693
      let val (t, _, tye_idx') = inf [] t tye_idx;
traytel@40938
   694
      in (t, tye_idx') end;
wenzelm@42383
   695
traytel@40938
   696
    val (ts', (tye, _)) = (fold_map infer_single ts (Vartab.empty, idx)
wenzelm@42383
   697
      handle TYPE_INFERENCE_ERROR err =>
traytel@40836
   698
        let
traytel@40836
   699
          fun gen_single t (tye_idx, constraints) =
traytel@40836
   700
            let val (_, tye_idx', constraints') = generate_constraints ctxt err t tye_idx
traytel@40836
   701
            in (tye_idx', constraints' @ constraints) end;
wenzelm@42383
   702
traytel@40836
   703
          val (tye_idx, constraints) = fold gen_single ts ((Vartab.empty, idx), []);
traytel@40836
   704
          val (tye, idx) = process_constraints ctxt err constraints tye_idx;
wenzelm@42383
   705
        in
traytel@40836
   706
          (insert_coercions ctxt tye ts, (tye, idx))
traytel@40836
   707
        end);
wenzelm@40281
   708
wenzelm@40281
   709
    val (_, ts'') = Type_Infer.finish ctxt tye ([], ts');
wenzelm@40281
   710
  in ts'' end;
wenzelm@40281
   711
wenzelm@40281
   712
wenzelm@40281
   713
wenzelm@40281
   714
(** installation **)
wenzelm@40281
   715
wenzelm@40283
   716
(* term check *)
wenzelm@40283
   717
wenzelm@42616
   718
val coercion_enabled = Attrib.setup_config_bool @{binding coercion_enabled} (K false);
wenzelm@40939
   719
wenzelm@40283
   720
val add_term_check =
wenzelm@40283
   721
  Syntax.add_term_check ~100 "coercions"
wenzelm@42402
   722
    (fn ctxt => Config.get ctxt coercion_enabled ? coercion_infer_types ctxt);
wenzelm@40281
   723
wenzelm@40281
   724
wenzelm@40283
   725
(* declarations *)
wenzelm@40281
   726
wenzelm@40284
   727
fun add_type_map raw_t context =
wenzelm@40281
   728
  let
wenzelm@40281
   729
    val ctxt = Context.proof_of context;
wenzelm@40284
   730
    val t = singleton (Variable.polymorphic ctxt) raw_t;
wenzelm@40281
   731
traytel@45059
   732
    fun err_str t = "\n\nThe provided function has the type:\n" ^
wenzelm@42383
   733
      Syntax.string_of_typ ctxt (fastype_of t) ^
traytel@45059
   734
      "\n\nThe general type signature of a map function is:" ^
traytel@41353
   735
      "\nf1 => f2 => ... => fn => C [x1, ..., xn] => C [y1, ..., yn]" ^
traytel@45059
   736
      "\nwhere C is a constructor and fi is of type (xi => yi) or (yi => xi).";
wenzelm@42383
   737
traytel@41353
   738
    val ((fis, T1), T2) = apfst split_last (strip_type (fastype_of t))
traytel@41353
   739
      handle Empty => error ("Not a proper map function:" ^ err_str t);
wenzelm@42383
   740
wenzelm@40281
   741
    fun gen_arg_var ([], []) = []
wenzelm@40282
   742
      | gen_arg_var ((T, T') :: Ts, (U, U') :: Us) =
traytel@41353
   743
          if U = U' then
traytel@41353
   744
            if is_stypeT U then INVARIANT_TO U :: gen_arg_var ((T, T') :: Ts, Us)
traytel@41353
   745
            else error ("Invariant xi and yi should be base types:" ^ err_str t)
traytel@41353
   746
          else if T = U andalso T' = U' then COVARIANT :: gen_arg_var (Ts, Us)
wenzelm@40281
   747
          else if T = U' andalso T' = U then CONTRAVARIANT :: gen_arg_var (Ts, Us)
traytel@41353
   748
          else error ("Functions do not apply to arguments correctly:" ^ err_str t)
wenzelm@42383
   749
      | gen_arg_var (_, Ts) =
wenzelm@42383
   750
          if forall (op = andf is_stypeT o fst) Ts
traytel@41353
   751
          then map (INVARIANT_TO o fst) Ts
traytel@41353
   752
          else error ("Different numbers of functions and variant arguments\n" ^ err_str t);
wenzelm@40281
   753
traytel@41353
   754
    (*retry flag needed to adjust the type lists, when given a map over type constructor fun*)
traytel@41353
   755
    fun check_map_fun fis (Type (C1, Ts)) (Type (C2, Us)) retry =
traytel@41353
   756
          if C1 = C2 andalso not (null fis) andalso forall is_funtype fis
traytel@41353
   757
          then ((map dest_funT fis, Ts ~~ Us), C1)
traytel@41353
   758
          else error ("Not a proper map function:" ^ err_str t)
traytel@41353
   759
      | check_map_fun fis T1 T2 true =
traytel@41353
   760
          let val (fis', T') = split_last fis
traytel@41353
   761
          in check_map_fun fis' T' (T1 --> T2) false end
traytel@41353
   762
      | check_map_fun _ _ _ _ = error ("Not a proper map function:" ^ err_str t);
wenzelm@40281
   763
traytel@41353
   764
    val res = check_map_fun fis T1 T2 true;
wenzelm@40281
   765
    val res_av = gen_arg_var (fst res);
wenzelm@40281
   766
  in
wenzelm@40281
   767
    map_tmaps (Symtab.update (snd res, (t, res_av))) context
wenzelm@40281
   768
  end;
wenzelm@40281
   769
traytel@45059
   770
fun transitive_coercion tab G (a, b) =
traytel@45059
   771
  let
traytel@45059
   772
    val path = hd (Graph.irreducible_paths G (a, b));
traytel@45059
   773
    val path' = fst (split_last path) ~~ tl path;
traytel@45059
   774
    val coercions = map (fst o the o Symreltab.lookup tab) path';
traytel@45059
   775
  in (Abs (Name.uu, Type (a, []),
traytel@45059
   776
      fold (fn t => fn u => t $ u) coercions (Bound 0)), coercions)
traytel@45059
   777
  end;
traytel@45059
   778
wenzelm@40284
   779
fun add_coercion raw_t context =
wenzelm@40281
   780
  let
wenzelm@40281
   781
    val ctxt = Context.proof_of context;
wenzelm@40284
   782
    val t = singleton (Variable.polymorphic ctxt) raw_t;
wenzelm@40281
   783
traytel@45059
   784
    fun err_coercion () = error ("Bad type for a coercion:\n" ^
traytel@45059
   785
        Syntax.string_of_term ctxt t ^ " :: " ^
wenzelm@40281
   786
        Syntax.string_of_typ ctxt (fastype_of t));
wenzelm@40281
   787
wenzelm@40840
   788
    val (T1, T2) = Term.dest_funT (fastype_of t)
wenzelm@40840
   789
      handle TYPE _ => err_coercion ();
wenzelm@40281
   790
wenzelm@40281
   791
    val a =
wenzelm@40281
   792
      (case T1 of
wenzelm@40281
   793
        Type (x, []) => x
wenzelm@40281
   794
      | _ => err_coercion ());
wenzelm@40281
   795
wenzelm@40281
   796
    val b =
wenzelm@40281
   797
      (case T2 of
wenzelm@40281
   798
        Type (x, []) => x
wenzelm@40281
   799
      | _ => err_coercion ());
wenzelm@40281
   800
wenzelm@40281
   801
    fun coercion_data_update (tab, G) =
wenzelm@40281
   802
      let
wenzelm@40281
   803
        val G' = maybe_new_nodes [a, b] G
wenzelm@40281
   804
        val G'' = Graph.add_edge_trans_acyclic (a, b) G'
traytel@45059
   805
          handle Graph.CYCLES _ => error (
traytel@45059
   806
            Syntax.string_of_typ ctxt T1 ^ " is already a subtype of " ^
traytel@45059
   807
            Syntax.string_of_typ ctxt T2 ^ "!\n\nCannot add coercion of type: " ^
traytel@45059
   808
            Syntax.string_of_typ ctxt (T1 --> T2));
wenzelm@40281
   809
        val new_edges =
wenzelm@40281
   810
          flat (Graph.dest G'' |> map (fn (x, ys) => ys |> map_filter (fn y =>
wenzelm@40281
   811
            if Graph.is_edge G' (x, y) then NONE else SOME (x, y))));
wenzelm@40281
   812
        val G_and_new = Graph.add_edge (a, b) G';
wenzelm@40281
   813
wenzelm@40281
   814
        val tab' = fold
traytel@45059
   815
          (fn pair => fn tab =>
traytel@45059
   816
            Symreltab.update (pair, transitive_coercion tab G_and_new pair) tab)
wenzelm@40281
   817
          (filter (fn pair => pair <> (a, b)) new_edges)
traytel@45059
   818
          (Symreltab.update ((a, b), (t, [])) tab);
wenzelm@40281
   819
      in
wenzelm@40281
   820
        (tab', G'')
wenzelm@40281
   821
      end;
wenzelm@40281
   822
  in
wenzelm@40281
   823
    map_coes_and_graph coercion_data_update context
wenzelm@40281
   824
  end;
wenzelm@40281
   825
traytel@45059
   826
fun delete_coercion raw_t context =
traytel@45059
   827
  let
traytel@45059
   828
    val ctxt = Context.proof_of context;
traytel@45059
   829
    val t = singleton (Variable.polymorphic ctxt) raw_t;
traytel@45059
   830
traytel@45059
   831
    fun err_coercion the = error ("Not" ^
traytel@45059
   832
        (if the then " the defined " else  " a ") ^ "coercion:\n" ^
traytel@45059
   833
        Syntax.string_of_term ctxt t ^ " :: " ^
traytel@45059
   834
        Syntax.string_of_typ ctxt (fastype_of t));
traytel@45059
   835
traytel@45059
   836
    val (T1, T2) = Term.dest_funT (fastype_of t)
traytel@45059
   837
      handle TYPE _ => err_coercion false;
traytel@45059
   838
traytel@45059
   839
    val a =
traytel@45059
   840
      (case T1 of
traytel@45059
   841
        Type (x, []) => x
traytel@45059
   842
      | _ => err_coercion false);
traytel@45059
   843
traytel@45059
   844
    val b =
traytel@45059
   845
      (case T2 of
traytel@45059
   846
        Type (x, []) => x
traytel@45059
   847
      | _ => err_coercion false);
traytel@45059
   848
traytel@45059
   849
    fun delete_and_insert tab G =
traytel@45059
   850
      let
traytel@45059
   851
        val pairs =
traytel@45059
   852
          Symreltab.fold (fn ((a, b), (_, ts)) => fn pairs =>
traytel@45059
   853
            if member (op aconv) ts t then (a, b) :: pairs else pairs) tab [(a, b)];
traytel@45059
   854
        fun delete pair (G, tab) = (Graph.del_edge pair G, Symreltab.delete_safe pair tab);
traytel@45059
   855
        val (G', tab') = fold delete pairs (G, tab);
traytel@45059
   856
        fun reinsert pair (G, xs) = (case (Graph.irreducible_paths G pair) of
traytel@45059
   857
              [] => (G, xs)
traytel@45059
   858
            | _ => (Graph.add_edge pair G, (pair, transitive_coercion tab' G' pair) :: xs));
traytel@45059
   859
        val (G'', ins) = fold reinsert pairs (G', []);
traytel@45059
   860
      in
traytel@45059
   861
        (fold Symreltab.update ins tab', G'')
traytel@45059
   862
      end
traytel@45059
   863
traytel@45059
   864
    fun show_term t = Pretty.block [Syntax.pretty_term ctxt t,
traytel@45059
   865
      Pretty.str " :: ", Syntax.pretty_typ ctxt (fastype_of t)]
traytel@45059
   866
traytel@45059
   867
    fun coercion_data_update (tab, G) =
traytel@45059
   868
        (case Symreltab.lookup tab (a, b) of
traytel@45059
   869
          NONE => err_coercion false
traytel@45059
   870
        | SOME (t', []) => if t aconv t'
traytel@45059
   871
            then delete_and_insert tab G
traytel@45059
   872
            else err_coercion true
traytel@45059
   873
        | SOME (t', ts) => if t aconv t'
traytel@45059
   874
            then error ("Cannot delete the automatically derived coercion:\n" ^
traytel@45059
   875
              Syntax.string_of_term ctxt t ^ " :: " ^
traytel@45059
   876
              Syntax.string_of_typ ctxt (fastype_of t) ^
traytel@45059
   877
              Pretty.string_of (Pretty.big_list "\n\nDeleting one of the coercions:"
traytel@45059
   878
                (map show_term ts)) ^
traytel@45059
   879
              "\nwill also remove the transitive coercion.")
traytel@45059
   880
            else err_coercion true);
traytel@45059
   881
  in
traytel@45059
   882
    map_coes_and_graph coercion_data_update context
traytel@45059
   883
  end;
traytel@45059
   884
traytel@45059
   885
fun print_coercions ctxt =
traytel@45059
   886
  let
traytel@45059
   887
    fun show_coercion ((a, b), (t, _)) = Pretty.block [
traytel@45059
   888
      Syntax.pretty_typ ctxt (Type (a, [])),
traytel@45059
   889
      Pretty.brk 1, Pretty.str "<:", Pretty.brk 1,
traytel@45059
   890
      Syntax.pretty_typ ctxt (Type (b, [])),
traytel@45059
   891
      Pretty.brk 3, Pretty.block [Pretty.str "using", Pretty.brk 1,
traytel@45059
   892
      Pretty.quote (Syntax.pretty_term ctxt t)]];
traytel@45059
   893
  in
traytel@45059
   894
    Pretty.big_list "Coercions:" (map show_coercion (Symreltab.dest (coes_of ctxt)))
traytel@45059
   895
    |> Pretty.writeln
traytel@45059
   896
  end;
traytel@45059
   897
traytel@45059
   898
fun print_coercion_maps ctxt =
traytel@45059
   899
  let
traytel@45059
   900
    fun show_map (x, (t, _)) = Pretty.block [
traytel@45059
   901
      Pretty.str x, Pretty.str ":", Pretty.brk 1,
traytel@45059
   902
      Pretty.quote (Syntax.pretty_term ctxt t)];
traytel@45059
   903
  in
traytel@45059
   904
    Pretty.big_list "Coercion maps:" (map show_map (Symtab.dest (tmaps_of ctxt)))
traytel@45059
   905
    |> Pretty.writeln
traytel@45059
   906
  end;
traytel@45059
   907
wenzelm@40283
   908
wenzelm@40283
   909
(* theory setup *)
wenzelm@40283
   910
wenzelm@40283
   911
val setup =
wenzelm@40283
   912
  Context.theory_map add_term_check #>
wenzelm@40284
   913
  Attrib.setup @{binding coercion}
wenzelm@40284
   914
    (Args.term >> (fn t => Thm.declaration_attribute (K (add_coercion t))))
wenzelm@40281
   915
    "declaration of new coercions" #>
traytel@45059
   916
  Attrib.setup @{binding coercion_delete}
traytel@45059
   917
    (Args.term >> (fn t => Thm.declaration_attribute (K (delete_coercion t))))
traytel@45059
   918
    "deletion of coercions" #>
traytel@40297
   919
  Attrib.setup @{binding coercion_map}
wenzelm@40284
   920
    (Args.term >> (fn t => Thm.declaration_attribute (K (add_type_map t))))
wenzelm@40283
   921
    "declaration of new map functions";
wenzelm@40281
   922
traytel@45059
   923
traytel@45059
   924
(* outer syntax commands *)
traytel@45059
   925
traytel@45059
   926
val _ =
traytel@45059
   927
  Outer_Syntax.improper_command "print_coercions" "print all coercions" Keyword.diag
traytel@45059
   928
    (Scan.succeed (Toplevel.keep (print_coercions o Toplevel.context_of)))
traytel@45059
   929
val _ =
traytel@45059
   930
  Outer_Syntax.improper_command "print_coercion_maps" "print all coercion maps" Keyword.diag
traytel@45059
   931
    (Scan.succeed (Toplevel.keep (print_coercion_maps o Toplevel.context_of)))
traytel@45059
   932
wenzelm@40281
   933
end;