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