src/Pure/type_infer.ML
author wenzelm
Tue Jul 11 12:17:01 2006 +0200 (2006-07-11)
changeset 20076 def4ad161528
parent 19577 fdb3642feb49
child 20161 b8b1d4a380aa
permissions -rw-r--r--
Name.invent_list;
     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_", Type ("fun", [T, _])) $ t) =
   177           constrain (pre_of (ps, t)) T
   178       | pre_of (ps, Bound i) = (ps, PBound i)
   179       | pre_of (ps, Abs (x, T, t)) =
   180           let
   181             val (ps', T') = preT_of (ps, T);
   182             val (ps'', t') = pre_of (ps', t);
   183           in (ps'', PAbs (x, T', t')) end
   184       | pre_of (ps, t $ u) =
   185           let
   186             val (ps', t') = pre_of (ps, t);
   187             val (ps'', u') = pre_of (ps', u);
   188           in (ps'', PAppl (t', u')) end;
   189 
   190     val (params', tm') = pre_of (params, tm);
   191   in ((vparams', params'), tm') end;
   192 
   193 fun preterms_of const_type is_param = foldl_map (preterm_of const_type is_param);
   194 
   195 
   196 
   197 (** pretyps/terms to typs/terms **)
   198 
   199 (* add_parms *)
   200 
   201 fun add_parmsT (PType (_, Ts)) rs = fold add_parmsT Ts rs
   202   | add_parmsT (Link (r as ref (Param _))) rs = r ins rs
   203   | add_parmsT (Link (ref T)) rs = add_parmsT T rs
   204   | add_parmsT _ rs = rs;
   205 
   206 val add_parms = fold_pretyps add_parmsT;
   207 
   208 
   209 (* add_names *)
   210 
   211 fun add_namesT (PType (_, Ts)) xs = fold add_namesT Ts xs
   212   | add_namesT (PTFree (x, _)) xs = x ins_string xs
   213   | add_namesT (PTVar ((x, _), _)) xs = x ins_string xs
   214   | add_namesT (Link (ref T)) xs = add_namesT T xs
   215   | add_namesT (Param _) xs = xs;
   216 
   217 val add_names = fold_pretyps add_namesT;
   218 
   219 
   220 (* simple_typ/term_of *)
   221 
   222 (*deref links, fail on params*)
   223 fun simple_typ_of (PType (a, Ts)) = Type (a, map simple_typ_of Ts)
   224   | simple_typ_of (PTFree v) = TFree v
   225   | simple_typ_of (PTVar v) = TVar v
   226   | simple_typ_of (Link (ref T)) = simple_typ_of T
   227   | simple_typ_of (Param _) = sys_error "simple_typ_of: illegal Param";
   228 
   229 (*convert types, drop constraints*)
   230 fun simple_term_of (PConst (c, T)) = Const (c, simple_typ_of T)
   231   | simple_term_of (PFree (x, T)) = Free (x, simple_typ_of T)
   232   | simple_term_of (PVar (xi, T)) = Var (xi, simple_typ_of T)
   233   | simple_term_of (PBound i) = Bound i
   234   | simple_term_of (PAbs (x, T, t)) = Abs (x, simple_typ_of T, simple_term_of t)
   235   | simple_term_of (PAppl (t, u)) = simple_term_of t $ simple_term_of u
   236   | simple_term_of (Constraint (t, _)) = simple_term_of t;
   237 
   238 
   239 (* typs_terms_of *)                             (*DESTRUCTIVE*)
   240 
   241 fun typs_terms_of used mk_var prfx (Ts, ts) =
   242   let
   243     fun elim (r as ref (Param S), x) = r := mk_var (x, S)
   244       | elim _ = ();
   245 
   246     val used' = fold add_names ts (fold add_namesT Ts used);
   247     val parms = rev (fold add_parms ts (fold add_parmsT Ts []));
   248     val names = Name.invent_list used' (prfx ^ "'a") (length parms);
   249   in
   250     ListPair.app elim (parms, names);
   251     (map simple_typ_of Ts, map simple_term_of ts)
   252   end;
   253 
   254 
   255 
   256 (** order-sorted unification of types **)       (*DESTRUCTIVE*)
   257 
   258 exception NO_UNIFIER of string;
   259 
   260 
   261 fun unify pp tsig =
   262   let
   263 
   264     (* adjust sorts of parameters *)
   265 
   266     fun not_of_sort x S' S =
   267       "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
   268         Pretty.string_of_sort pp S;
   269 
   270     fun meet (_, []) = ()
   271       | meet (Link (r as (ref (Param S'))), S) =
   272           if Type.subsort tsig (S', S) then ()
   273           else r := mk_param (Type.inter_sort tsig (S', S))
   274       | meet (Link (ref T), S) = meet (T, S)
   275       | meet (PType (a, Ts), S) =
   276           ListPair.app meet (Ts, Type.arity_sorts pp tsig a S
   277             handle ERROR msg => raise NO_UNIFIER msg)
   278       | meet (PTFree (x, S'), S) =
   279           if Type.subsort tsig (S', S) then ()
   280           else raise NO_UNIFIER (not_of_sort x S' S)
   281       | meet (PTVar (xi, S'), S) =
   282           if Type.subsort tsig (S', S) then ()
   283           else raise NO_UNIFIER (not_of_sort (Syntax.string_of_vname xi) S' S)
   284       | meet (Param _, _) = sys_error "meet";
   285 
   286 
   287     (* occurs check and assigment *)
   288 
   289     fun occurs_check r (Link (r' as ref T)) =
   290           if r = r' then raise NO_UNIFIER "Occurs check!"
   291           else occurs_check r T
   292       | occurs_check r (PType (_, Ts)) = List.app (occurs_check r) Ts
   293       | occurs_check _ _ = ();
   294 
   295     fun assign r T S =
   296       (case deref T of
   297         T' as Link (r' as ref (Param _)) =>
   298           if r = r' then () else (meet (T', S); r := T')
   299       | T' => (occurs_check r T'; meet (T', S); r := T'));
   300 
   301 
   302     (* unification *)
   303 
   304     fun unif (Link (r as ref (Param S)), T) = assign r T S
   305       | unif (T, Link (r as ref (Param S))) = assign r T S
   306       | unif (Link (ref T), U) = unif (T, U)
   307       | unif (T, Link (ref U)) = unif (T, U)
   308       | unif (PType (a, Ts), PType (b, Us)) =
   309           if a <> b then
   310             raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b)
   311           else ListPair.app unif (Ts, Us)
   312       | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
   313 
   314   in unif end;
   315 
   316 
   317 
   318 (** type inference **)
   319 
   320 fun appl_error pp why t T u U =
   321  ["Type error in application: " ^ why,
   322   "",
   323   Pretty.string_of (Pretty.block
   324     [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
   325       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
   326   Pretty.string_of (Pretty.block
   327     [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
   328       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
   329   ""];
   330 
   331 
   332 (* infer *)                                     (*DESTRUCTIVE*)
   333 
   334 fun infer pp tsig =
   335   let
   336     (* errors *)
   337 
   338     fun unif_failed msg =
   339       "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
   340 
   341     fun prep_output bs ts Ts =
   342       let
   343         val (Ts_bTs', ts') = typs_terms_of [] PTFree "??" (Ts @ map snd bs, ts);
   344         val (Ts', Ts'') = chop (length Ts) Ts_bTs';
   345         val xs = map Free (map fst bs ~~ Ts'');
   346         val ts'' = map (fn t => subst_bounds (xs, t)) ts';
   347       in (ts'', Ts') end;
   348 
   349     fun err_loose i =
   350       raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
   351 
   352     fun err_appl msg bs t T u U =
   353       let
   354         val ([t', u'], [T', U']) = prep_output bs [t, u] [T, U];
   355         val why =
   356           (case T' of
   357             Type ("fun", _) => "Incompatible operand type"
   358           | _ => "Operator not of function type");
   359         val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
   360       in raise TYPE (text, [T', U'], [t', u']) end;
   361 
   362     fun err_constraint msg bs t T U =
   363       let
   364         val ([t'], [T', U']) = prep_output bs [t] [T, U];
   365         val text = cat_lines
   366          [unif_failed msg,
   367           "Cannot meet type constraint:", "",
   368           Pretty.string_of (Pretty.block
   369            [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
   370             Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
   371           Pretty.string_of (Pretty.block
   372            [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
   373       in raise TYPE (text, [T', U'], [t']) end;
   374 
   375 
   376     (* main *)
   377 
   378     val unif = unify pp tsig;
   379 
   380     fun inf _ (PConst (_, T)) = T
   381       | inf _ (PFree (_, T)) = T
   382       | inf _ (PVar (_, T)) = T
   383       | inf bs (PBound i) = snd (List.nth (bs, i) handle Subscript => err_loose i)
   384       | inf bs (PAbs (x, T, t)) = PType ("fun", [T, inf ((x, T) :: bs) t])
   385       | inf bs (PAppl (t, u)) =
   386           let
   387             val T = inf bs t;
   388             val U = inf bs u;
   389             val V = mk_param [];
   390             val U_to_V = PType ("fun", [U, V]);
   391             val _ = unif (U_to_V, T) handle NO_UNIFIER msg => err_appl msg bs t T u U;
   392           in V end
   393       | inf bs (Constraint (t, U)) =
   394           let val T = inf bs t in
   395             unif (T, U) handle NO_UNIFIER msg => err_constraint msg bs t T U;
   396             T
   397           end;
   398 
   399   in inf [] end;
   400 
   401 
   402 (* basic_infer_types *)
   403 
   404 fun basic_infer_types pp tsig const_type used freeze is_param ts Ts =
   405   let
   406     (*convert to preterms/typs*)
   407     val (Tps, Ts') = pretyps_of (K true) ([], Ts);
   408     val ((vps, ps), ts') = preterms_of const_type is_param (([], Tps), ts);
   409 
   410     (*run type inference*)
   411     val tTs' = ListPair.map Constraint (ts', Ts');
   412     val _ = List.app (fn t => (infer pp tsig t; ())) tTs';
   413 
   414     (*collect result unifier*)
   415     fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); NONE)
   416       | ch_var xi_T = SOME xi_T;
   417     val env = map_filter ch_var Tps;
   418 
   419     (*convert back to terms/typs*)
   420     val mk_var =
   421       if freeze then PTFree
   422       else (fn (x, S) => PTVar ((x, 0), S));
   423     val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
   424     val final_env = map (apsnd simple_typ_of) env;
   425   in (final_ts, final_Ts, final_env) end;
   426 
   427 
   428 
   429 (** type inference **)
   430 
   431 (* user constraints *)
   432 
   433 fun constrain t T =
   434   if T = dummyT then t
   435   else Const ("_type_constraint_", T --> T) $ t;
   436 
   437 
   438 (* user parameters *)
   439 
   440 fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
   441 fun param i (x, S) = TVar (("?" ^ x, i), S);
   442 
   443 val paramify_dummies =
   444   let
   445     fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
   446 
   447     fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
   448       | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
   449       | paramify (Type (a, Ts)) maxidx =
   450           let val (Ts', maxidx') = fold_map paramify Ts maxidx
   451           in (Type (a, Ts'), maxidx') end
   452       | paramify T maxidx = (T, maxidx);
   453   in paramify end;
   454 
   455 
   456 (* decode sort constraints *)
   457 
   458 fun get_sort tsig def_sort map_sort raw_env =
   459   let
   460     fun eq ((xi: indexname, S), (xi', S')) =
   461       xi = xi' andalso Type.eq_sort tsig (S, S');
   462 
   463     val env = distinct eq (map (apsnd map_sort) raw_env);
   464     val _ = (case duplicates (eq_fst (op =)) env of [] => ()
   465       | dups => error ("Inconsistent sort constraints for type variable(s) "
   466           ^ commas_quote (map (Syntax.string_of_vname' o fst) dups)));
   467 
   468     fun get xi =
   469       (case (AList.lookup (op =) env xi, def_sort xi) of
   470         (NONE, NONE) => Type.defaultS tsig
   471       | (NONE, SOME S) => S
   472       | (SOME S, NONE) => S
   473       | (SOME S, SOME S') =>
   474           if Type.eq_sort tsig (S, S') then S'
   475           else error ("Sort constraint inconsistent with default for type variable " ^
   476             quote (Syntax.string_of_vname' xi)));
   477   in get end;
   478 
   479 
   480 (* decode_types -- transform parse tree into raw term *)
   481 
   482 fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
   483   let
   484     fun get_type xi = the_default dummyT (def_type xi);
   485     fun is_free x = is_some (def_type (x, ~1));
   486     val raw_env = Syntax.raw_term_sorts tm;
   487     val sort_of = get_sort tsig def_sort map_sort raw_env;
   488 
   489     val certT = Type.cert_typ tsig o map_type;
   490     fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
   491 
   492     fun decode (Const ("_constrain", _) $ t $ typ) =
   493           constrain (decode t) (decodeT typ)
   494       | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
   495           if T = dummyT then Abs (x, decodeT typ, decode t)
   496           else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
   497       | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
   498       | decode (t $ u) = decode t $ decode u
   499       | decode (Const (x, T)) =
   500           let val c = (case try (unprefix Syntax.constN) x of SOME c => c | NONE => map_const x)
   501           in Const (c, certT T) end
   502       | decode (Free (x, T)) =
   503           let val c = map_const x in
   504             if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
   505               Const (c, certT T)
   506             else if T = dummyT then Free (x, get_type (x, ~1))
   507             else constrain (Free (x, certT T)) (get_type (x, ~1))
   508           end
   509       | decode (Var (xi, T)) =
   510           if T = dummyT then Var (xi, get_type xi)
   511           else constrain (Var (xi, certT T)) (get_type xi)
   512       | decode (t as Bound _) = t;
   513   in decode tm end;
   514 
   515 
   516 (* infer_types *)
   517 
   518 (*Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
   519   unifies with Ti (for i=1,...,n).
   520 
   521   tsig: type signature
   522   const_type: name mapping and signature lookup
   523   def_type: partial map from indexnames to types (constrains Frees and Vars)
   524   def_sort: partial map from indexnames to sorts (constrains TFrees and TVars)
   525   used: list of already used type variables
   526   freeze: if true then generated parameters are turned into TFrees, else TVars*)
   527 
   528 fun infer_types pp tsig const_type def_type def_sort
   529     map_const map_type map_sort used freeze pat_Ts raw_ts =
   530   let
   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) =
   536       basic_infer_types pp tsig const_type used freeze is_param raw_ts' pat_Ts';
   537   in (ts, unifier) end;
   538 
   539 end;