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