src/Pure/type_infer.ML
author wenzelm
Tue Nov 28 00:35:21 2006 +0100 (2006-11-28)
changeset 21566 af2932baf068
parent 20854 f9cf9e62d11c
child 22678 23963361278c
permissions -rw-r--r--
dest_term: strip_imp_concl;
     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) -> Name.context -> 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_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 typ params =
   117   let
   118     val params' = fold_atyps
   119       (fn TVar (xi as (x, _), S) =>
   120           (fn ps =>
   121             if is_param 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_param 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 
   155     val preT_of = pretyp_of is_param;
   156     fun polyT_of T = fst (pretyp_of (K true) T Vartab.empty);
   157 
   158     fun constrain T t ps =
   159       if T = dummyT then (t, ps)
   160       else
   161         let val (T', ps') = preT_of T ps
   162         in (Constraint (t, T'), ps') end;
   163 
   164     fun pre_of (Const (c, T)) ps =
   165           (case const_type c of
   166             SOME U => constrain T (PConst (c, polyT_of U)) ps
   167           | NONE => raise TYPE ("No such constant: " ^ quote c, [], []))
   168       | pre_of (Var (xi, Type ("_polymorphic_", [T]))) ps = (PVar (xi, polyT_of T), ps)
   169       | pre_of (Var (xi, T)) ps = constrain T (PVar (xi, var_param xi)) ps
   170       | pre_of (Free (x, T)) ps = constrain T (PFree (x, var_param (x, ~1))) ps
   171       | pre_of (Const ("_type_constraint_", Type ("fun", [T, _])) $ t) ps =
   172           uncurry (constrain T) (pre_of t ps)
   173       | pre_of (Bound i) ps = (PBound i, ps)
   174       | pre_of (Abs (x, T, t)) ps =
   175           let
   176             val (T', ps') = preT_of T ps;
   177             val (t', ps'') = pre_of t ps';
   178           in (PAbs (x, T', t'), ps'') end
   179       | pre_of (t $ u) ps =
   180           let
   181             val (t', ps') = pre_of t ps;
   182             val (u', ps'') = pre_of u ps';
   183           in (PAppl (t', u'), ps'') end;
   184 
   185     val (tm', params') = pre_of tm params;
   186   in (tm', (vparams', params')) end;
   187 
   188 
   189 
   190 (** pretyps/terms to typs/terms **)
   191 
   192 (* add_parms *)
   193 
   194 fun add_parmsT (PType (_, Ts)) rs = fold add_parmsT Ts rs
   195   | add_parmsT (Link (r as ref (Param _))) rs = insert (op =) r rs
   196   | add_parmsT (Link (ref T)) rs = add_parmsT T rs
   197   | add_parmsT _ rs = rs;
   198 
   199 val add_parms = fold_pretyps add_parmsT;
   200 
   201 
   202 (* add_names *)
   203 
   204 fun add_namesT (PType (_, Ts)) = fold add_namesT Ts
   205   | add_namesT (PTFree (x, _)) = Name.declare x
   206   | add_namesT (PTVar ((x, _), _)) = Name.declare x
   207   | add_namesT (Link (ref T)) = add_namesT T
   208   | add_namesT (Param _) = I;
   209 
   210 val add_names = fold_pretyps add_namesT;
   211 
   212 
   213 (* simple_typ/term_of *)
   214 
   215 (*deref links, fail on params*)
   216 fun simple_typ_of (PType (a, Ts)) = Type (a, map simple_typ_of Ts)
   217   | simple_typ_of (PTFree v) = TFree v
   218   | simple_typ_of (PTVar v) = TVar v
   219   | simple_typ_of (Link (ref T)) = simple_typ_of T
   220   | simple_typ_of (Param _) = sys_error "simple_typ_of: illegal Param";
   221 
   222 (*convert types, drop constraints*)
   223 fun simple_term_of (PConst (c, T)) = Const (c, simple_typ_of T)
   224   | simple_term_of (PFree (x, T)) = Free (x, simple_typ_of T)
   225   | simple_term_of (PVar (xi, T)) = Var (xi, simple_typ_of T)
   226   | simple_term_of (PBound i) = Bound i
   227   | simple_term_of (PAbs (x, T, t)) = Abs (x, simple_typ_of T, simple_term_of t)
   228   | simple_term_of (PAppl (t, u)) = simple_term_of t $ simple_term_of u
   229   | simple_term_of (Constraint (t, _)) = simple_term_of t;
   230 
   231 
   232 (* typs_terms_of *)                             (*DESTRUCTIVE*)
   233 
   234 fun typs_terms_of used mk_var prfx (Ts, ts) =
   235   let
   236     fun elim (r as ref (Param S), x) = r := mk_var (x, S)
   237       | elim _ = ();
   238 
   239     val used' = fold add_names ts (fold add_namesT Ts used);
   240     val parms = rev (fold add_parms ts (fold add_parmsT Ts []));
   241     val names = Name.invents used' (prfx ^ "'a") (length parms);
   242   in
   243     ListPair.app elim (parms, names);
   244     (map simple_typ_of Ts, map simple_term_of ts)
   245   end;
   246 
   247 
   248 
   249 (** order-sorted unification of types **)       (*DESTRUCTIVE*)
   250 
   251 exception NO_UNIFIER of string;
   252 
   253 
   254 fun unify pp tsig =
   255   let
   256 
   257     (* adjust sorts of parameters *)
   258 
   259     fun not_of_sort x S' S =
   260       "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
   261         Pretty.string_of_sort pp S;
   262 
   263     fun meet (_, []) = ()
   264       | meet (Link (r as (ref (Param S'))), S) =
   265           if Type.subsort tsig (S', S) then ()
   266           else r := mk_param (Type.inter_sort tsig (S', S))
   267       | meet (Link (ref T), S) = meet (T, S)
   268       | meet (PType (a, Ts), S) =
   269           ListPair.app meet (Ts, Type.arity_sorts pp tsig a S
   270             handle ERROR msg => raise NO_UNIFIER msg)
   271       | meet (PTFree (x, S'), S) =
   272           if Type.subsort tsig (S', S) then ()
   273           else raise NO_UNIFIER (not_of_sort x S' S)
   274       | meet (PTVar (xi, S'), S) =
   275           if Type.subsort tsig (S', S) then ()
   276           else raise NO_UNIFIER (not_of_sort (Syntax.string_of_vname xi) S' S)
   277       | meet (Param _, _) = sys_error "meet";
   278 
   279 
   280     (* occurs check and assigment *)
   281 
   282     fun occurs_check r (Link (r' as ref T)) =
   283           if r = r' then raise NO_UNIFIER "Occurs check!"
   284           else occurs_check r T
   285       | occurs_check r (PType (_, Ts)) = List.app (occurs_check r) Ts
   286       | occurs_check _ _ = ();
   287 
   288     fun assign r T S =
   289       (case deref T of
   290         T' as Link (r' as ref (Param _)) =>
   291           if r = r' then () else (meet (T', S); r := T')
   292       | T' => (occurs_check r T'; meet (T', S); r := T'));
   293 
   294 
   295     (* unification *)
   296 
   297     fun unif (Link (r as ref (Param S)), T) = assign r T S
   298       | unif (T, Link (r as ref (Param S))) = assign r T S
   299       | unif (Link (ref T), U) = unif (T, U)
   300       | unif (T, Link (ref U)) = unif (T, U)
   301       | unif (PType (a, Ts), PType (b, Us)) =
   302           if a <> b then
   303             raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b)
   304           else ListPair.app unif (Ts, Us)
   305       | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
   306 
   307   in unif end;
   308 
   309 
   310 
   311 (** type inference **)
   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 (* basic_infer_types *)
   396 
   397 fun basic_infer_types pp tsig const_type used freeze is_param ts Ts =
   398   let
   399     (*convert to preterms/typs*)
   400     val (Ts', Tps) = fold_map (pretyp_of (K true)) Ts Vartab.empty;
   401     val (ts', (vps, ps)) = fold_map (preterm_of const_type is_param) ts (Vartab.empty, Tps);
   402 
   403     (*run type inference*)
   404     val tTs' = ListPair.map Constraint (ts', Ts');
   405     val _ = List.app (fn t => (infer pp tsig t; ())) tTs';
   406 
   407     (*collect result unifier*)
   408     fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); NONE)
   409       | ch_var xi_T = SOME xi_T;
   410     val env = map_filter ch_var (Vartab.dest Tps);
   411 
   412     (*convert back to terms/typs*)
   413     val mk_var =
   414       if freeze then PTFree
   415       else (fn (x, S) => PTVar ((x, 0), S));
   416     val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
   417     val final_env = map (apsnd simple_typ_of) env;
   418   in (final_ts, final_Ts, final_env) end;
   419 
   420 
   421 
   422 (** type inference **)
   423 
   424 (* user constraints *)
   425 
   426 fun constrain t T =
   427   if T = dummyT then t
   428   else Const ("_type_constraint_", T --> T) $ t;
   429 
   430 
   431 (* user parameters *)
   432 
   433 fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
   434 fun param i (x, S) = TVar (("?" ^ x, i), S);
   435 
   436 val paramify_dummies =
   437   let
   438     fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
   439 
   440     fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
   441       | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
   442       | paramify (Type (a, Ts)) maxidx =
   443           let val (Ts', maxidx') = fold_map paramify Ts maxidx
   444           in (Type (a, Ts'), maxidx') end
   445       | paramify T maxidx = (T, maxidx);
   446   in paramify end;
   447 
   448 
   449 (* decode sort constraints *)
   450 
   451 fun get_sort tsig def_sort map_sort raw_env =
   452   let
   453     fun eq ((xi, S), (xi', S')) =
   454       Term.eq_ix (xi, xi') andalso Type.eq_sort tsig (S, S');
   455 
   456     val env = distinct eq (map (apsnd map_sort) raw_env);
   457     val _ = (case duplicates (eq_fst (op =)) env of [] => ()
   458       | dups => error ("Inconsistent sort constraints for type variable(s) "
   459           ^ commas_quote (map (Syntax.string_of_vname' o fst) dups)));
   460 
   461     fun get xi =
   462       (case (AList.lookup (op =) env xi, def_sort xi) of
   463         (NONE, NONE) => Type.defaultS tsig
   464       | (NONE, SOME S) => S
   465       | (SOME S, NONE) => S
   466       | (SOME S, SOME S') =>
   467           if Type.eq_sort tsig (S, S') then S'
   468           else error ("Sort constraint inconsistent with default for type variable " ^
   469             quote (Syntax.string_of_vname' xi)));
   470   in get end;
   471 
   472 
   473 (* decode_types -- transform parse tree into raw term *)
   474 
   475 fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
   476   let
   477     fun get_type xi = the_default dummyT (def_type xi);
   478     fun is_free x = is_some (def_type (x, ~1));
   479     val raw_env = Syntax.raw_term_sorts tm;
   480     val sort_of = get_sort tsig def_sort map_sort raw_env;
   481 
   482     val certT = Type.cert_typ tsig o map_type;
   483     fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
   484 
   485     fun decode (Const ("_constrain", _) $ t $ typ) =
   486           constrain (decode t) (decodeT typ)
   487       | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
   488           if T = dummyT then Abs (x, decodeT typ, decode t)
   489           else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
   490       | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
   491       | decode (t $ u) = decode t $ decode u
   492       | decode (Const (x, T)) =
   493           let val c = (case try (unprefix Syntax.constN) x of SOME c => c | NONE => map_const x)
   494           in Const (c, certT T) end
   495       | decode (Free (x, T)) =
   496           let val c = map_const x in
   497             if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
   498               Const (c, certT T)
   499             else if T = dummyT then Free (x, get_type (x, ~1))
   500             else constrain (Free (x, certT T)) (get_type (x, ~1))
   501           end
   502       | decode (Var (xi, T)) =
   503           if T = dummyT then Var (xi, get_type xi)
   504           else constrain (Var (xi, certT T)) (get_type xi)
   505       | decode (t as Bound _) = t;
   506   in decode tm end;
   507 
   508 
   509 (* infer_types *)
   510 
   511 (*Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
   512   unifies with Ti (for i=1,...,n).
   513 
   514   tsig: type signature
   515   const_type: name mapping and signature lookup
   516   def_type: partial map from indexnames to types (constrains Frees and Vars)
   517   def_sort: partial map from indexnames to sorts (constrains TFrees and TVars)
   518   used: context of already used type variables
   519   freeze: if true then generated parameters are turned into TFrees, else TVars*)
   520 
   521 fun infer_types pp tsig const_type def_type def_sort
   522     map_const map_type map_sort used freeze pat_Ts raw_ts =
   523   let
   524     val pat_Ts' = map (Type.cert_typ tsig) pat_Ts;
   525     val is_const = is_some o const_type;
   526     val raw_ts' =
   527       map (decode_types tsig is_const def_type def_sort map_const map_type map_sort) raw_ts;
   528     val (ts, Ts, unifier) =
   529       basic_infer_types pp tsig const_type used freeze is_param raw_ts' pat_Ts';
   530   in (ts, unifier) end;
   531 
   532 end;