src/Pure/type_infer.ML
author wenzelm
Mon Sep 13 13:20:18 2010 +0200 (2010-09-13)
changeset 39296 e275d581a218
parent 39295 6e8b0672c6a2
child 40286 b928e3960446
permissions -rw-r--r--
tuned signature;
tuned comments;
wenzelm@2957
     1
(*  Title:      Pure/type_infer.ML
wenzelm@2957
     2
    Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
wenzelm@2957
     3
wenzelm@39296
     4
Representation of type-inference problems.  Simple type inference.
wenzelm@2957
     5
*)
wenzelm@2957
     6
wenzelm@2957
     7
signature TYPE_INFER =
wenzelm@2957
     8
sig
wenzelm@24504
     9
  val is_param: indexname -> bool
wenzelm@39294
    10
  val is_paramT: typ -> bool
wenzelm@14788
    11
  val param: int -> string * sort -> typ
wenzelm@39296
    12
  val anyT: sort -> typ
wenzelm@22771
    13
  val paramify_vars: typ -> typ
wenzelm@18339
    14
  val paramify_dummies: typ -> int -> typ * int
wenzelm@39296
    15
  val deref: typ Vartab.table -> typ -> typ
wenzelm@39296
    16
  val finish: Proof.context -> typ Vartab.table -> typ list * term list -> typ list * term list
wenzelm@39296
    17
  val fixate: Proof.context -> term list -> term list
wenzelm@39296
    18
  val prepare: Proof.context -> (string -> typ option) -> (string * int -> typ option) ->
wenzelm@39296
    19
    term list -> int * term list
wenzelm@39290
    20
  val infer_types: Proof.context -> (string -> typ option) -> (indexname -> typ option) ->
wenzelm@27263
    21
    term list -> term list
wenzelm@2957
    22
end;
wenzelm@2957
    23
wenzelm@37145
    24
structure Type_Infer: TYPE_INFER =
wenzelm@2957
    25
struct
wenzelm@2957
    26
wenzelm@22698
    27
(** type parameters and constraints **)
wenzelm@2957
    28
wenzelm@39286
    29
(* type inference parameters -- may get instantiated *)
wenzelm@2957
    30
wenzelm@24504
    31
fun is_param (x, _: int) = String.isPrefix "?" x;
wenzelm@39294
    32
wenzelm@39294
    33
fun is_paramT (TVar (xi, _)) = is_param xi
wenzelm@39294
    34
  | is_paramT _ = false;
wenzelm@39294
    35
wenzelm@22698
    36
fun param i (x, S) = TVar (("?" ^ x, i), S);
wenzelm@22698
    37
wenzelm@39294
    38
fun mk_param i S = TVar (("?'a", i), S);
wenzelm@39294
    39
wenzelm@39296
    40
wenzelm@39296
    41
(* pre-stage parameters *)
wenzelm@39296
    42
wenzelm@39296
    43
fun anyT S = TFree ("'_dummy_", S);
wenzelm@39296
    44
wenzelm@32002
    45
val paramify_vars =
wenzelm@32146
    46
  Same.commit
wenzelm@32146
    47
    (Term_Subst.map_atypsT_same
wenzelm@32146
    48
      (fn TVar ((x, i), S) => (param i (x, S)) | _ => raise Same.SAME));
wenzelm@22771
    49
wenzelm@22698
    50
val paramify_dummies =
wenzelm@22698
    51
  let
wenzelm@22698
    52
    fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
wenzelm@2957
    53
wenzelm@22698
    54
    fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
wenzelm@22698
    55
      | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
wenzelm@22698
    56
      | paramify (Type (a, Ts)) maxidx =
wenzelm@22698
    57
          let val (Ts', maxidx') = fold_map paramify Ts maxidx
