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