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