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