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