src/Pure/type_infer.ML
author wenzelm
Mon May 25 21:11:46 1998 +0200 (1998-05-25)
changeset 4957 30c49821e61f
parent 3784 3b15cda31c97
child 5634 7f61a83d4a01
permissions -rw-r--r--
remove seq2, scan (use seq2, foldl_map from library.ML);
     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 infer_types: (term -> Pretty.T) -> (typ -> Pretty.T)
    11     -> (string -> typ option) -> Sorts.classrel -> Sorts.arities
    12     -> string list -> bool -> (indexname -> bool) -> term list -> typ list
    13     -> term list * typ list * (indexname * typ) list
    14 end;
    15 
    16 structure TypeInfer: TYPE_INFER =
    17 struct
    18 
    19 
    20 (** term encodings **)
    21 
    22 (*
    23   Flavours of term encodings:
    24 
    25     parse trees (type term):
    26       A very complicated structure produced by the syntax module's
    27       read functions.  Encodes types and sorts as terms; may contain
    28       explicit constraints and partial typing information (where
    29       dummyT serves as wildcard).
    30 
    31       Parse trees are INTERNAL! Users should never encounter them,
    32       except in parse / print translation functions.
    33 
    34     raw terms (type term):
    35       Provide the user interface to type inferences.  They may contain
    36       partial type information (dummyT is wildcard) or explicit type
    37       constraints (introduced via constrain: term -> typ -> term).
    38 
    39       The type inference function also lets users specify a certain
    40       subset of TVars to be treated as non-rigid inference parameters.
    41 
    42     preterms (type preterm):
    43       The internal representation for type inference.
    44 
    45     well-typed term (type term):
    46       Fully typed lambda terms to be accepted by appropriate
    47       certification functions.
    48 *)
    49 
    50 
    51 
    52 (** pretyps and preterms **)
    53 
    54 (*links to parameters may get instantiated, anything else is rigid*)
    55 datatype pretyp =
    56   PType of string * pretyp list |
    57   PTFree of string * sort |
    58   PTVar of indexname * sort |
    59   Param of sort |
    60   Link of pretyp ref;
    61 
    62 datatype preterm =
    63   PConst of string * pretyp |
    64   PFree of string * pretyp |
    65   PVar of indexname * pretyp |
    66   PBound of int |
    67   PAbs of string * pretyp * preterm |
    68   PAppl of preterm * preterm |
    69   Constraint of preterm * pretyp;
    70 
    71 
    72 (* utils *)
    73 
    74 val mk_param = Link o ref o Param;
    75 
    76 fun deref (T as Link (ref (Param _))) = T
    77   | deref (Link (ref T)) = deref T
    78   | deref T = T;
    79 
    80 fun foldl_pretyps f (x, PConst (_, T)) = f (x, T)
    81   | foldl_pretyps f (x, PFree (_, T)) = f (x, T)
    82   | foldl_pretyps f (x, PVar (_, T)) = f (x, T)
    83   | foldl_pretyps _ (x, PBound _) = x
    84   | foldl_pretyps f (x, PAbs (_, T, t)) = foldl_pretyps f (f (x, T), t)
    85   | foldl_pretyps f (x, PAppl (t, u)) = foldl_pretyps f (foldl_pretyps f (x, t), u)
    86   | foldl_pretyps f (x, Constraint (t, T)) = f (foldl_pretyps f (x, t), T);
    87 
    88 
    89 
    90 (** raw typs/terms to pretyps/preterms **)
    91 
    92 (* pretyp(s)_of *)
    93 
    94 fun pretyp_of is_param (params, typ) =
    95   let
    96     fun add_parms (ps, TVar (xi as (x, _), S)) =
    97           if is_param xi andalso is_none (assoc (ps, xi))
    98           then (xi, mk_param S) :: ps else ps
    99       | add_parms (ps, TFree _) = ps
   100       | add_parms (ps, Type (_, Ts)) = foldl add_parms (ps, Ts);
   101 
   102     val params' = add_parms (params, typ);
   103 
   104     fun pre_of (TVar (v as (xi, _))) =
   105           (case assoc (params', xi) of
   106             None => PTVar v
   107           | Some p => p)
   108       | pre_of (TFree v) = PTFree v
   109       | pre_of (T as Type (a, Ts)) =
   110           if T = dummyT then mk_param []
   111           else PType (a, map pre_of Ts);
   112   in (params', pre_of typ) end;
   113 
   114 fun pretyps_of is_param = foldl_map (pretyp_of is_param);
   115 
   116 
   117 (* preterm(s)_of *)
   118 
   119 fun preterm_of const_type is_param ((vparams, params), tm) =
   120   let
   121     fun add_vparm (ps, xi) =
   122       if is_none (assoc (ps, xi)) then
   123         (xi, mk_param []) :: ps
   124       else ps;
   125 
   126     fun add_vparms (ps, Var (xi, _)) = add_vparm (ps, xi)
   127       | add_vparms (ps, Free (x, _)) = add_vparm (ps, (x, ~1))
   128       | add_vparms (ps, Abs (_, _, t)) = add_vparms (ps, t)
   129       | add_vparms (ps, t $ u) = add_vparms (add_vparms (ps, t), u)
   130       | add_vparms (ps, _) = ps;
   131 
   132     val vparams' = add_vparms (vparams, tm);
   133     fun var_param xi = the (assoc (vparams', xi));
   134 
   135 
   136     val preT_of = pretyp_of is_param;
   137 
   138     fun constrain (ps, t) T =
   139       if T = dummyT then (ps, t)
   140       else
   141         let val (ps', T') = preT_of (ps, T) in
   142           (ps', Constraint (t, T'))
   143         end;
   144 
   145     fun pre_of (ps, Const (c, T)) =
   146           (case const_type c of
   147             Some U => constrain (ps, PConst (c, snd (pretyp_of (K true) ([], U)))) T
   148           | None => raise TYPE ("No such constant: " ^ quote c, [], []))
   149       | pre_of (ps, Free (x, T)) = constrain (ps, PFree (x, var_param (x, ~1))) T
   150       | pre_of (ps, Var (xi, T)) = constrain (ps, PVar (xi, var_param xi)) T
   151       | pre_of (ps, Const ("_type_constraint_", T) $ t) = constrain (pre_of (ps, t)) T
   152       | pre_of (ps, Bound i) = (ps, PBound i)
   153       | pre_of (ps, Abs (x, T, t)) =
   154           let
   155             val (ps', T') = preT_of (ps, T);
   156             val (ps'', t') = pre_of (ps', t);
   157           in (ps'', PAbs (x, T', t')) end
   158       | pre_of (ps, t $ u) =
   159           let
   160             val (ps', t') = pre_of (ps, t);
   161             val (ps'', u') = pre_of (ps', u);
   162           in (ps'', PAppl (t', u')) end;
   163 
   164 
   165     val (params', tm') = pre_of (params, tm);
   166   in
   167     ((vparams', params'), tm')
   168   end;
   169 
   170 fun preterms_of const_type is_param = foldl_map (preterm_of const_type is_param);
   171 
   172 
   173 
   174 (** pretyps/terms to typs/terms **)
   175 
   176 (* add_parms *)
   177 
   178 fun add_parmsT (rs, PType (_, Ts)) = foldl add_parmsT (rs, Ts)
   179   | add_parmsT (rs, Link (r as ref (Param _))) = r ins rs
   180   | add_parmsT (rs, Link (ref T)) = add_parmsT (rs, T)
   181   | add_parmsT (rs, _) = rs;
   182 
   183 val add_parms = foldl_pretyps add_parmsT;
   184 
   185 
   186 (* add_names *)
   187 
   188 fun add_namesT (xs, PType (_, Ts)) = foldl add_namesT (xs, Ts)
   189   | add_namesT (xs, PTFree (x, _)) = x ins xs
   190   | add_namesT (xs, PTVar ((x, _), _)) = x ins xs
   191   | add_namesT (xs, Link (ref T)) = add_namesT (xs, T)
   192   | add_namesT (xs, Param _) = xs;
   193 
   194 val add_names = foldl_pretyps add_namesT;
   195 
   196 
   197 (* simple_typ/term_of *)
   198 
   199 (*deref links, fail on params*)
   200 fun simple_typ_of (PType (a, Ts)) = Type (a, map simple_typ_of Ts)
   201   | simple_typ_of (PTFree v) = TFree v
   202   | simple_typ_of (PTVar v) = TVar v
   203   | simple_typ_of (Link (ref T)) = simple_typ_of T
   204   | simple_typ_of (Param _) = sys_error "simple_typ_of: illegal Param";
   205 
   206 (*convert types, drop constraints*)
   207 fun simple_term_of (PConst (c, T)) = Const (c, simple_typ_of T)
   208   | simple_term_of (PFree (x, T)) = Free (x, simple_typ_of T)
   209   | simple_term_of (PVar (xi, T)) = Var (xi, simple_typ_of T)
   210   | simple_term_of (PBound i) = Bound i
   211   | simple_term_of (PAbs (x, T, t)) = Abs (x, simple_typ_of T, simple_term_of t)
   212   | simple_term_of (PAppl (t, u)) = simple_term_of t $ simple_term_of u
   213   | simple_term_of (Constraint (t, _)) = simple_term_of t;
   214 
   215 
   216 (* typs_terms_of *)                             (*DESTRUCTIVE*)
   217 
   218 fun typs_terms_of used mk_var prfx (Ts, ts) =
   219   let
   220     fun elim (r as ref (Param S), x) = r := mk_var (x, S)
   221       | elim _ = ();
   222 
   223     val used' = foldl add_names (foldl add_namesT (used, Ts), ts);
   224     val parms = rev (foldl add_parms (foldl add_parmsT ([], Ts), ts));
   225     val pre_names = replicate (length parms) (prfx ^ "'");
   226     val names = variantlist (pre_names, prfx ^ "'" :: used');
   227   in
   228     seq2 elim (parms, names);
   229     (map simple_typ_of Ts, map simple_term_of ts)
   230   end;
   231 
   232 
   233 
   234 (** order-sorted unification of types **)       (*DESTRUCTIVE*)
   235 
   236 exception NO_UNIFIER of string;
   237 
   238 
   239 fun unify classrel arities =
   240   let
   241 
   242     (* adjust sorts of parameters *)
   243 
   244     fun not_in_sort x S' S =
   245       "Variable " ^ x ^ "::" ^ Sorts.str_of_sort S' ^ " not of sort " ^
   246         Sorts.str_of_sort S ^ ".";
   247 
   248     fun meet (_, []) = ()
   249       | meet (Link (r as (ref (Param S'))), S) =
   250           if Sorts.sort_le classrel (S', S) then ()
   251           else r := mk_param (Sorts.inter_sort classrel (S', S))
   252       | meet (Link (ref T), S) = meet (T, S)
   253       | meet (PType (a, Ts), S) =
   254           seq2 meet (Ts, Sorts.mg_domain classrel arities a S
   255             handle TYPE (msg, _, _) => raise NO_UNIFIER msg)
   256       | meet (PTFree (x, S'), S) =
   257           if Sorts.sort_le classrel (S', S) then ()
   258           else raise NO_UNIFIER (not_in_sort x S' S)
   259       | meet (PTVar (xi, S'), S) =
   260           if Sorts.sort_le classrel (S', S) then ()
   261           else raise NO_UNIFIER (not_in_sort (Syntax.string_of_vname xi) S' S)
   262       | meet (Param _, _) = sys_error "meet";
   263 
   264 
   265     (* occurs check and assigment *)
   266 
   267     fun occurs_check r (Link (r' as ref T)) =
   268           if r = r' then raise NO_UNIFIER "Occurs check!"
   269           else occurs_check r T
   270       | occurs_check r (PType (_, Ts)) = seq (occurs_check r) Ts
   271       | occurs_check _ _ = ();
   272 
   273     fun assign r T S =
   274       (case deref T of
   275         T' as Link (r' as ref (Param _)) =>
   276           if r = r' then () else (r := T'; meet (T', S))
   277       | T' => (occurs_check r T'; r := T'; meet (T', S)));
   278 
   279 
   280     (* unification *)
   281 
   282     fun unif (Link (r as ref (Param S)), T) = assign r T S
   283       | unif (T, Link (r as ref (Param S))) = assign r T S
   284       | unif (Link (ref T), U) = unif (T, U)
   285       | unif (T, Link (ref U)) = unif (T, U)
   286       | unif (PType (a, Ts), PType (b, Us)) =
   287           if a <> b then
   288             raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b ^ ".")
   289           else seq2 unif (Ts, Us)
   290       | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
   291 
   292   in unif end;
   293 
   294 
   295 
   296 (** type inference **)
   297 
   298 (* infer *)                                     (*DESTRUCTIVE*)
   299 
   300 fun infer prt prT classrel arities =
   301   let
   302     (* errors *)
   303 
   304     fun unif_failed msg =
   305       "Type unification failed" ^ (if msg = "" then "." else ": " ^ msg) ^ "\n";
   306 
   307     val str_of = Pretty.string_of;
   308 
   309     fun prep_output bs ts Ts =
   310       let
   311         val (Ts_bTs', ts') = typs_terms_of [] PTFree "??" (Ts @ map snd bs, ts);
   312         val len = length Ts;
   313         val Ts' = take (len, Ts_bTs');
   314         val xs = map Free (map fst bs ~~ drop (len, Ts_bTs'));
   315         val ts'' = map (fn t => subst_bounds (xs, t)) ts';
   316       in (ts'', Ts') end;
   317 
   318     fun err_loose i =
   319       raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
   320 
   321     fun err_appl msg bs t T u U =
   322       let
   323         val ([t', u'], [T', U']) = prep_output bs [t, u] [T, U];
   324         val why =
   325           (case T' of
   326             Type ("fun", _) => "Incompatible operand type."
   327           | _ => "Operator not of function type.");
   328         val text = cat_lines
   329          [unif_failed msg,
   330           "Type error in application: " ^ why,
   331           "",
   332           str_of (Pretty.block [Pretty.str "Operator:", Pretty.brk 2, prt t',
   333             Pretty.str " :: ", prT T']),
   334           str_of (Pretty.block [Pretty.str "Operand:", Pretty.brk 3, prt u',
   335             Pretty.str " :: ", prT U']), ""];
   336       in raise TYPE (text, [T', U'], [t', u']) end;
   337 
   338     fun err_constraint msg bs t T U =
   339       let
   340         val ([t'], [T', U']) = prep_output bs [t] [T, U];
   341         val text = cat_lines
   342          [unif_failed msg,
   343           "Cannot meet type constraint:",
   344           "",
   345           str_of (Pretty.block [Pretty.str "Term:", Pretty.brk 2, prt t',
   346             Pretty.str " :: ", prT T']),
   347           str_of (Pretty.block [Pretty.str "Type:", Pretty.brk 2, prT U']), ""];
   348       in raise TYPE (text, [T', U'], [t']) end;
   349 
   350 
   351     (* main *)
   352 
   353     val unif = unify classrel arities;
   354 
   355     fun inf _ (PConst (_, T)) = T
   356       | inf _ (PFree (_, T)) = T
   357       | inf _ (PVar (_, T)) = T
   358       | inf bs (PBound i) = snd (nth_elem (i, bs) handle LIST _ => err_loose i)
   359       | inf bs (PAbs (x, T, t)) = PType ("fun", [T, inf ((x, T) :: bs) t])
   360       | inf bs (PAppl (t, u)) =
   361           let
   362             val T = inf bs t;
   363             val U = inf bs u;
   364             val V = mk_param [];
   365             val U_to_V = PType ("fun", [U, V]);
   366             val _ = unif (U_to_V, T) handle NO_UNIFIER msg => err_appl msg bs t T u U;
   367           in V end
   368       | inf bs (Constraint (t, U)) =
   369           let val T = inf bs t in
   370             unif (T, U) handle NO_UNIFIER msg => err_constraint msg bs t T U;
   371             T
   372           end;
   373 
   374   in inf [] end;
   375 
   376 
   377 (* infer_types *)
   378 
   379 fun infer_types prt prT const_type classrel arities used freeze is_param ts Ts =
   380   let
   381     (*convert to preterms/typs*)
   382     val (Tps, Ts') = pretyps_of (K true) ([], Ts);
   383     val ((vps, ps), ts') = preterms_of const_type is_param (([], Tps), ts);
   384 
   385     (*run type inference*)
   386     val tTs' = ListPair.map Constraint (ts', Ts');
   387     val _ = seq (fn t => (infer prt prT classrel arities t; ())) tTs';
   388 
   389     (*collect result unifier*)
   390     fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); None)
   391       | ch_var xi_T = Some xi_T;
   392     val env = mapfilter ch_var Tps;
   393 
   394     (*convert back to terms/typs*)
   395     val mk_var =
   396       if freeze then PTFree
   397       else (fn (x, S) => PTVar ((x, 0), S));
   398     val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
   399     val final_env = map (apsnd simple_typ_of) env;
   400   in
   401     (final_ts, final_Ts, final_env)
   402   end;
   403 
   404 
   405 end;