src/Pure/type_infer.ML
author berghofe
Thu Jul 23 09:38:22 2009 +0200 (2009-07-23)
changeset 32141 31cd1ea502aa
parent 32033 f92df23c3305
child 32146 4937d9836824
permissions -rw-r--r--
Purely functional type inference.
     1 (*  Title:      Pure/type_infer.ML
     2     Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
     3 
     4 Simple type inference.
     5 *)
     6 
     7 signature TYPE_INFER =
     8 sig
     9   val anyT: sort -> typ
    10   val polymorphicT: typ -> typ
    11   val constrain: typ -> term -> term
    12   val is_param: indexname -> bool
    13   val param: int -> string * sort -> typ
    14   val paramify_vars: typ -> typ
    15   val paramify_dummies: typ -> int -> typ * int
    16   val fixate_params: Name.context -> term list -> term list
    17   val appl_error: Pretty.pp -> string -> term -> typ -> term -> typ -> string list
    18   val infer_types: Pretty.pp -> Type.tsig -> (typ list -> typ list) ->
    19     (string -> typ option) -> (indexname -> typ option) -> Name.context -> int ->
    20     term list -> term list
    21 end;
    22 
    23 structure TypeInfer: TYPE_INFER =
    24 struct
    25 
    26 
    27 (** type parameters and constraints **)
    28 
    29 fun anyT S = TFree ("'_dummy_", S);
    30 
    31 (*indicate polymorphic Vars*)
    32 fun polymorphicT T = Type ("_polymorphic_", [T]);
    33 
    34 val constrain = Syntax.type_constraint;
    35 
    36 
    37 (* user parameters *)
    38 
    39 fun is_param (x, _: int) = String.isPrefix "?" x;
    40 fun param i (x, S) = TVar (("?" ^ x, i), S);
    41 
    42 val paramify_vars =
    43   perhaps (Term_Subst.map_atypsT_option (fn TVar ((x, i), S) => SOME (param i (x, S)) | _ => NONE));
    44 
    45 val paramify_dummies =
    46   let
    47     fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
    48 
    49     fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
    50       | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
    51       | paramify (Type (a, Ts)) maxidx =
    52           let val (Ts', maxidx') = fold_map paramify Ts maxidx
    53           in (Type (a, Ts'), maxidx') end
    54       | paramify T maxidx = (T, maxidx);
    55   in paramify end;
    56 
    57 fun fixate_params name_context ts =
    58   let
    59     fun subst_param (xi, S) (inst, used) =
    60       if is_param xi then
    61         let
    62           val [a] = Name.invents used Name.aT 1;
    63           val used' = Name.declare a used;
    64         in (((xi, S), TFree (a, S)) :: inst, used') end
    65       else (inst, used);
    66     val name_context' = (fold o fold_types) Term.declare_typ_names ts name_context;
    67     val (inst, _) = fold_rev subst_param (fold Term.add_tvars ts []) ([], name_context');
    68   in (map o map_types) (Term_Subst.instantiateT inst) ts end;
    69 
    70 
    71 
    72 (** pretyps and preterms **)
    73 
    74 (*parameters may get instantiated, anything else is rigid*)
    75 datatype pretyp =
    76   PType of string * pretyp list |
    77   PTFree of string * sort |
    78   PTVar of indexname * sort |
    79   Param of int * sort;
    80 
    81 datatype preterm =
    82   PConst of string * pretyp |
    83   PFree of string * pretyp |
    84   PVar of indexname * pretyp |
    85   PBound of int |
    86   PAbs of string * pretyp * preterm |
    87   PAppl of preterm * preterm |
    88   Constraint of preterm * pretyp;
    89 
    90 
    91 (* utils *)
    92 
    93 fun deref tye (T as Param (i, S)) = (case Inttab.lookup tye i of
    94       NONE => T
    95     | SOME U => deref tye U)
    96   | deref tye T = T;
    97 
    98 fun fold_pretyps f (PConst (_, T)) x = f T x
    99   | fold_pretyps f (PFree (_, T)) x = f T x
   100   | fold_pretyps f (PVar (_, T)) x = f T x
   101   | fold_pretyps _ (PBound _) x = x
   102   | fold_pretyps f (PAbs (_, T, t)) x = fold_pretyps f t (f T x)
   103   | fold_pretyps f (PAppl (t, u)) x = fold_pretyps f u (fold_pretyps f t x)
   104   | fold_pretyps f (Constraint (t, T)) x = f T (fold_pretyps f t x);
   105 
   106 
   107 
   108 (** raw typs/terms to pretyps/preterms **)
   109 
   110 (* pretyp_of *)
   111 
   112 fun pretyp_of is_para typ params_idx =
   113   let
   114     val (params', idx) = fold_atyps
   115       (fn TVar (xi as (x, _), S) =>
   116           (fn ps_idx as (ps, idx) =>
   117             if is_para xi andalso not (Vartab.defined ps xi)
   118             then (Vartab.update (xi, Param (idx, S)) ps, idx + 1) else ps_idx)
   119         | _ => I) typ params_idx;
   120 
   121     fun pre_of (TVar (v as (xi, _))) idx =
   122           (case Vartab.lookup params' xi of
   123             NONE => PTVar v
   124           | SOME p => p, idx)
   125       | pre_of (TFree ("'_dummy_", S)) idx = (Param (idx, S), idx + 1)
   126       | pre_of (TFree v) idx = (PTFree v, idx)
   127       | pre_of (T as Type (a, Ts)) idx =
   128           if T = dummyT then (Param (idx, []), idx + 1)
   129           else
   130             let val (Ts', idx') = fold_map pre_of Ts idx
   131             in (PType (a, Ts'), idx') end;
   132 
   133     val (ptyp, idx') = pre_of typ idx;
   134   in (ptyp, (params', idx')) end;
   135 
   136 
   137 (* preterm_of *)
   138 
   139 fun preterm_of const_type is_para tm (vparams, params, idx) =
   140   let
   141     fun add_vparm xi (ps_idx as (ps, idx)) =
   142       if not (Vartab.defined ps xi) then
   143         (Vartab.update (xi, Param (idx, [])) ps, idx + 1)
   144       else ps_idx;
   145 
   146     val (vparams', idx') = fold_aterms
   147       (fn Var (_, Type ("_polymorphic_", _)) => I
   148         | Var (xi, _) => add_vparm xi
   149         | Free (x, _) => add_vparm (x, ~1)
   150         | _ => I)
   151       tm (vparams, idx);
   152     fun var_param xi = the (Vartab.lookup vparams' xi);
   153 
   154     val preT_of = pretyp_of is_para;
   155     fun polyT_of T idx = apsnd snd (pretyp_of (K true) T (Vartab.empty, idx));
   156 
   157     fun constraint T t ps =
   158       if T = dummyT then (t, ps)
   159       else
   160         let val (T', ps') = preT_of T ps
   161         in (Constraint (t, T'), ps') end;
   162 
   163     fun pre_of (Const (c, T)) (ps, idx) =
   164           (case const_type c of
   165             SOME U =>
   166               let val (pU, idx') = polyT_of U idx
   167               in constraint T (PConst (c, pU)) (ps, idx') end
   168           | NONE => raise TYPE ("No such constant: " ^ quote c, [], []))
   169       | pre_of (Var (xi, Type ("_polymorphic_", [T]))) (ps, idx) =
   170           let val (pT, idx') = polyT_of T idx
   171           in (PVar (xi, pT), (ps, idx')) end
   172       | pre_of (Var (xi, T)) ps_idx = constraint T (PVar (xi, var_param xi)) ps_idx
   173       | pre_of (Free (x, T)) ps_idx = constraint T (PFree (x, var_param (x, ~1))) ps_idx
   174       | pre_of (Const ("_type_constraint_", Type ("fun", [T, _])) $ t) ps_idx =
   175           pre_of t ps_idx |-> constraint T
   176       | pre_of (Bound i) ps_idx = (PBound i, ps_idx)
   177       | pre_of (Abs (x, T, t)) ps_idx =
   178           let
   179             val (T', ps_idx') = preT_of T ps_idx;
   180             val (t', ps_idx'') = pre_of t ps_idx';
   181           in (PAbs (x, T', t'), ps_idx'') end
   182       | pre_of (t $ u) ps_idx =
   183           let
   184             val (t', ps_idx') = pre_of t ps_idx;
   185             val (u', ps_idx'') = pre_of u ps_idx';
   186           in (PAppl (t', u'), ps_idx'') end;
   187 
   188     val (tm', (params', idx'')) = pre_of tm (params, idx');
   189   in (tm', (vparams', params', idx'')) end;
   190 
   191 
   192 
   193 (** pretyps/terms to typs/terms **)
   194 
   195 (* add_parms *)
   196 
   197 fun add_parmsT tye T = case deref tye T of
   198     PType (_, Ts) => fold (add_parmsT tye) Ts
   199   | Param (i, _) => insert (op =) i
   200   | _ => I;
   201 
   202 fun add_parms tye = fold_pretyps (add_parmsT tye);
   203 
   204 
   205 (* add_names *)
   206 
   207 fun add_namesT tye T = case deref tye T of
   208     PType (_, Ts) => fold (add_namesT tye) Ts
   209   | PTFree (x, _) => Name.declare x
   210   | PTVar ((x, _), _) => Name.declare x
   211   | Param _ => I;
   212 
   213 fun add_names tye = fold_pretyps (add_namesT tye);
   214 
   215 
   216 (* simple_typ/term_of *)
   217 
   218 fun simple_typ_of tye f T = case deref tye T of
   219     PType (a, Ts) => Type (a, map (simple_typ_of tye f) Ts)
   220   | PTFree v => TFree v
   221   | PTVar v => TVar v
   222   | Param (i, S) => TVar (f i, S);
   223 
   224 (*convert types, drop constraints*)
   225 fun simple_term_of tye f (PConst (c, T)) = Const (c, simple_typ_of tye f T)
   226   | simple_term_of tye f (PFree (x, T)) = Free (x, simple_typ_of tye f T)
   227   | simple_term_of tye f (PVar (xi, T)) = Var (xi, simple_typ_of tye f T)
   228   | simple_term_of tye f (PBound i) = Bound i
   229   | simple_term_of tye f (PAbs (x, T, t)) =
   230       Abs (x, simple_typ_of tye f T, simple_term_of tye f t)
   231   | simple_term_of tye f (PAppl (t, u)) =
   232       simple_term_of tye f t $ simple_term_of tye f u
   233   | simple_term_of tye f (Constraint (t, _)) = simple_term_of tye f t;
   234 
   235 
   236 (* typs_terms_of *)
   237 
   238 fun typs_terms_of tye used maxidx (Ts, ts) =
   239   let
   240     val used' = fold (add_names tye) ts (fold (add_namesT tye) Ts used);
   241     val parms = rev (fold (add_parms tye) ts (fold (add_parmsT tye) Ts []));
   242     val names = Name.invents used' ("?" ^ Name.aT) (length parms);
   243     val tab = Inttab.make (parms ~~ names);
   244     fun f i = (the (Inttab.lookup tab i), maxidx + 1);
   245   in (map (simple_typ_of tye f) Ts, map (simple_term_of tye f) ts) end;
   246 
   247 
   248 
   249 (** order-sorted unification of types **)
   250 
   251 exception NO_UNIFIER of string * pretyp Inttab.table;
   252 
   253 fun unify pp tsig =
   254   let
   255 
   256     (* adjust sorts of parameters *)
   257 
   258     fun not_of_sort x S' S =
   259       "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
   260         Pretty.string_of_sort pp S;
   261 
   262     fun meet (_, []) tye_idx = tye_idx
   263       | meet (Param (i, S'), S) (tye_idx as (tye, idx)) =
   264           if Type.subsort tsig (S', S) then tye_idx
   265           else (Inttab.update_new (i,
   266             Param (idx, Type.inter_sort tsig (S', S))) tye, idx + 1)
   267       | meet (PType (a, Ts), S) (tye_idx as (tye, _)) =
   268           meets (Ts, Type.arity_sorts pp tsig a S
   269             handle ERROR msg => raise NO_UNIFIER (msg, tye)) tye_idx
   270       | meet (PTFree (x, S'), S) (tye_idx as (tye, _)) =
   271           if Type.subsort tsig (S', S) then tye_idx
   272           else raise NO_UNIFIER (not_of_sort x S' S, tye)
   273       | meet (PTVar (xi, S'), S) (tye_idx as (tye, _)) =
   274           if Type.subsort tsig (S', S) then tye_idx
   275           else raise NO_UNIFIER (not_of_sort (Term.string_of_vname xi) S' S, tye)
   276     and meets (T :: Ts, S :: Ss) (tye_idx as (tye, _)) =
   277           meets (Ts, Ss) (meet (deref tye T, S) tye_idx)
   278       | meets _ tye_idx = tye_idx;
   279 
   280 
   281     (* occurs check and assigment *)
   282 
   283     fun occurs_check tye i (Param (i', S)) =
   284           if i = i' then raise NO_UNIFIER ("Occurs check!", tye)
   285           else (case Inttab.lookup tye i' of
   286               NONE => ()
   287             | SOME T => occurs_check tye i T)
   288       | occurs_check tye i (PType (_, Ts)) = List.app (occurs_check tye i) Ts
   289       | occurs_check _ _ _ = ();
   290 
   291     fun assign i (T as Param (i', _)) S (tye_idx as (tye, idx)) =
   292           if i = i' then tye_idx
   293           else meet (T, S) (Inttab.update_new (i, T) tye, idx)
   294       | assign i T S (tye, idx) =
   295           (occurs_check tye i T; meet (T, S) (Inttab.update_new (i, T) tye, idx));
   296 
   297 
   298     (* unification *)
   299 
   300     fun unif (T1, T2) (tye_idx as (tye, idx)) = case (deref tye T1, deref tye T2) of
   301         (Param (i, S), T) => assign i T S tye_idx
   302       | (T, Param (i, S)) => assign i T S tye_idx
   303       | (PType (a, Ts), PType (b, Us)) =>
   304           if a <> b then
   305             raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b, tye)
   306           else fold unif (Ts ~~ Us) tye_idx
   307       | (T, U) => if T = U then tye_idx else raise NO_UNIFIER ("", tye);
   308 
   309   in unif end;
   310 
   311 
   312 
   313 (** type inference **)
   314 
   315 (* appl_error *)
   316 
   317 fun appl_error pp why t T u U =
   318  ["Type error in application: " ^ why,
   319   "",
   320   Pretty.string_of (Pretty.block
   321     [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
   322       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
   323   Pretty.string_of (Pretty.block
   324     [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
   325       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
   326   ""];
   327 
   328 
   329 (* infer *)
   330 
   331 fun infer pp tsig =
   332   let
   333     (* errors *)
   334 
   335     fun unif_failed msg =
   336       "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
   337 
   338     fun prep_output tye bs ts Ts =
   339       let
   340         val (Ts_bTs', ts') = typs_terms_of tye Name.context ~1 (Ts @ map snd bs, ts);
   341         val (Ts', Ts'') = chop (length Ts) Ts_bTs';
   342         fun prep t =
   343           let val xs = rev (Term.variant_frees t (rev (map fst bs ~~ Ts'')))
   344           in Term.subst_bounds (map Syntax.mark_boundT xs, t) end;
   345       in (map prep ts', Ts') end;
   346 
   347     fun err_loose i =
   348       raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
   349 
   350     fun err_appl msg tye bs t T u U =
   351       let
   352         val ([t', u'], [T', U']) = prep_output tye bs [t, u] [T, U];
   353         val why =
   354           (case T' of
   355             Type ("fun", _) => "Incompatible operand type"
   356           | _ => "Operator not of function type");
   357         val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
   358       in raise TYPE (text, [T', U'], [t', u']) end;
   359 
   360     fun err_constraint msg tye bs t T U =
   361       let
   362         val ([t'], [T', U']) = prep_output tye bs [t] [T, U];
   363         val text = cat_lines
   364          [unif_failed msg,
   365           "Cannot meet type constraint:", "",
   366           Pretty.string_of (Pretty.block
   367            [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
   368             Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
   369           Pretty.string_of (Pretty.block
   370            [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
   371       in raise TYPE (text, [T', U'], [t']) end;
   372 
   373 
   374     (* main *)
   375 
   376     val unif = unify pp tsig;
   377 
   378     fun inf _ (PConst (_, T)) tye_idx = (T, tye_idx)
   379       | inf _ (PFree (_, T)) tye_idx = (T, tye_idx)
   380       | inf _ (PVar (_, T)) tye_idx = (T, tye_idx)
   381       | inf bs (PBound i) tye_idx =
   382           (snd (nth bs i handle Subscript => err_loose i), tye_idx)
   383       | inf bs (PAbs (x, T, t)) tye_idx =
   384           let val (U, tye_idx') = inf ((x, T) :: bs) t tye_idx
   385           in (PType ("fun", [T, U]), tye_idx') end
   386       | inf bs (PAppl (t, u)) tye_idx =
   387           let
   388             val (T, tye_idx') = inf bs t tye_idx;
   389             val (U, (tye, idx)) = inf bs u tye_idx';
   390             val V = Param (idx, []);
   391             val U_to_V = PType ("fun", [U, V]);
   392             val tye_idx'' = unif (U_to_V, T) (tye, idx + 1)
   393               handle NO_UNIFIER (msg, tye') => err_appl msg tye' bs t T u U;
   394           in (V, tye_idx'') end
   395       | inf bs (Constraint (t, U)) tye_idx =
   396           let val (T, tye_idx') = inf bs t tye_idx in
   397             (T,
   398              unif (T, U) tye_idx'
   399              handle NO_UNIFIER (msg, tye) => err_constraint msg tye bs t T U)
   400           end;
   401 
   402   in inf [] end;
   403 
   404 
   405 (* infer_types *)
   406 
   407 fun infer_types pp tsig check_typs const_type var_type used maxidx raw_ts =
   408   let
   409     (*constrain vars*)
   410     val get_type = the_default dummyT o var_type;
   411     val constrain_vars = Term.map_aterms
   412       (fn Free (x, T) => constrain T (Free (x, get_type (x, ~1)))
   413         | Var (xi, T) => constrain T (Var (xi, get_type xi))
   414         | t => t);
   415 
   416     (*convert to preterms*)
   417     val ts = burrow_types check_typs raw_ts;
   418     val (ts', (_, _, idx)) =
   419       fold_map (preterm_of const_type is_param o constrain_vars) ts
   420       (Vartab.empty, Vartab.empty, 0);
   421 
   422     (*do type inference*)
   423     val (tye, _) = fold (snd oo infer pp tsig) ts' (Inttab.empty, idx);
   424   in #2 (typs_terms_of tye used maxidx ([], ts')) end;
   425 
   426 end;