src/Pure/type_infer.ML
author berghofe
Thu Apr 21 19:12:03 2005 +0200 (2005-04-21)
changeset 15797 a63605582573
parent 15570 8d8c70b41bab
child 16195 0eb3c15298cd
permissions -rw-r--r--
- Eliminated nodup_vars check.
- Unification and matching functions now check types of term variables / sorts
of type variables when applying a substitution.
- Thm.instantiate now takes (ctyp * ctyp) list instead of (indexname * ctyp) list
as argument, to allow for proper instantiation of theorems containing
type variables with same name but different sorts.
     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 appl_error: Pretty.pp -> string -> term -> typ -> term -> typ -> string list
    14   val constrain: term -> typ -> term
    15   val param: int -> string * sort -> typ
    16   val paramify_dummies: int * typ -> int * typ
    17   val get_sort: Type.tsig -> (indexname -> sort option) -> (sort -> sort)
    18     -> (indexname * sort) list -> indexname -> sort
    19   val infer_types: Pretty.pp
    20     -> Type.tsig -> (string -> typ option) -> (indexname -> typ option)
    21     -> (indexname -> sort option) -> (string -> string) -> (typ -> typ)
    22     -> (sort -> sort) -> string list -> bool -> typ list -> term list
    23     -> term list * (indexname * typ) list
    24 end;
    25 
    26 structure TypeInfer: TYPE_INFER =
    27 struct
    28 
    29 
    30 (** term encodings **)
    31 
    32 (*
    33   Flavours of term encodings:
    34 
    35     parse trees (type term):
    36       A very complicated structure produced by the syntax module's
    37       read functions.  Encodes types and sorts as terms; may contain
    38       explicit constraints and partial typing information (where
    39       dummies serve as wildcards).
    40 
    41       Parse trees are INTERNAL! Users should never encounter them,
    42       except in parse / print translation functions.
    43 
    44     raw terms (type term):
    45       Provide the user interface to type inferences.  They may contain
    46       partial type information (dummies are wildcards) or explicit
    47       type constraints (introduced via constrain: term -> typ ->
    48       term).
    49 
    50       The type inference function also lets users specify a certain
    51       subset of TVars to be treated as non-rigid inference parameters.
    52 
    53     preterms (type preterm):
    54       The internal representation for type inference.
    55 
    56     well-typed term (type term):
    57       Fully typed lambda terms to be accepted by appropriate
    58       certification functions.
    59 *)
    60 
    61 
    62 
    63 (** pretyps and preterms **)
    64 
    65 (*links to parameters may get instantiated, anything else is rigid*)
    66 datatype pretyp =
    67   PType of string * pretyp list |
    68   PTFree of string * sort |
    69   PTVar of indexname * sort |
    70   Param of sort |
    71   Link of pretyp ref;
    72 
    73 datatype preterm =
    74   PConst of string * pretyp |
    75   PFree of string * pretyp |
    76   PVar of indexname * pretyp |
    77   PBound of int |
    78   PAbs of string * pretyp * preterm |
    79   PAppl of preterm * preterm |
    80   Constraint of preterm * pretyp;
    81 
    82 
    83 (* utils *)
    84 
    85 val mk_param = Link o ref o Param;
    86 
    87 fun deref (T as Link (ref (Param _))) = T
    88   | deref (Link (ref T)) = deref T
    89   | deref T = T;
    90 
    91 fun foldl_pretyps f (x, PConst (_, T)) = f (x, T)
    92   | foldl_pretyps f (x, PFree (_, T)) = f (x, T)
    93   | foldl_pretyps f (x, PVar (_, T)) = f (x, T)
    94   | foldl_pretyps _ (x, PBound _) = x
    95   | foldl_pretyps f (x, PAbs (_, T, t)) = foldl_pretyps f (f (x, T), t)
    96   | foldl_pretyps f (x, PAppl (t, u)) = foldl_pretyps f (foldl_pretyps f (x, t), u)
    97   | foldl_pretyps f (x, Constraint (t, T)) = f (foldl_pretyps f (x, t), T);
    98 
    99 
   100 
   101 (** raw typs/terms to pretyps/preterms **)
   102 
   103 (* pretyp(s)_of *)
   104 
   105 fun anyT S = TFree ("'_dummy_", S);
   106 val logicT = anyT [];
   107 
   108 (*indicate polymorphic Vars*)
   109 fun polymorphicT T = Type ("_polymorphic_", [T]);
   110 
   111 fun pretyp_of is_param (params, typ) =
   112   let
   113     fun add_parms (ps, TVar (xi as (x, _), S)) =
   114           if is_param xi andalso is_none (assoc (ps, xi))
   115           then (xi, mk_param S) :: ps else ps
   116       | add_parms (ps, TFree _) = ps
   117       | add_parms (ps, Type (_, Ts)) = Library.foldl add_parms (ps, Ts);
   118 
   119     val params' = add_parms (params, typ);
   120 
   121     fun pre_of (TVar (v as (xi, _))) =
   122           (case assoc (params', xi) of
   123             NONE => PTVar v
   124           | SOME p => p)
   125       | pre_of (TFree ("'_dummy_", S)) = mk_param S
   126       | pre_of (TFree v) = PTFree v
   127       | pre_of (T as Type (a, Ts)) =
   128           if T = dummyT then mk_param []
   129           else PType (a, map pre_of Ts);
   130   in (params', pre_of typ) end;
   131 
   132 fun pretyps_of is_param = foldl_map (pretyp_of is_param);
   133 
   134 
   135 (* preterm(s)_of *)
   136 
   137 fun preterm_of const_type is_param ((vparams, params), tm) =
   138   let
   139     fun add_vparm (ps, xi) =
   140       if is_none (assoc (ps, xi)) then
   141         (xi, mk_param []) :: ps
   142       else ps;
   143 
   144     fun add_vparms (ps, Var (xi, Type ("_polymorphic_", _))) = ps
   145       | add_vparms (ps, Var (xi, _)) = add_vparm (ps, xi)
   146       | add_vparms (ps, Free (x, _)) = add_vparm (ps, (x, ~1))
   147       | add_vparms (ps, Abs (_, _, t)) = add_vparms (ps, t)
   148       | add_vparms (ps, t $ u) = add_vparms (add_vparms (ps, t), u)
   149       | add_vparms (ps, _) = ps;
   150 
   151     val vparams' = add_vparms (vparams, tm);
   152     fun var_param xi = valOf (assoc (vparams', xi));
   153 
   154 
   155     val preT_of = pretyp_of is_param;
   156 
   157     fun constrain (ps, t) T =
   158       if T = dummyT then (ps, t)
   159       else
   160         let val (ps', T') = preT_of (ps, T)
   161         in (ps', Constraint (t, T')) end;
   162 
   163     fun pre_of (ps, Const (c, T)) =
   164           (case const_type c of
   165             SOME U => constrain (ps, PConst (c, snd (pretyp_of (K true) ([], U)))) T
   166           | NONE => raise TYPE ("No such constant: " ^ quote c, [], []))
   167       | pre_of (ps, Var (xi, Type ("_polymorphic_", [T]))) =
   168           (ps, PVar (xi, snd (pretyp_of (K true) ([], T))))
   169       | pre_of (ps, Var (xi, T)) = constrain (ps, PVar (xi, var_param xi)) T
   170       | pre_of (ps, Free (x, T)) = constrain (ps, PFree (x, var_param (x, ~1))) T
   171       | pre_of (ps, Const ("_type_constraint_", T) $ t) = constrain (pre_of (ps, t)) T
   172       | pre_of (ps, Bound i) = (ps, PBound i)
   173       | pre_of (ps, Abs (x, T, t)) =
   174           let
   175             val (ps', T') = preT_of (ps, T);
   176             val (ps'', t') = pre_of (ps', t);
   177           in (ps'', PAbs (x, T', t')) end
   178       | pre_of (ps, t $ u) =
   179           let
   180             val (ps', t') = pre_of (ps, t);
   181             val (ps'', u') = pre_of (ps', u);
   182           in (ps'', PAppl (t', u')) end;
   183 
   184     val (params', tm') = pre_of (params, tm);
   185   in ((vparams', params'), tm') end;
   186 
   187 fun preterms_of const_type is_param = foldl_map (preterm_of const_type is_param);
   188 
   189 
   190 
   191 (** pretyps/terms to typs/terms **)
   192 
   193 (* add_parms *)
   194 
   195 fun add_parmsT (rs, PType (_, Ts)) = Library.foldl add_parmsT (rs, Ts)
   196   | add_parmsT (rs, Link (r as ref (Param _))) = r ins rs
   197   | add_parmsT (rs, Link (ref T)) = add_parmsT (rs, T)
   198   | add_parmsT (rs, _) = rs;
   199 
   200 val add_parms = foldl_pretyps add_parmsT;
   201 
   202 
   203 (* add_names *)
   204 
   205 fun add_namesT (xs, PType (_, Ts)) = Library.foldl add_namesT (xs, Ts)
   206   | add_namesT (xs, PTFree (x, _)) = x ins xs
   207   | add_namesT (xs, PTVar ((x, _), _)) = x ins xs
   208   | add_namesT (xs, Link (ref T)) = add_namesT (xs, T)
   209   | add_namesT (xs, Param _) = xs;
   210 
   211 val add_names = foldl_pretyps add_namesT;
   212 
   213 
   214 (* simple_typ/term_of *)
   215 
   216 (*deref links, fail on params*)
   217 fun simple_typ_of (PType (a, Ts)) = Type (a, map simple_typ_of Ts)
   218   | simple_typ_of (PTFree v) = TFree v
   219   | simple_typ_of (PTVar v) = TVar v
   220   | simple_typ_of (Link (ref T)) = simple_typ_of T
   221   | simple_typ_of (Param _) = sys_error "simple_typ_of: illegal Param";
   222 
   223 (*convert types, drop constraints*)
   224 fun simple_term_of (PConst (c, T)) = Const (c, simple_typ_of T)
   225   | simple_term_of (PFree (x, T)) = Free (x, simple_typ_of T)
   226   | simple_term_of (PVar (xi, T)) = Var (xi, simple_typ_of T)
   227   | simple_term_of (PBound i) = Bound i
   228   | simple_term_of (PAbs (x, T, t)) = Abs (x, simple_typ_of T, simple_term_of t)
   229   | simple_term_of (PAppl (t, u)) = simple_term_of t $ simple_term_of u
   230   | simple_term_of (Constraint (t, _)) = simple_term_of t;
   231 
   232 
   233 (* typs_terms_of *)                             (*DESTRUCTIVE*)
   234 
   235 fun typs_terms_of used mk_var prfx (Ts, ts) =
   236   let
   237     fun elim (r as ref (Param S), x) = r := mk_var (x, S)
   238       | elim _ = ();
   239 
   240     val used' = Library.foldl add_names (Library.foldl add_namesT (used, Ts), ts);
   241     val parms = rev (Library.foldl add_parms (Library.foldl add_parmsT ([], Ts), ts));
   242     val names = Term.invent_names used' (prfx ^ "'a") (length parms);
   243   in
   244     seq2 elim (parms, names);
   245     (map simple_typ_of Ts, map simple_term_of ts)
   246   end;
   247 
   248 
   249 
   250 (** order-sorted unification of types **)       (*DESTRUCTIVE*)
   251 
   252 exception NO_UNIFIER of string;
   253 
   254 
   255 fun unify pp classes arities =
   256   let
   257 
   258     (* adjust sorts of parameters *)
   259 
   260     fun not_in_sort x S' S =
   261       "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
   262         Pretty.string_of_sort pp S;
   263 
   264     fun no_domain (a, c) = "No way to get " ^ Pretty.string_of_arity pp (a, [], [c]);
   265 
   266     fun meet (_, []) = ()
   267       | meet (Link (r as (ref (Param S'))), S) =
   268           if Sorts.sort_le classes (S', S) then ()
   269           else r := mk_param (Sorts.inter_sort classes (S', S))
   270       | meet (Link (ref T), S) = meet (T, S)
   271       | meet (PType (a, Ts), S) =
   272           seq2 meet (Ts, Sorts.mg_domain (classes, arities) a S
   273             handle Sorts.DOMAIN ac => raise NO_UNIFIER (no_domain ac))
   274       | meet (PTFree (x, S'), S) =
   275           if Sorts.sort_le classes (S', S) then ()
   276           else raise NO_UNIFIER (not_in_sort x S' S)
   277       | meet (PTVar (xi, S'), S) =
   278           if Sorts.sort_le classes (S', S) then ()
   279           else raise NO_UNIFIER (not_in_sort (Syntax.string_of_vname xi) S' S)
   280       | meet (Param _, _) = sys_error "meet";
   281 
   282 
   283     (* occurs check and assigment *)
   284 
   285     fun occurs_check r (Link (r' as ref T)) =
   286           if r = r' then raise NO_UNIFIER "Occurs check!"
   287           else occurs_check r T
   288       | occurs_check r (PType (_, Ts)) = List.app (occurs_check r) Ts
   289       | occurs_check _ _ = ();
   290 
   291     fun assign r T S =
   292       (case deref T of
   293         T' as Link (r' as ref (Param _)) =>
   294           if r = r' then () else (meet (T', S); r := T')
   295       | T' => (occurs_check r T'; meet (T', S); r := T'));
   296 
   297 
   298     (* unification *)
   299 
   300     fun unif (Link (r as ref (Param S)), T) = assign r T S
   301       | unif (T, Link (r as ref (Param S))) = assign r T S
   302       | unif (Link (ref T), U) = unif (T, U)
   303       | unif (T, Link (ref U)) = unif (T, U)
   304       | unif (PType (a, Ts), PType (b, Us)) =
   305           if a <> b then
   306             raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b)
   307           else seq2 unif (Ts, Us)
   308       | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
   309 
   310   in unif end;
   311 
   312 
   313 
   314 (** type inference **)
   315 
   316 fun appl_error pp why t T u U =
   317  ["Type error in application: " ^ why,
   318   "",
   319   Pretty.string_of (Pretty.block
   320     [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
   321       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
   322   Pretty.string_of (Pretty.block
   323     [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
   324       Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
   325   ""];
   326 
   327 
   328 (* infer *)                                     (*DESTRUCTIVE*)
   329 
   330 fun infer pp classes arities =
   331   let
   332     (* errors *)
   333 
   334     fun unif_failed msg =
   335       "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
   336 
   337     fun prep_output bs ts Ts =
   338       let
   339         val (Ts_bTs', ts') = typs_terms_of [] PTFree "??" (Ts @ map snd bs, ts);
   340         val (Ts',Ts'') = Library.splitAt(length Ts, Ts_bTs');
   341         val xs = map Free (map fst bs ~~ Ts'');
   342         val ts'' = map (fn t => subst_bounds (xs, t)) ts';
   343       in (ts'', Ts') end;
   344 
   345     fun err_loose i =
   346       raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
   347 
   348     fun err_appl msg bs t T u U =
   349       let
   350         val ([t', u'], [T', U']) = prep_output bs [t, u] [T, U];
   351         val why =
   352           (case T' of
   353             Type ("fun", _) => "Incompatible operand type"
   354           | _ => "Operator not of function type");
   355         val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
   356       in raise TYPE (text, [T', U'], [t', u']) end;
   357 
   358     fun err_constraint msg bs t T U =
   359       let
   360         val ([t'], [T', U']) = prep_output bs [t] [T, U];
   361         val text = cat_lines
   362          [unif_failed msg,
   363           "Cannot meet type constraint:", "",
   364           Pretty.string_of (Pretty.block
   365            [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
   366             Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
   367           Pretty.string_of (Pretty.block
   368            [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
   369       in raise TYPE (text, [T', U'], [t']) end;
   370 
   371 
   372     (* main *)
   373 
   374     val unif = unify pp classes arities;
   375 
   376     fun inf _ (PConst (_, T)) = T
   377       | inf _ (PFree (_, T)) = T
   378       | inf _ (PVar (_, T)) = T
   379       | inf bs (PBound i) = snd (List.nth (bs, i) handle Subscript => err_loose i)
   380       | inf bs (PAbs (x, T, t)) = PType ("fun", [T, inf ((x, T) :: bs) t])
   381       | inf bs (PAppl (t, u)) =
   382           let
   383             val T = inf bs t;
   384             val U = inf bs u;
   385             val V = mk_param [];
   386             val U_to_V = PType ("fun", [U, V]);
   387             val _ = unif (U_to_V, T) handle NO_UNIFIER msg => err_appl msg bs t T u U;
   388           in V end
   389       | inf bs (Constraint (t, U)) =
   390           let val T = inf bs t in
   391             unif (T, U) handle NO_UNIFIER msg => err_constraint msg bs t T U;
   392             T
   393           end;
   394 
   395   in inf [] end;
   396 
   397 
   398 (* basic_infer_types *)
   399 
   400 fun basic_infer_types pp const_type classes arities used freeze is_param ts Ts =
   401   let
   402     (*convert to preterms/typs*)
   403     val (Tps, Ts') = pretyps_of (K true) ([], Ts);
   404     val ((vps, ps), ts') = preterms_of const_type is_param (([], Tps), ts);
   405 
   406     (*run type inference*)
   407     val tTs' = ListPair.map Constraint (ts', Ts');
   408     val _ = List.app (fn t => (infer pp classes arities t; ())) tTs';
   409 
   410     (*collect result unifier*)
   411     fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); NONE)
   412       | ch_var xi_T = SOME xi_T;
   413     val env = List.mapPartial ch_var Tps;
   414 
   415     (*convert back to terms/typs*)
   416     val mk_var =
   417       if freeze then PTFree
   418       else (fn (x, S) => PTVar ((x, 0), S));
   419     val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
   420     val final_env = map (apsnd simple_typ_of) env;
   421   in (final_ts, final_Ts, final_env) end;
   422 
   423 
   424 
   425 (** type inference **)
   426 
   427 (* user constraints *)
   428 
   429 fun constrain t T =
   430   if T = dummyT then t
   431   else Const ("_type_constraint_", T) $ t;
   432 
   433 
   434 (* user parameters *)
   435 
   436 fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
   437 fun param i (x, S) = TVar (("?" ^ x, i), S);
   438 
   439 fun paramify_dummies (maxidx, TFree ("'_dummy_", S)) =
   440       (maxidx + 1, param (maxidx + 1) ("'dummy", S))
   441   | paramify_dummies (maxidx, Type (a, Ts)) =
   442       let val (maxidx', Ts') = foldl_map paramify_dummies (maxidx, Ts)
   443       in (maxidx', Type (a, Ts')) end
   444   | paramify_dummies arg = arg;
   445 
   446 
   447 (* decode sort constraints *)
   448 
   449 fun get_sort tsig def_sort map_sort raw_env =
   450   let
   451     fun eq ((xi, S), (xi', S')) =
   452       xi = xi' andalso Type.eq_sort tsig (S, S');
   453 
   454     val env = gen_distinct eq (map (apsnd map_sort) raw_env);
   455     val _ = (case gen_duplicates eq_fst env of [] => ()
   456       | dups => error ("Inconsistent sort constraints for type variable(s) "
   457           ^ commas_quote (map (Syntax.string_of_vname' o fst) dups)));
   458 
   459     fun get xi =
   460       (case (assoc (env, xi), def_sort xi) of
   461         (NONE, NONE) => Type.defaultS tsig
   462       | (NONE, SOME S) => S
   463       | (SOME S, NONE) => S
   464       | (SOME S, SOME S') =>
   465           if Type.eq_sort tsig (S, S') then S'
   466           else error ("Sort constraint inconsistent with default for type variable " ^
   467             quote (Syntax.string_of_vname' xi)));
   468   in get end;
   469 
   470 
   471 (* decode_types -- transform parse tree into raw term *)
   472 
   473 fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
   474   let
   475     fun get_type xi = getOpt (def_type xi, dummyT);
   476     fun is_free x = isSome (def_type (x, ~1));
   477     val raw_env = Syntax.raw_term_sorts tm;
   478     val sort_of = get_sort tsig def_sort map_sort raw_env;
   479 
   480     val certT = Type.cert_typ tsig o map_type;
   481     fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
   482 
   483     fun decode (Const ("_constrain", _) $ t $ typ) =
   484           constrain (decode t) (decodeT typ)
   485       | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
   486           if T = dummyT then Abs (x, decodeT typ, decode t)
   487           else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
   488       | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
   489       | decode (t $ u) = decode t $ decode u
   490       | decode (Free (x, T)) =
   491           let val c = map_const x in
   492             if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
   493               Const (c, certT T)
   494             else if T = dummyT then Free (x, get_type (x, ~1))
   495             else constrain (Free (x, certT T)) (get_type (x, ~1))
   496           end
   497       | decode (Var (xi, T)) =
   498           if T = dummyT then Var (xi, get_type xi)
   499           else constrain (Var (xi, certT T)) (get_type xi)
   500       | decode (t as Bound _) = t
   501       | decode (Const (c, T)) = Const (map_const c, certT T);
   502   in decode tm end;
   503 
   504 
   505 (* infer_types *)
   506 
   507 (*Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
   508   unifies with Ti (for i=1,...,n).
   509 
   510   tsig: type signature
   511   const_type: name mapping and signature lookup
   512   def_type: partial map from indexnames to types (constrains Frees, Vars)
   513   def_sort: partial map from indexnames to sorts (constrains TFrees, TVars)
   514   used: list of already used type variables
   515   freeze: if true then generated parameters are turned into TFrees, else TVars*)
   516 
   517 fun infer_types pp tsig const_type def_type def_sort
   518     map_const map_type map_sort used freeze pat_Ts raw_ts =
   519   let
   520     val {classes, arities, ...} = Type.rep_tsig tsig;
   521     val pat_Ts' = map (Type.cert_typ tsig) pat_Ts;
   522     val is_const = isSome o const_type;
   523     val raw_ts' =
   524       map (decode_types tsig is_const def_type def_sort map_const map_type map_sort) raw_ts;
   525     val (ts, Ts, unifier) = basic_infer_types pp const_type
   526       classes arities used freeze is_param raw_ts' pat_Ts';
   527   in (ts, unifier) end;
   528 
   529 end;