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