src/Pure/type_infer.ML
author wenzelm
Mon Sep 13 11:35:55 2010 +0200 (2010-09-13)
changeset 39294 27fae73fe769
parent 39292 6f085332c7d3
child 39295 6e8b0672c6a2
permissions -rw-r--r--
simplified Type_Infer: eliminated separate datatypes pretyp/preterm -- only assign is_paramT TVars;
     1 (*  Title:      Pure/type_infer.ML
     2     Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
     3 
     4 Simple type inference.
     5 *)
     6 
     7 signature TYPE_INFER =
     8 sig
     9   val anyT: sort -> typ
    10   val is_param: indexname -> bool
    11   val is_paramT: typ -> bool
    12   val param: int -> string * sort -> typ
    13   val paramify_vars: typ -> typ
    14   val paramify_dummies: typ -> int -> typ * int
    15   val fixate_params: Name.context -> term list -> term list
    16   val infer_types: Proof.context -> (string -> typ option) -> (indexname -> typ option) ->
    17     term list -> term list
    18 end;
    19 
    20 structure Type_Infer: TYPE_INFER =
    21 struct
    22 
    23 
    24 (** type parameters and constraints **)
    25 
    26 fun anyT S = TFree ("'_dummy_", S);
    27 
    28 
    29 (* type inference parameters -- may get instantiated *)
    30 
    31 fun is_param (x, _: int) = String.isPrefix "?" x;
    32 
    33 fun is_paramT (TVar (xi, _)) = is_param xi
    34   | is_paramT _ = false;
    35 
    36 fun param i (x, S) = TVar (("?" ^ x, i), S);
    37 
    38 fun mk_param i S = TVar (("?'a", i), S);
    39 
    40 val paramify_vars =
    41   Same.commit
    42     (Term_Subst.map_atypsT_same
    43       (fn TVar ((x, i), S) => (param i (x, S)) | _ => raise Same.SAME));
    44 
    45 val paramify_dummies =
    46   let
    47     fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
    48 
    49     fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
    50       | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
    51       | paramify (Type (a, Ts)) maxidx =
    52           let val (Ts', maxidx') = fold_map paramify Ts maxidx
    53           in (Type (a, Ts'), maxidx') end
    54       | paramify T maxidx = (T, maxidx);
    55   in paramify end;
    56 
    57 fun fixate_params name_context ts =
    58   let
    59     fun subst_param (xi, S) (inst, used) =
    60       if is_param xi then
    61         let
    62           val [a] = Name.invents used Name.aT 1;
    63           val used' = Name.declare a used;
    64         in (((xi, S), TFree (a, S)) :: inst, used') end
    65       else (inst, used);
    66     val name_context' = (fold o fold_types) Term.declare_typ_names ts name_context;
    67     val (inst, _) = fold_rev subst_param (fold Term.add_tvars ts []) ([], name_context');
    68   in (map o map_types) (Term_Subst.instantiateT inst) ts end;
    69 
    70 
    71 
    72 (** prepare types/terms: create inference parameters **)
    73 
    74 (* prepare_typ *)
    75 
    76 fun prepare_typ typ params_idx =
    77   let
    78     val (params', idx) = fold_atyps
    79       (fn TVar (xi as (x, _), S) =>
    80           (fn ps_idx as (ps, idx) =>
    81             if is_param xi andalso not (Vartab.defined ps xi)
    82             then (Vartab.update (xi, mk_param idx S) ps, idx + 1) else ps_idx)
    83         | _ => I) typ params_idx;
    84 
    85     fun prepare (T as Type (a, Ts)) idx =
    86           if T = dummyT then (mk_param idx [], idx + 1)
    87           else
    88             let val (Ts', idx') = fold_map prepare Ts idx
    89             in (Type (a, Ts'), idx') end
    90       | prepare (T as TVar (xi, _)) idx =
    91           (case Vartab.lookup params' xi of
    92             NONE => T
    93           | SOME p => p, idx)
    94       | prepare (TFree ("'_dummy_", S)) idx = (mk_param idx S, idx + 1)
    95       | prepare (T as TFree _) idx = (T, idx);
    96 
    97     val (typ', idx') = prepare typ idx;
    98   in (typ', (params', idx')) end;
    99 
   100 
   101 (* prepare_term *)
   102 
   103 fun prepare_term const_type tm (vparams, params, idx) =
   104   let
   105     fun add_vparm xi (ps_idx as (ps, idx)) =
   106       if not (Vartab.defined ps xi) then
   107         (Vartab.update (xi, mk_param idx []) ps, idx + 1)
   108       else ps_idx;
   109 
   110     val (vparams', idx') = fold_aterms
   111       (fn Var (_, Type ("_polymorphic_", _)) => I
   112         | Var (xi, _) => add_vparm xi
   113         | Free (x, _) => add_vparm (x, ~1)
   114         | _ => I)
   115       tm (vparams, idx);
   116     fun var_param xi = the (Vartab.lookup vparams' xi);
   117 
   118     fun polyT_of T idx = apsnd snd (prepare_typ (paramify_vars T) (Vartab.empty, idx));
   119 
   120     fun constraint T t ps =
   121       if T = dummyT then (t, ps)
   122       else
   123         let val (T', ps') = prepare_typ T ps
   124         in (Type.constraint T' t, ps') end;
   125 
   126     fun prepare (Const ("_type_constraint_", T) $ t) ps_idx =
   127           let
   128             val (T', ps_idx') = prepare_typ T ps_idx;
   129             val (t', ps_idx'') = prepare t ps_idx';
   130           in (Const ("_type_constraint_", T') $ t', ps_idx'') end
   131       | prepare (Const (c, T)) (ps, idx) =
   132           (case const_type c of
   133             SOME U =>
   134               let val (U', idx') = polyT_of U idx
   135               in constraint T (Const (c, U')) (ps, idx') end
   136           | NONE => error ("Undeclared constant: " ^ quote c))
   137       | prepare (Var (xi, Type ("_polymorphic_", [T]))) (ps, idx) =
   138           let val (T', idx') = polyT_of T idx
   139           in (Var (xi, T'), (ps, idx')) end
   140       | prepare (Var (xi, T)) ps_idx = constraint T (Var (xi, var_param xi)) ps_idx
   141       | prepare (Free (x, T)) ps_idx = constraint T (Free (x, var_param (x, ~1))) ps_idx
   142       | prepare (Bound i) ps_idx = (Bound i, ps_idx)
   143       | prepare (Abs (x, T, t)) ps_idx =
   144           let
   145             val (T', ps_idx') = prepare_typ T ps_idx;
   146             val (t', ps_idx'') = prepare t ps_idx';
   147           in (Abs (x, T', t'), ps_idx'') end
   148       | prepare (t $ u) ps_idx =
   149           let
   150             val (t', ps_idx') = prepare t ps_idx;
   151             val (u', ps_idx'') = prepare u ps_idx';
   152           in (t' $ u', ps_idx'') end;
   153 
   154     val (tm', (params', idx'')) = prepare tm (params, idx');
   155   in (tm', (vparams', params', idx'')) end;
   156 
   157 
   158 
   159 (** finish types/terms: standardize remaining parameters **)
   160 
   161 (* dereferenced views *)
   162 
   163 fun deref tye (T as TVar (xi, _)) =
   164       (case Vartab.lookup tye xi of
   165         NONE => T
   166       | SOME U => deref tye U)
   167   | deref tye T = T;
   168 
   169 fun add_parms tye T =
   170   (case deref tye T of
   171     Type (_, Ts) => fold (add_parms tye) Ts
   172   | TVar (xi, _) => if is_param xi then insert (op =) xi else I
   173   | _ => I);
   174 
   175 fun add_names tye T =
   176   (case deref tye T of
   177     Type (_, Ts) => fold (add_names tye) Ts
   178   | TFree (x, _) => Name.declare x
   179   | TVar ((x, i), _) => if is_param (x, i) then I else Name.declare x);
   180 
   181 
   182 (* finish *)
   183 
   184 fun finish ctxt tye (Ts, ts) =
   185   let
   186     val used =
   187       (fold o fold_types) (add_names tye) ts (fold (add_names tye) Ts (Variable.names_of ctxt));
   188     val parms = rev ((fold o fold_types) (add_parms tye) ts (fold (add_parms tye) Ts []));
   189     val names = Name.invents used ("?" ^ Name.aT) (length parms);
   190     val tab = Vartab.make (parms ~~ names);
   191     val idx = Variable.maxidx_of ctxt + 1;
   192 
   193     fun finish_typ T =
   194       (case deref tye T of
   195         Type (a, Ts) => Type (a, map finish_typ Ts)
   196       | U as TFree _ => U
   197       | U as TVar (xi, S) =>
   198           (case Vartab.lookup tab xi of
   199             NONE => U
   200           | SOME a => TVar ((a, idx), S)));
   201   in (map finish_typ Ts, map (Type.strip_constraints o Term.map_types finish_typ) ts) end;
   202 
   203 
   204 
   205 (** order-sorted unification of types **)
   206 
   207 exception NO_UNIFIER of string * typ Vartab.table;
   208 
   209 fun unify ctxt pp =
   210   let
   211     val thy = ProofContext.theory_of ctxt;
   212     val arity_sorts = Type.arity_sorts pp (Sign.tsig_of thy);
   213 
   214 
   215     (* adjust sorts of parameters *)
   216 
   217     fun not_of_sort x S' S =
   218       "Variable " ^ x ^ "::" ^ Syntax.string_of_sort ctxt S' ^ " not of sort " ^
   219         Syntax.string_of_sort ctxt S;
   220 
   221     fun meet (_, []) tye_idx = tye_idx
   222       | meet (Type (a, Ts), S) (tye_idx as (tye, _)) =
   223           meets (Ts, arity_sorts a S handle ERROR msg => raise NO_UNIFIER (msg, tye)) tye_idx
   224       | meet (TFree (x, S'), S) (tye_idx as (tye, _)) =
   225           if Sign.subsort thy (S', S) then tye_idx
   226           else raise NO_UNIFIER (not_of_sort x S' S, tye)
   227       | meet (TVar (xi, S'), S) (tye_idx as (tye, idx)) =
   228           if Sign.subsort thy (S', S) then tye_idx
   229           else if is_param xi then
   230             (Vartab.update_new (xi, mk_param idx (Sign.inter_sort thy (S', S))) tye, idx + 1)
   231           else raise NO_UNIFIER (not_of_sort (Term.string_of_vname xi) S' S, tye)
   232     and meets (T :: Ts, S :: Ss) (tye_idx as (tye, _)) =
   233           meets (Ts, Ss) (meet (deref tye T, S) tye_idx)
   234       | meets _ tye_idx = tye_idx;
   235 
   236 
   237     (* occurs check and assignment *)
   238 
   239     fun occurs_check tye xi (TVar (xi', S)) =
   240           if xi = xi' then raise NO_UNIFIER ("Occurs check!", tye)
   241           else
   242             (case Vartab.lookup tye xi' of
   243               NONE => ()
   244             | SOME T => occurs_check tye xi T)
   245       | occurs_check tye xi (Type (_, Ts)) = List.app (occurs_check tye xi) Ts
   246       | occurs_check _ _ _ = ();
   247 
   248     fun assign xi (T as TVar (xi', _)) S env =
   249           if xi = xi' then env
   250           else env |> meet (T, S) |>> Vartab.update_new (xi, T)
   251       | assign xi T S (env as (tye, _)) =
   252           (occurs_check tye xi T; env |> meet (T, S) |>> Vartab.update_new (xi, T));
   253 
   254 
   255     (* unification *)
   256 
   257     fun show_tycon (a, Ts) =
   258       quote (Syntax.string_of_typ ctxt (Type (a, replicate (length Ts) dummyT)));
   259 
   260     fun unif (T1, T2) (env as (tye, _)) =
   261       (case pairself (`is_paramT o deref tye) (T1, T2) of
   262         ((true, TVar (xi, S)), (_, T)) => assign xi T S env
   263       | ((_, T), (true, TVar (xi, S))) => assign xi T S env
   264       | ((_, Type (a, Ts)), (_, Type (b, Us))) =>
   265           if a <> b then
   266             raise NO_UNIFIER
   267               ("Clash of types " ^ show_tycon (a, Ts) ^ " and " ^ show_tycon (b, Us), tye)
   268           else fold unif (Ts ~~ Us) env
   269       | ((_, T), (_, U)) => if T = U then env else raise NO_UNIFIER ("", tye));
   270 
   271   in unif end;
   272 
   273 
   274 
   275 (** type inference **)
   276 
   277 (* infer *)
   278 
   279 fun infer ctxt =
   280   let
   281     val pp = Syntax.pp ctxt;
   282 
   283 
   284     (* errors *)
   285 
   286     fun prep_output tye bs ts Ts =
   287       let
   288         val (Ts_bTs', ts') = finish ctxt tye (Ts @ map snd bs, ts);
   289         val (Ts', Ts'') = chop (length Ts) Ts_bTs';
   290         fun prep t =
   291           let val xs = rev (Term.variant_frees t (rev (map fst bs ~~ Ts'')))
   292           in Term.subst_bounds (map Syntax.mark_boundT xs, t) end;
   293       in (map prep ts', Ts') end;
   294 
   295     fun err_loose i = error ("Loose bound variable: B." ^ string_of_int i);
   296 
   297     fun unif_failed msg =
   298       "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n\n";
   299 
   300     fun err_appl msg tye bs t T u U =
   301       let val ([t', u'], [T', U']) = prep_output tye bs [t, u] [T, U]
   302       in error (unif_failed msg ^ Type.appl_error pp t' T' u' U' ^ "\n") end;
   303 
   304 
   305     (* main *)
   306 
   307     fun inf _ (Const (_, T)) tye_idx = (T, tye_idx)
   308       | inf _ (Free (_, T)) tye_idx = (T, tye_idx)
   309       | inf _ (Var (_, T)) tye_idx = (T, tye_idx)
   310       | inf bs (Bound i) tye_idx =
   311           (snd (nth bs i handle Subscript => err_loose i), tye_idx)
   312       | inf bs (Abs (x, T, t)) tye_idx =
   313           let val (U, tye_idx') = inf ((x, T) :: bs) t tye_idx
   314           in (T --> U, tye_idx') end
   315       | inf bs (t $ u) tye_idx =
   316           let
   317             val (T, tye_idx') = inf bs t tye_idx;
   318             val (U, (tye, idx)) = inf bs u tye_idx';
   319             val V = mk_param idx [];
   320             val tye_idx'' = unify ctxt pp (U --> V, T) (tye, idx + 1)
   321               handle NO_UNIFIER (msg, tye') => err_appl msg tye' bs t T u U;
   322           in (V, tye_idx'') end;
   323 
   324   in inf [] end;
   325 
   326 
   327 (* infer_types *)
   328 
   329 fun infer_types ctxt const_type var_type raw_ts =
   330   let
   331     (*constrain vars*)
   332     val get_type = the_default dummyT o var_type;
   333     val constrain_vars = Term.map_aterms
   334       (fn Free (x, T) => Type.constraint T (Free (x, get_type (x, ~1)))
   335         | Var (xi, T) => Type.constraint T (Var (xi, get_type xi))
   336         | t => t);
   337 
   338     (*convert to preterms*)
   339     val ts = burrow_types (Syntax.check_typs ctxt) raw_ts;
   340     val (ts', (_, _, idx)) =
   341       fold_map (prepare_term const_type o constrain_vars) ts
   342       (Vartab.empty, Vartab.empty, 0);
   343 
   344     (*do type inference*)
   345     val (tye, _) = fold (snd oo infer ctxt) ts' (Vartab.empty, idx);
   346   in #2 (finish ctxt tye ([], ts')) end;
   347 
   348 end;