src/Pure/type_infer.ML
author wenzelm
Sun Sep 12 19:04:02 2010 +0200 (2010-09-12)
changeset 39288 f1ae2493d93f
parent 39287 d30be6791038
child 39289 92b50c8bb67b
permissions -rw-r--r--
eliminated aliases of Type.constraint;
     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 polymorphicT: typ -> typ
    11   val is_param: indexname -> 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 appl_error: Pretty.pp -> string -> term -> typ -> term -> typ -> string list
    17   val infer_types: Pretty.pp -> Type.tsig -> (typ list -> typ list) ->
    18     (string -> typ option) -> (indexname -> typ option) -> Name.context -> int ->
    19     term list -> term list
    20 end;
    21 
    22 structure Type_Infer: TYPE_INFER =
    23 struct
    24 
    25 
    26 (** type parameters and constraints **)
    27 
    28 fun anyT S = TFree ("'_dummy_", S);
    29 
    30 (*indicate polymorphic Vars*)
    31 fun polymorphicT T = Type ("_polymorphic_", [T]);
    32 
    33 
    34 (* type inference parameters -- may get instantiated *)
    35 
    36 fun is_param (x, _: int) = String.isPrefix "?" x;
    37 fun param i (x, S) = TVar (("?" ^ x, i), S);
    38 
    39 val paramify_vars =
    40   Same.commit
    41     (Term_Subst.map_atypsT_same
    42       (fn TVar ((x, i), S) => (param i (x, S)) | _ => raise Same.SAME));
    43 
    44 val paramify_dummies =
    45   let
    46     fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
    47 
    48     fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
    49       | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
    50       | paramify (Type (a, Ts)) maxidx =
    51           let val (Ts', maxidx') = fold_map paramify Ts maxidx
    52           in (Type (a, Ts'), maxidx') end
    53       | paramify T maxidx = (T, maxidx);
    54   in paramify end;
    55 
    56 fun fixate_params name_context ts =
    57   let
    58     fun subst_param (xi, S) (inst, used) =
    59       if is_param xi then
    60         let
    61           val [a] = Name.invents used Name.aT 1;
    62           val used' = Name.declare a used;
    63         in (((xi, S), TFree (a, S)) :: inst, used') end
    64       else (inst, used);
    65     val name_context' = (fold o fold_types) Term.declare_typ_names ts name_context;
    66     val (inst, _) = fold_rev subst_param (fold Term.add_tvars ts []) ([], name_context');
    67   in (map o map_types) (Term_Subst.instantiateT inst) ts end;
    68 
    69 
    70 
    71 (** pretyps and preterms **)
    72 
    73 datatype pretyp =
    74   PType of string * pretyp list |
    75   PTFree of string * sort |
    76   PTVar of indexname * sort |
    77   Param of int * sort;
    78 
    79 datatype preterm =
    80   PConst of string * pretyp |
    81   PFree of string * pretyp |
    82   PVar of indexname * pretyp |
    83   PBound of int |
    84   PAbs of string * pretyp * preterm |
    85   PAppl of preterm * preterm |
    86   Constraint of preterm * pretyp;
    87 
    88 
    89 (* utils *)
    90 
    91 fun deref tye (T as Param (i, S)) =
    92       (case Inttab.lookup tye i of
    93         NONE => T
    94       | SOME U => deref tye U)
    95   | deref tye T = T;
    96 
    97 fun fold_pretyps f (PConst (_, T)) x = f T x
    98   | fold_pretyps f (PFree (_, T)) x = f T x
    99   | fold_pretyps f (PVar (_, T)) x = f T x
   100   | fold_pretyps _ (PBound _) x = x
   101   | fold_pretyps f (PAbs (_, T, t)) x = fold_pretyps f t (f T x)
   102   | fold_pretyps f (PAppl (t, u)) x = fold_pretyps f u (fold_pretyps f t x)
   103   | fold_pretyps f (Constraint (t, T)) x = f T (fold_pretyps f t x);
   104 
   105 
   106 
   107 (** raw typs/terms to pretyps/preterms **)
   108 
   109 (* pretyp_of *)
   110 
   111 fun pretyp_of typ params_idx =
   112   let
   113     val (params', idx) = fold_atyps
   114       (fn TVar (xi as (x, _), S) =>
   115           (fn ps_idx as (ps, idx) =>
   116             if is_param xi andalso not (Vartab.defined ps xi)
   117             then (Vartab.update (xi, Param (idx, S)) ps, idx + 1) else ps_idx)
   118         | _ => I) typ params_idx;
   119 
   120     fun pre_of (TVar (v as (xi, _))) idx =
   121           (case Vartab.lookup params' xi of
   122             NONE => PTVar v
   123           | SOME p => p, idx)
   124       | pre_of (TFree ("'_dummy_", S)) idx = (Param (idx, S), idx + 1)
   125       | pre_of (TFree v) idx = (PTFree v, idx)
   126       | pre_of (T as Type (a, Ts)) idx =
   127           if T = dummyT then (Param (idx, []), idx + 1)
   128           else
   129             let val (Ts', idx') = fold_map pre_of Ts idx
   130             in (PType (a, Ts'), idx') end;
   131 
   132     val (ptyp, idx') = pre_of typ idx;
   133   in (ptyp, (params', idx')) end;
   134 
   135 
   136 (* preterm_of *)
   137 
   138 fun preterm_of const_type tm (vparams, params, idx) =
   139   let
   140     fun add_vparm xi (ps_idx as (ps, idx)) =
   141       if not (Vartab.defined ps xi) then
   142         (Vartab.update (xi, Param (idx, [])) ps, idx + 1)
   143       else ps_idx;
   144 
   145     val (vparams', idx') = fold_aterms
   146       (fn Var (_, Type ("_polymorphic_", _)) => I
   147         | Var (xi, _) => add_vparm xi
   148         | Free (x, _) => add_vparm (x, ~1)
   149         | _ => I)
   150       tm (vparams, idx);
   151     fun var_param xi = the (Vartab.lookup vparams' xi);
   152 
   153     fun polyT_of T idx = apsnd snd (pretyp_of (paramify_vars T) (Vartab.empty, idx));
   154 
   155     fun constraint T t ps =
   156       if T = dummyT then (t, ps)
   157       else
   158         let val (T', ps') = pretyp_of T ps
   159         in (Constraint (t, T'), ps') end;
   160 
   161     fun pre_of (Const (c, T)) (ps, idx) =
   162           (case const_type c of
   163             SOME U =>
   164               let val (pU, idx') = polyT_of U idx
   165               in constraint T (PConst (c, pU)) (ps, idx') end
   166           | NONE => raise TYPE ("Undeclared constant: " ^ quote c, [], []))
   167       | pre_of (Var (xi, Type ("_polymorphic_", [T]))) (ps, idx) =
   168           let val (pT, idx') = polyT_of T idx
   169           in (PVar (xi, pT), (ps, idx')) end
   170       | pre_of (Var (xi, T)) ps_idx = constraint T (PVar (xi, var_param xi)) ps_idx
   171       | pre_of (Free (x, T)) ps_idx = constraint T (PFree (x, var_param (x, ~1))) ps_idx
   172       | pre_of (Const ("_type_constraint_", Type ("fun", [T, _])) $ t) ps_idx =
   173           pre_of t ps_idx |-> constraint T
   174       | pre_of (Bound i) ps_idx = (PBound i, ps_idx)
   175       | pre_of (Abs (x, T, t)) ps_idx =
   176           let
   177             val (T', ps_idx') = pretyp_of T ps_idx;
   178             val (t', ps_idx'') = pre_of t ps_idx';
   179           in (PAbs (x, T', t'), ps_idx'') end
   180       | pre_of (t $ u) ps_idx =
   181           let
   182             val (t', ps_idx') = pre_of t ps_idx;
   183             val (u', ps_idx'') = pre_of u ps_idx';
   184           in (PAppl (t', u'), ps_idx'') end;
   185 
   186     val (tm', (params', idx'')) = pre_of tm (params, idx');
   187   in (tm', (vparams', params', idx'')) end;
   188 
   189 
   190 
   191 (** pretyps/terms to typs/terms **)
   192 
   193 (* add_parms *)
   194 
   195 fun add_parmsT tye T =
   196   (case deref tye T of
   197     PType (_, Ts) => fold (add_parmsT tye) Ts
   198   | Param (i, _) => insert (op =) i
   199   | _ => I);
   200 
   201 fun add_parms tye = fold_pretyps (add_parmsT tye);
   202 
   203 
   204 (* add_names *)
   205 
   206 fun add_namesT tye T =
   207   (case deref tye T of
   208     PType (_, Ts) => fold (add_namesT tye) Ts
   209   | PTFree (x, _) => Name.declare x
   210   | PTVar ((x, _), _) => Name.declare x
   211   | Param _ => I);
   212 
   213 fun add_names tye = fold_pretyps (add_namesT tye);
   214 
   215 
   216 (* simple_typ/term_of *)
   217 
   218 fun simple_typ_of tye f T =
   219   (case deref tye T of
   220     PType (a, Ts) => Type (a, map (simple_typ_of tye f) Ts)
   221   | PTFree v => TFree v
   222   | PTVar v => TVar v
   223   | Param (i, S) => TVar (f i, S));
   224 
   225 (*convert types, drop constraints*)
   226 fun simple_term_of tye f (PConst (c, T)) = Const (c, simple_typ_of tye f T)
   227   | simple_term_of tye f (PFree (x, T)) = Free (x, simple_typ_of tye f T)
   228   | simple_term_of tye f (PVar (xi, T)) = Var (xi, simple_typ_of tye f T)
   229   | simple_term_of tye f (PBound i) = Bound i
   230   | simple_term_of tye f (PAbs (x, T, t)) =
   231       Abs (x, simple_typ_of tye f T, simple_term_of tye f t)
   232   | simple_term_of tye f (PAppl (t, u)) =
   233       simple_term_of tye f t $ simple_term_of tye f u
   234   | simple_term_of tye f (Constraint (t, _)) = simple_term_of tye f t;
   235 
   236 
   237 (* typs_terms_of *)
   238 
   239 fun typs_terms_of tye used maxidx (Ts, ts) =
   240   let
   241     val used' = fold (add_names tye) ts (fold (add_namesT tye) Ts used);
   242     val parms = rev (fold (add_parms tye) ts (fold (add_parmsT tye) Ts []));
   243     val names = Name.invents used' ("?" ^ Name.aT) (length parms);
   244     val tab = Inttab.make (parms ~~ names);
   245     fun f i = (the (Inttab.lookup tab i), maxidx + 1);
   246   in (map (simple_typ_of tye f) Ts, map (simple_term_of tye f) ts) end;
   247 
   248 
   249 
   250 (** order-sorted unification of types **)
   251 
   252 exception NO_UNIFIER of string * pretyp Inttab.table;
   253 
   254 fun unify pp tsig =
   255   let
   256     (* adjust sorts of parameters *)
   257 
   258     fun not_of_sort x S' S =
   259       "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
   260         Pretty.string_of_sort pp S;
   261 
   262     fun meet (_, []) tye_idx = tye_idx
   263       | meet (Param (i, S'), S) (tye_idx as (tye, idx)) =
   264           if Type.subsort tsig (S', S) then tye_idx
   265           else (Inttab.update_new (i,
   266             Param (idx, Type.inter_sort tsig (S', S))) tye, idx + 1)
   267       | meet (PType (a, Ts), S) (tye_idx as (tye, _)) =
   268           meets (Ts, Type.arity_sorts pp tsig a S
   269             handle ERROR msg => raise NO_UNIFIER (msg, tye)) tye_idx
   270       | meet (PTFree (x, S'), S) (tye_idx as (tye, _)) =
   271           if Type.subsort tsig (S', S) then tye_idx
   272           else raise NO_UNIFIER (not_of_sort x S' S, tye)
   273       | meet (PTVar (xi, S'), S) (tye_idx as (tye, _)) =
   274           if Type.subsort tsig (S', S) then tye_idx
   275           else raise NO_UNIFIER (not_of_sort (Term.string_of_vname xi) S' S, tye)
   276     and meets (T :: Ts, S :: Ss) (tye_idx as (tye, _)) =
   277           meets (Ts, Ss) (meet (deref tye T, S) tye_idx)
   278       | meets _ tye_idx = tye_idx;
   279 
   280 
   281     (* occurs check and assignment *)
   282 
   283     fun occurs_check tye i (Param (i', S)) =
   284           if i = i' then raise NO_UNIFIER ("Occurs check!", tye)
   285           else
   286             (case Inttab.lookup tye i' of
   287               NONE => ()
   288             | SOME T => occurs_check tye i T)
   289       | occurs_check tye i (PType (_, Ts)) = List.app (occurs_check tye i) Ts
   290       | occurs_check _ _ _ = ();
   291 
   292     fun assign i (T as Param (i', _)) S tye_idx =
   293           if i = i' then tye_idx
   294           else tye_idx |> meet (T, S) |>> Inttab.update_new (i, T)
   295       | assign i T S (tye_idx as (tye, _)) =
   296           (occurs_check tye i T; tye_idx |> meet (T, S) |>> Inttab.update_new (i, T));
   297 
   298 
   299     (* unification *)
   300 
   301     fun show_tycon (a, Ts) =
   302       quote (Pretty.string_of_typ pp (Type (a, replicate (length Ts) dummyT)));
   303 
   304     fun unif (T1, T2) (tye_idx as (tye, idx)) =
   305       (case (deref tye T1, deref tye T2) of
   306         (Param (i, S), T) => assign i T S tye_idx
   307       | (T, Param (i, S)) => assign i T S tye_idx
   308       | (PType (a, Ts), PType (b, Us)) =>
   309           if a <> b then
   310             raise NO_UNIFIER
   311               ("Clash of types " ^ show_tycon (a, Ts) ^ " and " ^ show_tycon (b, Us), tye)
   312           else fold unif (Ts ~~ Us) tye_idx
   313       | (T, U) => if T = U then tye_idx else raise NO_UNIFIER ("", tye));
   314 
   315   in unif end;
   316 
   317 
   318 
   319 (** type inference **)
   320 
   321 (* appl_error *)
   322 
   323 fun appl_error pp why t T u U =
   324  ["Type error in application: " ^ why,
   325   "",
   326   Pretty.string_of (Pretty.block
   327     [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
   328       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
   329   Pretty.string_of (Pretty.block
   330     [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
   331       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
   332   ""];
   333 
   334 
   335 (* infer *)
   336 
   337 fun infer pp tsig =
   338   let
   339     (* errors *)
   340 
   341     fun unif_failed msg =
   342       "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
   343 
   344     fun prep_output tye bs ts Ts =
   345       let
   346         val (Ts_bTs', ts') = typs_terms_of tye Name.context ~1 (Ts @ map snd bs, ts);
   347         val (Ts', Ts'') = chop (length Ts) Ts_bTs';
   348         fun prep t =
   349           let val xs = rev (Term.variant_frees t (rev (map fst bs ~~ Ts'')))
   350           in Term.subst_bounds (map Syntax.mark_boundT xs, t) end;
   351       in (map prep ts', Ts') end;
   352 
   353     fun err_loose i =
   354       raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
   355 
   356     fun err_appl msg tye bs t T u U =
   357       let
   358         val ([t', u'], [T', U']) = prep_output tye bs [t, u] [T, U];
   359         val why =
   360           (case T' of
   361             Type ("fun", _) => "Incompatible operand type"
   362           | _ => "Operator not of function type");
   363         val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
   364       in raise TYPE (text, [T', U'], [t', u']) end;
   365 
   366     fun err_constraint msg tye bs t T U =
   367       let
   368         val ([t'], [T', U']) = prep_output tye bs [t] [T, U];
   369         val text = cat_lines
   370          [unif_failed msg,
   371           "Cannot meet type constraint:", "",
   372           Pretty.string_of (Pretty.block
   373            [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
   374             Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
   375           Pretty.string_of (Pretty.block
   376            [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
   377       in raise TYPE (text, [T', U'], [t']) end;
   378 
   379 
   380     (* main *)
   381 
   382     val unif = unify pp tsig;
   383 
   384     fun inf _ (PConst (_, T)) tye_idx = (T, tye_idx)
   385       | inf _ (PFree (_, T)) tye_idx = (T, tye_idx)
   386       | inf _ (PVar (_, T)) tye_idx = (T, tye_idx)
   387       | inf bs (PBound i) tye_idx =
   388           (snd (nth bs i handle Subscript => err_loose i), tye_idx)
   389       | inf bs (PAbs (x, T, t)) tye_idx =
   390           let val (U, tye_idx') = inf ((x, T) :: bs) t tye_idx
   391           in (PType ("fun", [T, U]), tye_idx') end
   392       | inf bs (PAppl (t, u)) tye_idx =
   393           let
   394             val (T, tye_idx') = inf bs t tye_idx;
   395             val (U, (tye, idx)) = inf bs u tye_idx';
   396             val V = Param (idx, []);
   397             val U_to_V = PType ("fun", [U, V]);
   398             val tye_idx'' = unif (U_to_V, T) (tye, idx + 1)
   399               handle NO_UNIFIER (msg, tye') => err_appl msg tye' bs t T u U;
   400           in (V, tye_idx'') end
   401       | inf bs (Constraint (t, U)) tye_idx =
   402           let val (T, tye_idx') = inf bs t tye_idx in
   403             (T,
   404              unif (T, U) tye_idx'
   405                handle NO_UNIFIER (msg, tye) => err_constraint msg tye bs t T U)
   406           end;
   407 
   408   in inf [] end;
   409 
   410 
   411 (* infer_types *)
   412 
   413 fun infer_types pp tsig check_typs const_type var_type used maxidx raw_ts =
   414   let
   415     (*constrain vars*)
   416     val get_type = the_default dummyT o var_type;
   417     val constrain_vars = Term.map_aterms
   418       (fn Free (x, T) => Type.constraint T (Free (x, get_type (x, ~1)))
   419         | Var (xi, T) => Type.constraint T (Var (xi, get_type xi))
   420         | t => t);
   421 
   422     (*convert to preterms*)
   423     val ts = burrow_types check_typs raw_ts;
   424     val (ts', (_, _, idx)) =
   425       fold_map (preterm_of const_type o constrain_vars) ts
   426       (Vartab.empty, Vartab.empty, 0);
   427 
   428     (*do type inference*)
   429     val (tye, _) = fold (snd oo infer pp tsig) ts' (Inttab.empty, idx);
   430   in #2 (typs_terms_of tye used maxidx ([], ts')) end;
   431 
   432 end;