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