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