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