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