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