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