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