src/Pure/type_infer.ML
author wenzelm
Mon Feb 06 20:59:06 2006 +0100 (2006-02-06)
changeset 18939 18e2a2676d80
parent 18339 64cb06a0bb50
child 18964 67f572e03236
permissions -rw-r--r--
tuned;
     1 (*  Title:      Pure/type_infer.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
     4 
     5 Type inference.
     6 *)
     7 
     8 signature TYPE_INFER =
     9 sig
    10   val anyT: sort -> typ
    11   val logicT: typ
    12   val mixfixT: Syntax.mixfix -> typ
    13   val polymorphicT: typ -> typ
    14   val appl_error: Pretty.pp -> string -> term -> typ -> term -> typ -> string list
    15   val constrain: term -> typ -> term
    16   val param: int -> string * sort -> typ
    17   val paramify_dummies: typ -> int -> typ * int
    18   val get_sort: Type.tsig -> (indexname -> sort option) -> (sort -> sort)
    19     -> (indexname * sort) list -> indexname -> sort
    20   val infer_types: Pretty.pp
    21     -> Type.tsig -> (string -> typ option) -> (indexname -> typ option)
    22     -> (indexname -> sort option) -> (string -> string) -> (typ -> typ)
    23     -> (sort -> sort) -> string list -> bool -> typ list -> term list
    24     -> term list * (indexname * typ) list
    25 end;
    26 
    27 structure TypeInfer: TYPE_INFER =
    28 struct
    29 
    30 
    31 (** term encodings **)
    32 
    33 (*
    34   Flavours of term encodings:
    35 
    36     parse trees (type term):
    37       A very complicated structure produced by the syntax module's
    38       read functions.  Encodes types and sorts as terms; may contain
    39       explicit constraints and partial typing information (where
    40       dummies serve as wildcards).
    41 
    42       Parse trees are INTERNAL! Users should never encounter them,
    43       except in parse / print translation functions.
    44 
    45     raw terms (type term):
    46       Provide the user interface to type inferences.  They may contain
    47       partial type information (dummies are wildcards) or explicit
    48       type constraints (introduced via constrain: term -> typ ->
    49       term).
    50 
    51       The type inference function also lets users specify a certain
    52       subset of TVars to be treated as non-rigid inference parameters.
    53 
    54     preterms (type preterm):
    55       The internal representation for type inference.
    56 
    57     well-typed term (type term):
    58       Fully typed lambda terms to be accepted by appropriate
    59       certification functions.
    60 *)
    61 
    62 
    63 
    64 (** pretyps and preterms **)
    65 
    66 (*links to parameters may get instantiated, anything else is rigid*)
    67 datatype pretyp =
    68   PType of string * pretyp list |
    69   PTFree of string * sort |
    70   PTVar of indexname * sort |
    71   Param of sort |
    72   Link of pretyp ref;
    73 
    74 datatype preterm =
    75   PConst of string * pretyp |
    76   PFree of string * pretyp |
    77   PVar of indexname * pretyp |
    78   PBound of int |
    79   PAbs of string * pretyp * preterm |
    80   PAppl of preterm * preterm |
    81   Constraint of preterm * pretyp;
    82 
    83 
    84 (* utils *)
    85 
    86 val mk_param = Link o ref o Param;
    87 
    88 fun deref (T as Link (ref (Param _))) = T
    89   | deref (Link (ref T)) = deref T
    90   | deref T = T;
    91 
    92 fun fold_pretyps f (PConst (_, T)) x = f T x
    93   | fold_pretyps f (PFree (_, T)) x = f T x
    94   | fold_pretyps f (PVar (_, T)) x = f T x
    95   | fold_pretyps _ (PBound _) x = x
    96   | fold_pretyps f (PAbs (_, T, t)) x = fold_pretyps f t (f T x)
    97   | fold_pretyps f (PAppl (t, u)) x = fold_pretyps f u (fold_pretyps f t x)
    98   | fold_pretyps f (Constraint (t, T)) x = f T (fold_pretyps f t x);
    99 
   100 
   101 
   102 (** raw typs/terms to pretyps/preterms **)
   103 
   104 (* pretyp(s)_of *)
   105 
   106 fun anyT S = TFree ("'_dummy_", S);
   107 val logicT = anyT [];
   108 
   109 fun mixfixT (Binder _) = (logicT --> logicT) --> logicT
   110   | mixfixT mx = replicate (Syntax.mixfix_args mx) logicT ---> logicT;
   111 
   112 
   113 (*indicate polymorphic Vars*)
   114 fun polymorphicT T = Type ("_polymorphic_", [T]);
   115 
   116 fun pretyp_of is_param (params, typ) =
   117   let
   118     fun add_parms (TVar (xi as (x, _), S)) ps =
   119           if is_param xi andalso not (AList.defined (op =) ps xi)
   120           then (xi, mk_param S) :: ps else ps
   121       | add_parms (TFree _) ps = ps
   122       | add_parms (Type (_, Ts)) ps = fold add_parms Ts ps;
   123 
   124     val params' = add_parms typ params;
   125 
   126     fun pre_of (TVar (v as (xi, _))) =
   127           (case AList.lookup (op =) params' xi of
   128             NONE => PTVar v
   129           | SOME p => p)
   130       | pre_of (TFree ("'_dummy_", S)) = mk_param S
   131       | pre_of (TFree v) = PTFree v
   132       | pre_of (T as Type (a, Ts)) =
   133           if T = dummyT then mk_param []
   134           else PType (a, map pre_of Ts);
   135   in (params', pre_of typ) end;
   136 
   137 fun pretyps_of is_param = foldl_map (pretyp_of is_param);
   138 
   139 
   140 (* preterm(s)_of *)
   141 
   142 fun preterm_of const_type is_param ((vparams, params), tm) =
   143   let
   144     fun add_vparm (ps, xi) =
   145       if not (AList.defined (op =) ps xi) then
   146         (xi, mk_param []) :: ps
   147       else ps;
   148 
   149     fun add_vparms (ps, Var (xi, Type ("_polymorphic_", _))) = ps
   150       | add_vparms (ps, Var (xi, _)) = add_vparm (ps, xi)
   151       | add_vparms (ps, Free (x, _)) = add_vparm (ps, (x, ~1))
   152       | add_vparms (ps, Abs (_, _, t)) = add_vparms (ps, t)
   153       | add_vparms (ps, t $ u) = add_vparms (add_vparms (ps, t), u)
   154       | add_vparms (ps, _) = ps;
   155 
   156     val vparams' = add_vparms (vparams, tm);
   157     fun var_param xi = (the o AList.lookup (op =) vparams') xi;
   158 
   159 
   160     val preT_of = pretyp_of is_param;
   161 
   162     fun constrain (ps, t) T =
   163       if T = dummyT then (ps, t)
   164       else
   165         let val (ps', T') = preT_of (ps, T)
   166         in (ps', Constraint (t, T')) end;
   167 
   168     fun pre_of (ps, Const (c, T)) =
   169           (case const_type c of
   170             SOME U => constrain (ps, PConst (c, snd (pretyp_of (K true) ([], U)))) T
   171           | NONE => raise TYPE ("No such constant: " ^ quote c, [], []))
   172       | pre_of (ps, Var (xi, Type ("_polymorphic_", [T]))) =
   173           (ps, PVar (xi, snd (pretyp_of (K true) ([], T))))
   174       | pre_of (ps, Var (xi, T)) = constrain (ps, PVar (xi, var_param xi)) T
   175       | pre_of (ps, Free (x, T)) = constrain (ps, PFree (x, var_param (x, ~1))) T
   176       | pre_of (ps, Const ("_type_constraint_", T) $ t) = constrain (pre_of (ps, t)) T
   177       | pre_of (ps, Bound i) = (ps, PBound i)
   178       | pre_of (ps, Abs (x, T, t)) =
   179           let
   180             val (ps', T') = preT_of (ps, T);
   181             val (ps'', t') = pre_of (ps', t);
   182           in (ps'', PAbs (x, T', t')) end
   183       | pre_of (ps, t $ u) =
   184           let
   185             val (ps', t') = pre_of (ps, t);
   186             val (ps'', u') = pre_of (ps', u);
   187           in (ps'', PAppl (t', u')) end;
   188 
   189     val (params', tm') = pre_of (params, tm);
   190   in ((vparams', params'), tm') end;
   191 
   192 fun preterms_of const_type is_param = foldl_map (preterm_of const_type is_param);
   193 
   194 
   195 
   196 (** pretyps/terms to typs/terms **)
   197 
   198 (* add_parms *)
   199 
   200 fun add_parmsT (PType (_, Ts)) rs = fold add_parmsT Ts rs
   201   | add_parmsT (Link (r as ref (Param _))) rs = r ins rs
   202   | add_parmsT (Link (ref T)) rs = add_parmsT T rs
   203   | add_parmsT _ rs = rs;
   204 
   205 val add_parms = fold_pretyps add_parmsT;
   206 
   207 
   208 (* add_names *)
   209 
   210 fun add_namesT (PType (_, Ts)) xs = fold add_namesT Ts xs
   211   | add_namesT (PTFree (x, _)) xs = x ins_string xs
   212   | add_namesT (PTVar ((x, _), _)) xs = x ins_string xs
   213   | add_namesT (Link (ref T)) xs = add_namesT T xs
   214   | add_namesT (Param _) xs = xs;
   215 
   216 val add_names = fold_pretyps add_namesT;
   217 
   218 
   219 (* simple_typ/term_of *)
   220 
   221 (*deref links, fail on params*)
   222 fun simple_typ_of (PType (a, Ts)) = Type (a, map simple_typ_of Ts)
   223   | simple_typ_of (PTFree v) = TFree v
   224   | simple_typ_of (PTVar v) = TVar v
   225   | simple_typ_of (Link (ref T)) = simple_typ_of T
   226   | simple_typ_of (Param _) = sys_error "simple_typ_of: illegal Param";
   227 
   228 (*convert types, drop constraints*)
   229 fun simple_term_of (PConst (c, T)) = Const (c, simple_typ_of T)
   230   | simple_term_of (PFree (x, T)) = Free (x, simple_typ_of T)
   231   | simple_term_of (PVar (xi, T)) = Var (xi, simple_typ_of T)
   232   | simple_term_of (PBound i) = Bound i
   233   | simple_term_of (PAbs (x, T, t)) = Abs (x, simple_typ_of T, simple_term_of t)
   234   | simple_term_of (PAppl (t, u)) = simple_term_of t $ simple_term_of u
   235   | simple_term_of (Constraint (t, _)) = simple_term_of t;
   236 
   237 
   238 (* typs_terms_of *)                             (*DESTRUCTIVE*)
   239 
   240 fun typs_terms_of used mk_var prfx (Ts, ts) =
   241   let
   242     fun elim (r as ref (Param S), x) = r := mk_var (x, S)
   243       | elim _ = ();
   244 
   245     val used' = fold add_names ts (fold add_namesT Ts used);
   246     val parms = rev (fold add_parms ts (fold add_parmsT Ts []));
   247     val names = Term.invent_names used' (prfx ^ "'a") (length parms);
   248   in
   249     ListPair.app elim (parms, names);
   250     (map simple_typ_of Ts, map simple_term_of ts)
   251   end;
   252 
   253 
   254 
   255 (** order-sorted unification of types **)       (*DESTRUCTIVE*)
   256 
   257 exception NO_UNIFIER of string;
   258 
   259 
   260 fun unify pp classes arities =
   261   let
   262 
   263     (* adjust sorts of parameters *)
   264 
   265     fun not_in_sort x S' S =
   266       "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
   267         Pretty.string_of_sort pp S;
   268 
   269     fun no_domain (a, c) = "No way to get " ^ Pretty.string_of_arity pp (a, [], [c]);
   270 
   271     fun meet (_, []) = ()
   272       | meet (Link (r as (ref (Param S'))), S) =
   273           if Sorts.sort_le classes (S', S) then ()
   274           else r := mk_param (Sorts.inter_sort classes (S', S))
   275       | meet (Link (ref T), S) = meet (T, S)
   276       | meet (PType (a, Ts), S) =
   277           ListPair.app meet (Ts, Sorts.mg_domain (classes, arities) a S
   278             handle Sorts.DOMAIN ac => raise NO_UNIFIER (no_domain ac))
   279       | meet (PTFree (x, S'), S) =
   280           if Sorts.sort_le classes (S', S) then ()
   281           else raise NO_UNIFIER (not_in_sort x S' S)
   282       | meet (PTVar (xi, S'), S) =
   283           if Sorts.sort_le classes (S', S) then ()
   284           else raise NO_UNIFIER (not_in_sort (Syntax.string_of_vname xi) S' S)
   285       | meet (Param _, _) = sys_error "meet";
   286 
   287 
   288     (* occurs check and assigment *)
   289 
   290     fun occurs_check r (Link (r' as ref T)) =
   291           if r = r' then raise NO_UNIFIER "Occurs check!"
   292           else occurs_check r T
   293       | occurs_check r (PType (_, Ts)) = List.app (occurs_check r) Ts
   294       | occurs_check _ _ = ();
   295 
   296     fun assign r T S =
   297       (case deref T of
   298         T' as Link (r' as ref (Param _)) =>
   299           if r = r' then () else (meet (T', S); r := T')
   300       | T' => (occurs_check r T'; meet (T', S); r := T'));
   301 
   302 
   303     (* unification *)
   304 
   305     fun unif (Link (r as ref (Param S)), T) = assign r T S
   306       | unif (T, Link (r as ref (Param S))) = assign r T S
   307       | unif (Link (ref T), U) = unif (T, U)
   308       | unif (T, Link (ref U)) = unif (T, U)
   309       | unif (PType (a, Ts), PType (b, Us)) =
   310           if a <> b then
   311             raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b)
   312           else ListPair.app unif (Ts, Us)
   313       | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
   314 
   315   in unif end;
   316 
   317 
   318 
   319 (** type inference **)
   320 
   321 fun appl_error pp why t T u U =
   322  ["Type error in application: " ^ why,
   323   "",
   324   Pretty.string_of (Pretty.block
   325     [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
   326       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
   327   Pretty.string_of (Pretty.block
   328     [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
   329       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
   330   ""];
   331 
   332 
   333 (* infer *)                                     (*DESTRUCTIVE*)
   334 
   335 fun infer pp classes arities =
   336   let
   337     (* errors *)
   338 
   339     fun unif_failed msg =
   340       "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
   341 
   342     fun prep_output bs ts Ts =
   343       let
   344         val (Ts_bTs', ts') = typs_terms_of [] PTFree "??" (Ts @ map snd bs, ts);
   345         val (Ts',Ts'') = Library.splitAt(length Ts, Ts_bTs');
   346         val xs = map Free (map fst bs ~~ Ts'');
   347         val ts'' = map (fn t => subst_bounds (xs, t)) ts';
   348       in (ts'', Ts') end;
   349 
   350     fun err_loose i =
   351       raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
   352 
   353     fun err_appl msg bs t T u U =
   354       let
   355         val ([t', u'], [T', U']) = prep_output bs [t, u] [T, U];
   356         val why =
   357           (case T' of
   358             Type ("fun", _) => "Incompatible operand type"
   359           | _ => "Operator not of function type");
   360         val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
   361       in raise TYPE (text, [T', U'], [t', u']) end;
   362 
   363     fun err_constraint msg bs t T U =
   364       let
   365         val ([t'], [T', U']) = prep_output bs [t] [T, U];
   366         val text = cat_lines
   367          [unif_failed msg,
   368           "Cannot meet type constraint:", "",
   369           Pretty.string_of (Pretty.block
   370            [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
   371             Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
   372           Pretty.string_of (Pretty.block
   373            [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
   374       in raise TYPE (text, [T', U'], [t']) end;
   375 
   376 
   377     (* main *)
   378 
   379     val unif = unify pp classes arities;
   380 
   381     fun inf _ (PConst (_, T)) = T
   382       | inf _ (PFree (_, T)) = T
   383       | inf _ (PVar (_, T)) = T
   384       | inf bs (PBound i) = snd (List.nth (bs, i) handle Subscript => err_loose i)
   385       | inf bs (PAbs (x, T, t)) = PType ("fun", [T, inf ((x, T) :: bs) t])
   386       | inf bs (PAppl (t, u)) =
   387           let
   388             val T = inf bs t;
   389             val U = inf bs u;
   390             val V = mk_param [];
   391             val U_to_V = PType ("fun", [U, V]);
   392             val _ = unif (U_to_V, T) handle NO_UNIFIER msg => err_appl msg bs t T u U;
   393           in V end
   394       | inf bs (Constraint (t, U)) =
   395           let val T = inf bs t in
   396             unif (T, U) handle NO_UNIFIER msg => err_constraint msg bs t T U;
   397             T
   398           end;
   399 
   400   in inf [] end;
   401 
   402 
   403 (* basic_infer_types *)
   404 
   405 fun basic_infer_types pp const_type classes arities used freeze is_param ts Ts =
   406   let
   407     (*convert to preterms/typs*)
   408     val (Tps, Ts') = pretyps_of (K true) ([], Ts);
   409     val ((vps, ps), ts') = preterms_of const_type is_param (([], Tps), ts);
   410 
   411     (*run type inference*)
   412     val tTs' = ListPair.map Constraint (ts', Ts');
   413     val _ = List.app (fn t => (infer pp classes arities t; ())) tTs';
   414 
   415     (*collect result unifier*)
   416     fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); NONE)
   417       | ch_var xi_T = SOME xi_T;
   418     val env = List.mapPartial ch_var Tps;
   419 
   420     (*convert back to terms/typs*)
   421     val mk_var =
   422       if freeze then PTFree
   423       else (fn (x, S) => PTVar ((x, 0), S));
   424     val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
   425     val final_env = map (apsnd simple_typ_of) env;
   426   in (final_ts, final_Ts, final_env) end;
   427 
   428 
   429 
   430 (** type inference **)
   431 
   432 (* user constraints *)
   433 
   434 fun constrain t T =
   435   if T = dummyT then t
   436   else Const ("_type_constraint_", T) $ t;
   437 
   438 
   439 (* user parameters *)
   440 
   441 fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
   442 fun param i (x, S) = TVar (("?" ^ x, i), S);
   443 
   444 val paramify_dummies =
   445   let
   446     fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
   447 
   448     fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
   449       | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
   450       | paramify (Type (a, Ts)) maxidx =
   451           let val (Ts', maxidx') = fold_map paramify Ts maxidx
   452           in (Type (a, Ts'), maxidx') end
   453       | paramify T maxidx = (T, maxidx);
   454   in paramify end;
   455 
   456 
   457 (* decode sort constraints *)
   458 
   459 fun get_sort tsig def_sort map_sort raw_env =
   460   let
   461     fun eq ((xi: indexname, S), (xi', S')) =
   462       xi = xi' andalso Type.eq_sort tsig (S, S');
   463 
   464     val env = gen_distinct eq (map (apsnd map_sort) raw_env);
   465     val _ = (case gen_duplicates (eq_fst (op =)) env of [] => ()
   466       | dups => error ("Inconsistent sort constraints for type variable(s) "
   467           ^ commas_quote (map (Syntax.string_of_vname' o fst) dups)));
   468 
   469     fun get xi =
   470       (case (AList.lookup (op =) env xi, def_sort xi) of
   471         (NONE, NONE) => Type.defaultS tsig
   472       | (NONE, SOME S) => S
   473       | (SOME S, NONE) => S
   474       | (SOME S, SOME S') =>
   475           if Type.eq_sort tsig (S, S') then S'
   476           else error ("Sort constraint inconsistent with default for type variable " ^
   477             quote (Syntax.string_of_vname' xi)));
   478   in get end;
   479 
   480 
   481 (* decode_types -- transform parse tree into raw term *)
   482 
   483 fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
   484   let
   485     fun get_type xi = the_default dummyT (def_type xi);
   486     fun is_free x = is_some (def_type (x, ~1));
   487     val raw_env = Syntax.raw_term_sorts tm;
   488     val sort_of = get_sort tsig def_sort map_sort raw_env;
   489 
   490     val certT = Type.cert_typ tsig o map_type;
   491     fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
   492 
   493     fun decode (Const ("_constrain", _) $ t $ typ) =
   494           constrain (decode t) (decodeT typ)
   495       | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
   496           if T = dummyT then Abs (x, decodeT typ, decode t)
   497           else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
   498       | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
   499       | decode (t $ u) = decode t $ decode u
   500       | decode (Free (x, T)) =
   501           let val c = map_const x in
   502             if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
   503               Const (c, certT T)
   504             else if T = dummyT then Free (x, get_type (x, ~1))
   505             else constrain (Free (x, certT T)) (get_type (x, ~1))
   506           end
   507       | decode (Var (xi, T)) =
   508           if T = dummyT then Var (xi, get_type xi)
   509           else constrain (Var (xi, certT T)) (get_type xi)
   510       | decode (t as Bound _) = t
   511       | decode (Const (c, T)) = Const (map_const c, certT T);
   512   in decode tm end;
   513 
   514 
   515 (* infer_types *)
   516 
   517 (*Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
   518   unifies with Ti (for i=1,...,n).
   519 
   520   tsig: type signature
   521   const_type: name mapping and signature lookup
   522   def_type: partial map from indexnames to types (constrains Frees and Vars)
   523   def_sort: partial map from indexnames to sorts (constrains TFrees and TVars)
   524   used: list of already used type variables
   525   freeze: if true then generated parameters are turned into TFrees, else TVars*)
   526 
   527 fun infer_types pp tsig const_type def_type def_sort
   528     map_const map_type map_sort used freeze pat_Ts raw_ts =
   529   let
   530     val {classes, arities, ...} = Type.rep_tsig tsig;
   531     val pat_Ts' = map (Type.cert_typ tsig) pat_Ts;
   532     val is_const = is_some o const_type;
   533     val raw_ts' =
   534       map (decode_types tsig is_const def_type def_sort map_const map_type map_sort) raw_ts;
   535     val (ts, Ts, unifier) = basic_infer_types pp const_type
   536       (#2 classes) arities used freeze is_param raw_ts' pat_Ts';
   537   in (ts, unifier) end;
   538 
   539 end;