wenzelm@22698
    58
          in (Type (a, Ts'), maxidx') end
wenzelm@22698
    59
      | paramify T maxidx = (T, maxidx);
wenzelm@22698
    60
  in paramify end;
wenzelm@2957
    61
wenzelm@2957
    62
wenzelm@2957
    63
wenzelm@39294
    64
(** prepare types/terms: create inference parameters **)
wenzelm@2957
    65
wenzelm@39294
    66
(* prepare_typ *)
wenzelm@2957
    67
wenzelm@39294
    68
fun prepare_typ typ params_idx =
wenzelm@2957
    69
  let
berghofe@32141
    70
    val (params', idx) = fold_atyps
wenzelm@20668
    71
      (fn TVar (xi as (x, _), S) =>
berghofe@32141
    72
          (fn ps_idx as (ps, idx) =>
wenzelm@39287
    73
            if is_param xi andalso not (Vartab.defined ps xi)
wenzelm@39294
    74
            then (Vartab.update (xi, mk_param idx S) ps, idx + 1) else ps_idx)
berghofe@32141
    75
        | _ => I) typ params_idx;
wenzelm@2957
    76
wenzelm@39294
    77
    fun prepare (T as Type (a, Ts)) idx =
wenzelm@39294
    78
          if T = dummyT then (mk_param idx [], idx + 1)
wenzelm@39294
    79
          else
wenzelm@39294
    80
            let val (Ts', idx') = fold_map prepare Ts idx
wenzelm@39294
    81
            in (Type (a, Ts'), idx') end
wenzelm@39294
    82
      | prepare (T as TVar (xi, _)) idx =
wenzelm@20735
    83
          (case Vartab.lookup params' xi of
wenzelm@39294
    84
            NONE => T
berghofe@32141
    85
          | SOME p => p, idx)
wenzelm@39294
    86
      | prepare (TFree ("'_dummy_", S)) idx = (mk_param idx S, idx + 1)
wenzelm@39294
    87
      | prepare (T as TFree _) idx = (T, idx);
berghofe@32141
    88
wenzelm@39294
    89
    val (typ', idx') = prepare typ idx;
wenzelm@39294
    90
  in (typ', (params', idx')) end;
wenzelm@2957
    91
wenzelm@2957
    92
wenzelm@39294
    93
(* prepare_term *)
wenzelm@2957
    94
wenzelm@39294
    95
fun prepare_term const_type tm (vparams, params, idx) =
wenzelm@2957
    96
  let
berghofe@32141
    97
    fun add_vparm xi (ps_idx as (ps, idx)) =
wenzelm@20735
    98
      if not (Vartab.defined ps xi) then
wenzelm@39294
    99
        (Vartab.update (xi, mk_param idx []) ps, idx + 1)
berghofe@32141
   100
      else ps_idx;
wenzelm@2957
   101
berghofe@32141
   102
    val (vparams', idx') = fold_aterms
wenzelm@20668
   103
      (fn Var (_, Type ("_polymorphic_", _)) => I
wenzelm@20668
   104
        | Var (xi, _) => add_vparm xi
wenzelm@20668
   105
        | Free (x, _) => add_vparm (x, ~1)
wenzelm@20668
   106
        | _ => I)
berghofe@32141
   107
      tm (vparams, idx);
wenzelm@20735
   108
    fun var_param xi = the (Vartab.lookup vparams' xi);
wenzelm@2957
   109
wenzelm@39294
   110
    fun polyT_of T idx = apsnd snd (prepare_typ (paramify_vars T) (Vartab.empty, idx));
wenzelm@2957
   111
wenzelm@22698
   112
    fun constraint T t ps =
wenzelm@20668
   113
      if T = dummyT then (t, ps)
wenzelm@2957
   114
      else
wenzelm@39294
   115
        let val (T', ps') = prepare_typ T ps
wenzelm@39294
   116
        in (Type.constraint T' t, ps') end;
wenzelm@2957
   117
wenzelm@39294
   118
    fun prepare (Const ("_type_constraint_", T) $ t) ps_idx =
wenzelm@39294
   119
          let
wenzelm@39294
   120
            val (T', ps_idx') = prepare_typ T ps_idx;
wenzelm@39294
   121
            val (t', ps_idx'') = prepare t ps_idx';
wenzelm@39294
   122
          in (Const ("_type_constraint_", T') $ t', ps_idx'') end
wenzelm@39294
   123
      | prepare (Const (c, T)) (ps, idx) =
wenzelm@2957
   124
          (case const_type c of
berghofe@32141
   125
            SOME U =>
wenzelm@39294
   126
              let val (U', idx') = polyT_of U idx
wenzelm@39294
   127
              in constraint T (Const (c, U')) (ps, idx') end
wenzelm@39291
   128
          | NONE => error ("Undeclared constant: " ^ quote c))
wenzelm@39294
   129
      | prepare (Var (xi, Type ("_polymorphic_", [T]))) (ps, idx) =
wenzelm@39294
   130
          let val (T', idx') = polyT_of T idx
wenzelm@39294
   131
          in (Var (xi, T'), (ps, idx')) end
wenzelm@39294
   132
      | prepare (Var (xi, T)) ps_idx = constraint T (Var (xi, var_param xi)) ps_idx
wenzelm@39294
   133
      | prepare (Free (x, T)) ps_idx = constraint T (Free (x, var_param (x, ~1))) ps_idx
wenzelm@39294
   134
      | prepare (Bound i) ps_idx = (Bound i, ps_idx)
wenzelm@39294
   135
      | prepare (Abs (x, T, t)) ps_idx =
wenzelm@39292
   136
          let
wenzelm@39294
   137
            val (T', ps_idx') = prepare_typ T ps_idx;
wenzelm@39294
   138
            val (t', ps_idx'') = prepare t ps_idx';
wenzelm@39294
   139
          in (Abs (x, T', t'), ps_idx'') end
wenzelm@39294
   140
      | prepare (t $ u) ps_idx =
wenzelm@2957
   141
          let
wenzelm@39294
   142
            val (t', ps_idx') = prepare t ps_idx;
wenzelm@39294
   143
            val (u', ps_idx'') = prepare u ps_idx';
wenzelm@39294
   144
          in (t' $ u', ps_idx'') end;
wenzelm@2957
   145
wenzelm@39294
   146
    val (tm', (params', idx'')) = prepare tm (params, idx');
berghofe@32141
   147
  in (tm', (vparams', params', idx'')) end;
wenzelm@2957
   148
wenzelm@2957
   149
wenzelm@2957
   150
wenzelm@39296
   151
(** results **)
wenzelm@2957
   152
wenzelm@39294
   153
(* dereferenced views *)
wenzelm@2957
   154
wenzelm@39294
   155
fun deref tye (T as TVar (xi, _)) =
wenzelm@39294
   156
      (case Vartab.lookup tye xi of
wenzelm@39294
   157
        NONE => T
wenzelm@39294
   158
      | SOME U => deref tye U)
wenzelm@39294
   159
  | deref tye T = T;
wenzelm@39294
   160
wenzelm@39294
   161
fun add_parms tye T =
wenzelm@32146
   162
  (case deref tye T of
wenzelm@39294
   163
    Type (_, Ts) => fold (add_parms tye) Ts
wenzelm@39294
   164
  | TVar (xi, _) => if is_param xi then insert (op =) xi else I
wenzelm@32146
   165
  | _ => I);
wenzelm@2957
   166
wenzelm@39294
   167
fun add_names tye T =
wenzelm@32146
   168
  (case deref tye T of
wenzelm@39294
   169
    Type (_, Ts) => fold (add_names tye) Ts
wenzelm@39294
   170
  | TFree (x, _) => Name.declare x
wenzelm@39294
   171
  | TVar ((x, i), _) => if is_param (x, i) then I else Name.declare x);
wenzelm@2957
   172
wenzelm@2957
   173
wenzelm@39296
   174
(* finish -- standardize remaining parameters *)
wenzelm@2957
   175
wenzelm@39294
   176
fun finish ctxt tye (Ts, ts) =
wenzelm@39294
   177
  let
wenzelm@39294
   178
    val used =
wenzelm@39294
   179
      (fold o fold_types) (add_names tye) ts (fold (add_names tye) Ts (Variable.names_of ctxt));
wenzelm@39294
   180
    val parms = rev ((fold o fold_types) (add_parms tye) ts (fold (add_parms tye) Ts []));
wenzelm@39294
   181
    val names = Name.invents used ("?" ^ Name.aT) (length parms);
wenzelm@39294
   182
    val tab = Vartab.make (parms ~~ names);
wenzelm@2957
   183
wenzelm@39294
   184
    fun finish_typ T =
wenzelm@39294
   185
      (case deref tye T of
wenzelm@39294
   186
        Type (a, Ts) => Type (a, map finish_typ Ts)
wenzelm@39294
   187
      | U as TFree _ => U
wenzelm@39294
   188
      | U as TVar (xi, S) =>
wenzelm@39294
   189
          (case Vartab.lookup tab xi of
wenzelm@39294
   190
            NONE => U
wenzelm@39295
   191
          | SOME a => TVar ((a, 0), S)));
wenzelm@39294
   192
  in (map finish_typ Ts, map (Type.strip_constraints o Term.map_types finish_typ) ts) end;
wenzelm@2957
   193
wenzelm@2957
   194
wenzelm@39296
   195
(* fixate -- introduce fresh type variables *)
wenzelm@39296
   196
wenzelm@39296
   197
fun fixate ctxt ts =
wenzelm@39296
   198
  let
wenzelm@39296
   199
    fun subst_param (xi, S) (inst, used) =
wenzelm@39296
   200
      if is_param xi then
wenzelm@39296
   201
        let
wenzelm@39296
   202
          val [a] = Name.invents used Name.aT 1;
wenzelm@39296
   203
          val used' = Name.declare a used;
wenzelm@39296
   204
        in (((xi, S), TFree (a, S)) :: inst, used') end
wenzelm@39296
   205
      else (inst, used);
wenzelm@39296
   206
    val used = (fold o fold_types) Term.declare_typ_names ts (Variable.names_of ctxt);
wenzelm@39296
   207
    val (inst, _) = fold_rev subst_param (fold Term.add_tvars ts []) ([], used);
wenzelm@39296
   208
  in (map o map_types) (Term_Subst.instantiateT inst) ts end;
wenzelm@39296
   209
wenzelm@39296
   210
wenzelm@2957
   211
berghofe@32141
   212
(** order-sorted unification of types **)
wenzelm@2957
   213
wenzelm@39294
   214
exception NO_UNIFIER of string * typ Vartab.table;
wenzelm@2957
   215
wenzelm@39290
   216
fun unify ctxt pp =
wenzelm@2957
   217
  let
wenzelm@39290
   218
    val thy = ProofContext.theory_of ctxt;
wenzelm@39290
   219
    val arity_sorts = Type.arity_sorts pp (Sign.tsig_of thy);
wenzelm@39290
   220
wenzelm@39290
   221
wenzelm@2957
   222
    (* adjust sorts of parameters *)
wenzelm@2957
   223
wenzelm@19465
   224
    fun not_of_sort x S' S =
wenzelm@39290
   225
      "Variable " ^ x ^ "::" ^ Syntax.string_of_sort ctxt S' ^ " not of sort " ^
wenzelm@39290
   226
        Syntax.string_of_sort ctxt S;
wenzelm@2957
   227
berghofe@32141
   228
    fun meet (_, []) tye_idx = tye_idx
wenzelm@39294
   229
      | meet (Type (a, Ts), S) (tye_idx as (tye, _)) =
wenzelm@39291
   230
          meets (Ts, arity_sorts a S handle ERROR msg => raise NO_UNIFIER (msg, tye)) tye_idx
wenzelm@39294
   231
      | meet (TFree (x, S'), S) (tye_idx as (tye, _)) =
wenzelm@39290
   232
          if Sign.subsort thy (S', S) then tye_idx
berghofe@32141
   233
          else raise NO_UNIFIER (not_of_sort x S' S, tye)
wenzelm@39294
   234
      | meet (TVar (xi, S'), S) (tye_idx as (tye, idx)) =
wenzelm@39290
   235
          if Sign.subsort thy (S', S) then tye_idx
wenzelm@39294
   236
          else if is_param xi then
wenzelm@39294
   237
            (Vartab.update_new (xi, mk_param idx (Sign.inter_sort thy (S', S))) tye, idx + 1)
berghofe@32141
   238
          else raise NO_UNIFIER (not_of_sort (Term.string_of_vname xi) S' S, tye)
berghofe@32141
   239
    and meets (T :: Ts, S :: Ss) (tye_idx as (tye, _)) =
berghofe@32141
   240
          meets (Ts, Ss) (meet (deref tye T, S) tye_idx)
berghofe@32141
   241
      | meets _ tye_idx = tye_idx;
wenzelm@2957
   242
wenzelm@2957
   243
wenzelm@35013
   244
    (* occurs check and assignment *)
wenzelm@2957
   245
wenzelm@39294
   246
    fun occurs_check tye xi (TVar (xi', S)) =
wenzelm@39294
   247
          if xi = xi' then raise NO_UNIFIER ("Occurs check!", tye)
wenzelm@32146
   248
          else
wenzelm@39294
   249
            (case Vartab.lookup tye xi' of
berghofe@32141
   250
              NONE => ()
wenzelm@39294
   251
            | SOME T => occurs_check tye xi T)
wenzelm@39294
   252
      | occurs_check tye xi (Type (_, Ts)) = List.app (occurs_check tye xi) Ts
berghofe@32141
   253
      | occurs_check _ _ _ = ();
wenzelm@2957
   254
wenzelm@39294
   255
    fun assign xi (T as TVar (xi', _)) S env =
wenzelm@39294
   256
          if xi = xi' then env
wenzelm@39294
   257
          else env |> meet (T, S) |>> Vartab.update_new (xi, T)
wenzelm@39294
   258
      | assign xi T S (env as (tye, _)) =
wenzelm@39294
   259
          (occurs_check tye xi T; env |> meet (T, S) |>> Vartab.update_new (xi, T));
wenzelm@2957
   260
wenzelm@2957
   261
wenzelm@2957
   262
    (* unification *)
wenzelm@2957
   263
wenzelm@39286
   264
    fun show_tycon (a, Ts) =
wenzelm@39290
   265
      quote (Syntax.string_of_typ ctxt (Type (a, replicate (length Ts) dummyT)));
wenzelm@39286
   266
wenzelm@39294
   267
    fun unif (T1, T2) (env as (tye, _)) =
wenzelm@39294
   268
      (case pairself (`is_paramT o deref tye) (T1, T2) of
wenzelm@39294
   269
        ((true, TVar (xi, S)), (_, T)) => assign xi T S env
wenzelm@39294
   270
      | ((_, T), (true, TVar (xi, S))) => assign xi T S env
wenzelm@39294
   271
      | ((_, Type (a, Ts)), (_, Type (b, Us))) =>
wenzelm@2979
   272
          if a <> b then
wenzelm@39286
   273
            raise NO_UNIFIER
wenzelm@39286
   274
              ("Clash of types " ^ show_tycon (a, Ts) ^ " and " ^ show_tycon (b, Us), tye)
wenzelm@39294
   275
          else fold unif (Ts ~~ Us) env
wenzelm@39294
   276
      | ((_, T), (_, U)) => if T = U then env else raise NO_UNIFIER ("", tye));
wenzelm@2957
   277
wenzelm@2957
   278
  in unif end;
wenzelm@2957
   279
wenzelm@2957
   280
wenzelm@2957
   281
wenzelm@39296
   282
(** simple type inference **)
wenzelm@2957
   283
berghofe@32141
   284
(* infer *)
wenzelm@2957
   285
wenzelm@39290
   286
fun infer ctxt =
wenzelm@2957
   287
  let
wenzelm@39290
   288
    val pp = Syntax.pp ctxt;
wenzelm@39290
   289
wenzelm@39290
   290
wenzelm@2979
   291
    (* errors *)
wenzelm@2957
   292
berghofe@32141
   293
    fun prep_output tye bs ts Ts =
wenzelm@2957
   294
      let
wenzelm@39294
   295
        val (Ts_bTs', ts') = finish ctxt tye (Ts @ map snd bs, ts);
wenzelm@19012
   296
        val (Ts', Ts'') = chop (length Ts) Ts_bTs';
wenzelm@27263
   297
        fun prep t =
wenzelm@27263
   298
          let val xs = rev (Term.variant_frees t (rev (map fst bs ~~ Ts'')))
wenzelm@27263
   299
          in Term.subst_bounds (map Syntax.mark_boundT xs, t) end;
wenzelm@27263
   300
      in (map prep ts', Ts') end;
wenzelm@2979
   301
wenzelm@39291
   302
    fun err_loose i = error ("Loose bound variable: B." ^ string_of_int i);
wenzelm@2979
   303
wenzelm@39289
   304
    fun unif_failed msg =
wenzelm@39289
   305
      "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n\n";
wenzelm@39289
   306
berghofe@32141
   307
    fun err_appl msg tye bs t T u U =
wenzelm@39291
   308
      let val ([t', u'], [T', U']) = prep_output tye bs [t, u] [T, U]
wenzelm@39291
   309
      in error (unif_failed msg ^ Type.appl_error pp t' T' u' U' ^ "\n") end;
wenzelm@2979
   310
wenzelm@2979
   311
wenzelm@2979
   312
    (* main *)
wenzelm@2979
   313
wenzelm@39294
   314
    fun inf _ (Const (_, T)) tye_idx = (T, tye_idx)
wenzelm@39294
   315
      | inf _ (Free (_, T)) tye_idx = (T, tye_idx)
wenzelm@39294
   316
      | inf _ (Var (_, T)) tye_idx = (T, tye_idx)
wenzelm@39294
   317
      | inf bs (Bound i) tye_idx =
berghofe@32141
   318
          (snd (nth bs i handle Subscript => err_loose i), tye_idx)
wenzelm@39294
   319
      | inf bs (Abs (x, T, t)) tye_idx =
berghofe@32141
   320
          let val (U, tye_idx') = inf ((x, T) :: bs) t tye_idx
wenzelm@39294
   321
          in (T --> U, tye_idx') end
wenzelm@39294
   322
      | inf bs (t $ u) tye_idx =
wenzelm@2957
   323
          let
berghofe@32141
   324
            val (T, tye_idx') = inf bs t tye_idx;
berghofe@32141
   325
            val (U, (tye, idx)) = inf bs u tye_idx';
wenzelm@39294
   326
            val V = mk_param idx [];
wenzelm@39294
   327
            val tye_idx'' = unify ctxt pp (U --> V, T) (tye, idx + 1)
berghofe@32141
   328
              handle NO_UNIFIER (msg, tye') => err_appl msg tye' bs t T u U;
wenzelm@39292
   329
          in (V, tye_idx'') end;
wenzelm@2957
   330
wenzelm@2957
   331
  in inf [] end;
wenzelm@2957
   332
wenzelm@2957
   333
wenzelm@39296
   334
(* main interfaces *)
wenzelm@2957
   335
wenzelm@39296
   336
fun prepare ctxt const_type var_type raw_ts =
wenzelm@2957
   337
  let
wenzelm@22698
   338
    val get_type = the_default dummyT o var_type;
wenzelm@22698
   339
    val constrain_vars = Term.map_aterms
wenzelm@39288
   340
      (fn Free (x, T) => Type.constraint T (Free (x, get_type (x, ~1)))
wenzelm@39288
   341
        | Var (xi, T) => Type.constraint T (Var (xi, get_type xi))
wenzelm@22698
   342
        | t => t);
wenzelm@22698
   343
wenzelm@39290
   344
    val ts = burrow_types (Syntax.check_typs ctxt) raw_ts;
berghofe@32141
   345
    val (ts', (_, _, idx)) =
wenzelm@39294
   346
      fold_map (prepare_term const_type o constrain_vars) ts
berghofe@32141
   347
      (Vartab.empty, Vartab.empty, 0);
wenzelm@39296
   348
  in (idx, ts') end;
wenzelm@2957
   349
wenzelm@39296
   350
fun infer_types ctxt const_type var_type raw_ts =
wenzelm@39296
   351
  let
wenzelm@39296
   352
    val (idx, ts) = prepare ctxt const_type var_type raw_ts;
wenzelm@39296
   353
    val (tye, _) = fold (snd oo infer ctxt) ts (Vartab.empty, idx);
wenzelm@39296
   354
    val (_, ts') = finish ctxt tye ([], ts);
wenzelm@39296
   355
  in ts' end;
wenzelm@14788
   356
wenzelm@2957
   357
end;