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