src/Pure/type_infer.ML
author wenzelm
Tue Apr 25 22:23:30 2006 +0200 (2006-04-25)
changeset 19465 e6093a7fa53a
parent 19046 bc5c6c9b114e
child 19482 9f11af8f7ef9
permissions -rw-r--r--
refer to structure Type instead of Sorts;
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@14788
    23
    -> (sort -> sort) -> string list -> 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@2957
   104
(* pretyp(s)_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@2957
   116
fun pretyp_of is_param (params, typ) =
wenzelm@2957
   117
  let
wenzelm@16195
   118
    fun add_parms (TVar (xi as (x, _), S)) ps =
wenzelm@17282
   119
          if is_param xi andalso not (AList.defined (op =) ps xi)
wenzelm@2957
   120
          then (xi, mk_param S) :: ps else ps
wenzelm@16195
   121
      | add_parms (TFree _) ps = ps
wenzelm@16195
   122
      | add_parms (Type (_, Ts)) ps = fold add_parms Ts ps;
wenzelm@2957
   123
wenzelm@16195
   124
    val params' = add_parms typ params;
wenzelm@2957
   125
wenzelm@2957
   126
    fun pre_of (TVar (v as (xi, _))) =
haftmann@17271
   127
          (case AList.lookup (op =) params' xi of
skalberg@15531
   128
            NONE => PTVar v
skalberg@15531
   129
          | SOME p => p)
wenzelm@8087
   130
      | pre_of (TFree ("'_dummy_", S)) = mk_param S
wenzelm@2957
   131
      | pre_of (TFree v) = PTFree v
wenzelm@2957
   132
      | pre_of (T as Type (a, Ts)) =
wenzelm@2957
   133
          if T = dummyT then mk_param []
wenzelm@2957
   134
          else PType (a, map pre_of Ts);
wenzelm@2957
   135
  in (params', pre_of typ) end;
wenzelm@2957
   136
wenzelm@4957
   137
fun pretyps_of is_param = foldl_map (pretyp_of is_param);
wenzelm@2957
   138
wenzelm@2957
   139
wenzelm@2957
   140
(* preterm(s)_of *)
wenzelm@2957
   141
wenzelm@2957
   142
fun preterm_of const_type is_param ((vparams, params), tm) =
wenzelm@2957
   143
  let
wenzelm@2957
   144
    fun add_vparm (ps, xi) =
wenzelm@17282
   145
      if not (AList.defined (op =) ps xi) then
wenzelm@2957
   146
        (xi, mk_param []) :: ps
wenzelm@2957
   147
      else ps;
wenzelm@2957
   148
wenzelm@8611
   149
    fun add_vparms (ps, Var (xi, Type ("_polymorphic_", _))) = ps
wenzelm@8611
   150
      | add_vparms (ps, Var (xi, _)) = add_vparm (ps, xi)
wenzelm@2957
   151
      | add_vparms (ps, Free (x, _)) = add_vparm (ps, (x, ~1))
wenzelm@2957
   152
      | add_vparms (ps, Abs (_, _, t)) = add_vparms (ps, t)
wenzelm@2957
   153
      | add_vparms (ps, t $ u) = add_vparms (add_vparms (ps, t), u)
wenzelm@2957
   154
      | add_vparms (ps, _) = ps;
wenzelm@2957
   155
wenzelm@2957
   156
    val vparams' = add_vparms (vparams, tm);
haftmann@17271
   157
    fun var_param xi = (the o AList.lookup (op =) vparams') xi;
wenzelm@2957
   158
wenzelm@2957
   159
wenzelm@2957
   160
    val preT_of = pretyp_of is_param;
wenzelm@2957
   161
wenzelm@2957
   162
    fun constrain (ps, t) T =
wenzelm@2957
   163
      if T = dummyT then (ps, t)
wenzelm@2957
   164
      else
wenzelm@8087
   165
        let val (ps', T') = preT_of (ps, T)
wenzelm@8087
   166
        in (ps', Constraint (t, T')) end;
wenzelm@2957
   167
wenzelm@2957
   168
    fun pre_of (ps, Const (c, T)) =
wenzelm@2957
   169
          (case const_type c of
skalberg@15531
   170
            SOME U => constrain (ps, PConst (c, snd (pretyp_of (K true) ([], U)))) T
skalberg@15531
   171
          | NONE => raise TYPE ("No such constant: " ^ quote c, [], []))
wenzelm@8611
   172
      | pre_of (ps, Var (xi, Type ("_polymorphic_", [T]))) =
wenzelm@8611
   173
          (ps, PVar (xi, snd (pretyp_of (K true) ([], T))))
wenzelm@8611
   174
      | pre_of (ps, Var (xi, T)) = constrain (ps, PVar (xi, var_param xi)) T
wenzelm@2957
   175
      | pre_of (ps, Free (x, T)) = constrain (ps, PFree (x, var_param (x, ~1))) T
wenzelm@2957
   176
      | pre_of (ps, Const ("_type_constraint_", T) $ t) = constrain (pre_of (ps, t)) T
wenzelm@2957
   177
      | pre_of (ps, Bound i) = (ps, PBound i)
wenzelm@2957
   178
      | pre_of (ps, Abs (x, T, t)) =
wenzelm@2957
   179
          let
wenzelm@2957
   180
            val (ps', T') = preT_of (ps, T);
wenzelm@2957
   181
            val (ps'', t') = pre_of (ps', t);
wenzelm@2957
   182
          in (ps'', PAbs (x, T', t')) end
wenzelm@2957
   183
      | pre_of (ps, t $ u) =
wenzelm@2957
   184
          let
wenzelm@2957
   185
            val (ps', t') = pre_of (ps, t);
wenzelm@2957
   186
            val (ps'', u') = pre_of (ps', u);
wenzelm@2957
   187
          in (ps'', PAppl (t', u')) end;
wenzelm@2957
   188
wenzelm@2957
   189
    val (params', tm') = pre_of (params, tm);
wenzelm@8611
   190
  in ((vparams', params'), tm') end;
wenzelm@2957
   191
wenzelm@4957
   192
fun preterms_of const_type is_param = foldl_map (preterm_of const_type is_param);
wenzelm@2957
   193
wenzelm@2957
   194
wenzelm@2957
   195
wenzelm@2957
   196
(** pretyps/terms to typs/terms **)
wenzelm@2957
   197
wenzelm@2957
   198
(* add_parms *)
wenzelm@2957
   199
wenzelm@16195
   200
fun add_parmsT (PType (_, Ts)) rs = fold add_parmsT Ts rs
wenzelm@16195
   201
  | add_parmsT (Link (r as ref (Param _))) rs = r ins rs
wenzelm@16195
   202
  | add_parmsT (Link (ref T)) rs = add_parmsT T rs
wenzelm@16195
   203
  | add_parmsT _ rs = rs;
wenzelm@2957
   204
wenzelm@16195
   205
val add_parms = fold_pretyps add_parmsT;
wenzelm@2957
   206
wenzelm@2957
   207
wenzelm@2957
   208
(* add_names *)
wenzelm@2957
   209
wenzelm@16195
   210
fun add_namesT (PType (_, Ts)) xs = fold add_namesT Ts xs
wenzelm@16195
   211
  | add_namesT (PTFree (x, _)) xs = x ins_string xs
wenzelm@16195
   212
  | add_namesT (PTVar ((x, _), _)) xs = x ins_string xs
wenzelm@16195
   213
  | add_namesT (Link (ref T)) xs = add_namesT T xs
wenzelm@16195
   214
  | add_namesT (Param _) xs = xs;
wenzelm@2957
   215
wenzelm@16195
   216
val add_names = fold_pretyps add_namesT;
wenzelm@2957
   217
wenzelm@2957
   218
wenzelm@2957
   219
(* simple_typ/term_of *)
wenzelm@2957
   220
wenzelm@2957
   221
(*deref links, fail on params*)
wenzelm@2957
   222
fun simple_typ_of (PType (a, Ts)) = Type (a, map simple_typ_of Ts)
wenzelm@2957
   223
  | simple_typ_of (PTFree v) = TFree v
wenzelm@2957
   224
  | simple_typ_of (PTVar v) = TVar v
wenzelm@2957
   225
  | simple_typ_of (Link (ref T)) = simple_typ_of T
wenzelm@2957
   226
  | simple_typ_of (Param _) = sys_error "simple_typ_of: illegal Param";
wenzelm@2957
   227
wenzelm@2957
   228
(*convert types, drop constraints*)
wenzelm@2957
   229
fun simple_term_of (PConst (c, T)) = Const (c, simple_typ_of T)
wenzelm@2957
   230
  | simple_term_of (PFree (x, T)) = Free (x, simple_typ_of T)
wenzelm@2957
   231
  | simple_term_of (PVar (xi, T)) = Var (xi, simple_typ_of T)
wenzelm@2957
   232
  | simple_term_of (PBound i) = Bound i
wenzelm@2957
   233
  | simple_term_of (PAbs (x, T, t)) = Abs (x, simple_typ_of T, simple_term_of t)
wenzelm@2957
   234
  | simple_term_of (PAppl (t, u)) = simple_term_of t $ simple_term_of u
wenzelm@2957
   235
  | simple_term_of (Constraint (t, _)) = simple_term_of t;
wenzelm@2957
   236
wenzelm@2957
   237
wenzelm@2957
   238
(* typs_terms_of *)                             (*DESTRUCTIVE*)
wenzelm@2957
   239
wenzelm@2957
   240
fun typs_terms_of used mk_var prfx (Ts, ts) =
wenzelm@2957
   241
  let
wenzelm@4957
   242
    fun elim (r as ref (Param S), x) = r := mk_var (x, S)
wenzelm@4957
   243
      | elim _ = ();
wenzelm@2957
   244
wenzelm@16195
   245
    val used' = fold add_names ts (fold add_namesT Ts used);
wenzelm@16195
   246
    val parms = rev (fold add_parms ts (fold add_parmsT Ts []));
wenzelm@14695
   247
    val names = Term.invent_names used' (prfx ^ "'a") (length parms);
wenzelm@2957
   248
  in
wenzelm@16195
   249
    ListPair.app elim (parms, names);
wenzelm@2957
   250
    (map simple_typ_of Ts, map simple_term_of ts)
wenzelm@2957
   251
  end;
wenzelm@2957
   252
wenzelm@2957
   253
wenzelm@2957
   254
wenzelm@2957
   255
(** order-sorted unification of types **)       (*DESTRUCTIVE*)
wenzelm@2957
   256
wenzelm@2957
   257
exception NO_UNIFIER of string;
wenzelm@2957
   258
wenzelm@2957
   259
wenzelm@19465
   260
fun unify pp tsig =
wenzelm@2957
   261
  let
wenzelm@2957
   262
wenzelm@2957
   263
    (* adjust sorts of parameters *)
wenzelm@2957
   264
wenzelm@19465
   265
    fun not_of_sort x S' S =
wenzelm@14828
   266
      "Variable " ^ x ^ "::" ^ Pretty.string_of_sort pp S' ^ " not of sort " ^
wenzelm@14828
   267
        Pretty.string_of_sort pp S;
wenzelm@2957
   268
wenzelm@4957
   269
    fun meet (_, []) = ()
wenzelm@4957
   270
      | meet (Link (r as (ref (Param S'))), S) =
wenzelm@19465
   271
          if Type.subsort tsig (S', S) then ()
wenzelm@19465
   272
          else r := mk_param (Type.inter_sort tsig (S', S))
wenzelm@4957
   273
      | meet (Link (ref T), S) = meet (T, S)
wenzelm@4957
   274
      | meet (PType (a, Ts), S) =
wenzelm@19465
   275
          ListPair.app meet (Ts, Type.arity_sorts pp tsig a S
wenzelm@19465
   276
            handle ERROR msg => raise NO_UNIFIER msg)
wenzelm@4957
   277
      | meet (PTFree (x, S'), S) =
wenzelm@19465
   278
          if Type.subsort tsig (S', S) then ()
wenzelm@19465
   279
          else raise NO_UNIFIER (not_of_sort x S' S)
wenzelm@4957
   280
      | meet (PTVar (xi, S'), S) =
wenzelm@19465
   281
          if Type.subsort tsig (S', S) then ()
wenzelm@19465
   282
          else raise NO_UNIFIER (not_of_sort (Syntax.string_of_vname xi) S' S)
wenzelm@4957
   283
      | meet (Param _, _) = sys_error "meet";
wenzelm@2957
   284
wenzelm@2957
   285
wenzelm@2957
   286
    (* occurs check and assigment *)
wenzelm@2957
   287
wenzelm@2957
   288
    fun occurs_check r (Link (r' as ref T)) =
wenzelm@2957
   289
          if r = r' then raise NO_UNIFIER "Occurs check!"
wenzelm@2957
   290
          else occurs_check r T
skalberg@15570
   291
      | occurs_check r (PType (_, Ts)) = List.app (occurs_check r) Ts
wenzelm@2957
   292
      | occurs_check _ _ = ();
wenzelm@2957
   293
wenzelm@2957
   294
    fun assign r T S =
wenzelm@2957
   295
      (case deref T of
wenzelm@2957
   296
        T' as Link (r' as ref (Param _)) =>
wenzelm@8087
   297
          if r = r' then () else (meet (T', S); r := T')
wenzelm@8087
   298
      | T' => (occurs_check r T'; meet (T', S); r := T'));
wenzelm@2957
   299
wenzelm@2957
   300
wenzelm@2957
   301
    (* unification *)
wenzelm@2957
   302
wenzelm@4957
   303
    fun unif (Link (r as ref (Param S)), T) = assign r T S
wenzelm@4957
   304
      | unif (T, Link (r as ref (Param S))) = assign r T S
wenzelm@4957
   305
      | unif (Link (ref T), U) = unif (T, U)
wenzelm@4957
   306
      | unif (T, Link (ref U)) = unif (T, U)
wenzelm@4957
   307
      | unif (PType (a, Ts), PType (b, Us)) =
wenzelm@2979
   308
          if a <> b then
wenzelm@14828
   309
            raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b)
wenzelm@16195
   310
          else ListPair.app unif (Ts, Us)
wenzelm@4957
   311
      | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
wenzelm@2957
   312
wenzelm@2957
   313
  in unif end;
wenzelm@2957
   314
wenzelm@2957
   315
wenzelm@2957
   316
wenzelm@2957
   317
(** type inference **)
wenzelm@2957
   318
wenzelm@14828
   319
fun appl_error pp why t T u U =
wenzelm@8087
   320
 ["Type error in application: " ^ why,
wenzelm@8087
   321
  "",
wenzelm@8087
   322
  Pretty.string_of (Pretty.block
wenzelm@14828
   323
    [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
wenzelm@14828
   324
      Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
wenzelm@8087
   325
  Pretty.string_of (Pretty.block
wenzelm@14828
   326
    [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
wenzelm@14828
   327
      Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
wenzelm@8087
   328
  ""];
wenzelm@8087
   329
nipkow@5635
   330
wenzelm@2957
   331
(* infer *)                                     (*DESTRUCTIVE*)
wenzelm@2957
   332
wenzelm@19465
   333
fun infer pp tsig =
wenzelm@2957
   334
  let
wenzelm@2979
   335
    (* errors *)
wenzelm@2957
   336
wenzelm@2979
   337
    fun unif_failed msg =
wenzelm@14828
   338
      "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
wenzelm@2979
   339
wenzelm@2979
   340
    fun prep_output bs ts Ts =
wenzelm@2957
   341
      let
wenzelm@2957
   342
        val (Ts_bTs', ts') = typs_terms_of [] PTFree "??" (Ts @ map snd bs, ts);
wenzelm@19012
   343
        val (Ts', Ts'') = chop (length Ts) Ts_bTs';
nipkow@13629
   344
        val xs = map Free (map fst bs ~~ Ts'');
wenzelm@2957
   345
        val ts'' = map (fn t => subst_bounds (xs, t)) ts';
wenzelm@2979
   346
      in (ts'', Ts') end;
wenzelm@2979
   347
wenzelm@2979
   348
    fun err_loose i =
wenzelm@3784
   349
      raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
wenzelm@2979
   350
wenzelm@3510
   351
    fun err_appl msg bs t T u U =
wenzelm@2979
   352
      let
wenzelm@3510
   353
        val ([t', u'], [T', U']) = prep_output bs [t, u] [T, U];
wenzelm@3510
   354
        val why =
wenzelm@3510
   355
          (case T' of
wenzelm@14828
   356
            Type ("fun", _) => "Incompatible operand type"
wenzelm@14828
   357
          | _ => "Operator not of function type");
wenzelm@14828
   358
        val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
wenzelm@3784
   359
      in raise TYPE (text, [T', U'], [t', u']) end;
wenzelm@2979
   360
wenzelm@2979
   361
    fun err_constraint msg bs t T U =
wenzelm@2979
   362
      let
wenzelm@2979
   363
        val ([t'], [T', U']) = prep_output bs [t] [T, U];
wenzelm@2979
   364
        val text = cat_lines
wenzelm@2979
   365
         [unif_failed msg,
nipkow@5635
   366
          "Cannot meet type constraint:", "",
wenzelm@14828
   367
          Pretty.string_of (Pretty.block
wenzelm@14828
   368
           [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
wenzelm@14828
   369
            Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
wenzelm@14828
   370
          Pretty.string_of (Pretty.block
wenzelm@14828
   371
           [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
wenzelm@3784
   372
      in raise TYPE (text, [T', U'], [t']) end;
wenzelm@2979
   373
wenzelm@2979
   374
wenzelm@2979
   375
    (* main *)
wenzelm@2979
   376
wenzelm@19465
   377
    val unif = unify pp tsig;
wenzelm@2957
   378
wenzelm@2957
   379
    fun inf _ (PConst (_, T)) = T
wenzelm@2957
   380
      | inf _ (PFree (_, T)) = T
wenzelm@2957
   381
      | inf _ (PVar (_, T)) = T
skalberg@15570
   382
      | inf bs (PBound i) = snd (List.nth (bs, i) handle Subscript => err_loose i)
wenzelm@2957
   383
      | inf bs (PAbs (x, T, t)) = PType ("fun", [T, inf ((x, T) :: bs) t])
wenzelm@2957
   384
      | inf bs (PAppl (t, u)) =
wenzelm@2957
   385
          let
wenzelm@2957
   386
            val T = inf bs t;
wenzelm@2957
   387
            val U = inf bs u;
wenzelm@2957
   388
            val V = mk_param [];
wenzelm@2957
   389
            val U_to_V = PType ("fun", [U, V]);
wenzelm@4957
   390
            val _ = unif (U_to_V, T) handle NO_UNIFIER msg => err_appl msg bs t T u U;
wenzelm@2957
   391
          in V end
wenzelm@2957
   392
      | inf bs (Constraint (t, U)) =
wenzelm@2957
   393
          let val T = inf bs t in
wenzelm@4957
   394
            unif (T, U) handle NO_UNIFIER msg => err_constraint msg bs t T U;
wenzelm@2957
   395
            T
wenzelm@2957
   396
          end;
wenzelm@2957
   397
wenzelm@2957
   398
  in inf [] end;
wenzelm@2957
   399
wenzelm@2957
   400
wenzelm@14788
   401
(* basic_infer_types *)
wenzelm@2957
   402
wenzelm@19465
   403
fun basic_infer_types pp tsig const_type used freeze is_param ts Ts =
wenzelm@2957
   404
  let
wenzelm@2957
   405
    (*convert to preterms/typs*)
wenzelm@2957
   406
    val (Tps, Ts') = pretyps_of (K true) ([], Ts);
wenzelm@2957
   407
    val ((vps, ps), ts') = preterms_of const_type is_param (([], Tps), ts);
wenzelm@2957
   408
wenzelm@2957
   409
    (*run type inference*)
wenzelm@2957
   410
    val tTs' = ListPair.map Constraint (ts', Ts');
wenzelm@19465
   411
    val _ = List.app (fn t => (infer pp tsig t; ())) tTs';
wenzelm@2957
   412
wenzelm@2957
   413
    (*collect result unifier*)
skalberg@15531
   414
    fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); NONE)
skalberg@15531
   415
      | ch_var xi_T = SOME xi_T;
skalberg@15570
   416
    val env = List.mapPartial ch_var Tps;
wenzelm@2957
   417
wenzelm@2957
   418
    (*convert back to terms/typs*)
wenzelm@2957
   419
    val mk_var =
wenzelm@2957
   420
      if freeze then PTFree
wenzelm@2957
   421
      else (fn (x, S) => PTVar ((x, 0), S));
wenzelm@2957
   422
    val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
wenzelm@2957
   423
    val final_env = map (apsnd simple_typ_of) env;
wenzelm@14788
   424
  in (final_ts, final_Ts, final_env) end;
wenzelm@14788
   425
wenzelm@14788
   426
wenzelm@14788
   427
wenzelm@14788
   428
(** type inference **)
wenzelm@14788
   429
wenzelm@14788
   430
(* user constraints *)
wenzelm@14788
   431
wenzelm@14788
   432
fun constrain t T =
wenzelm@14788
   433
  if T = dummyT then t
wenzelm@14788
   434
  else Const ("_type_constraint_", T) $ t;
wenzelm@14788
   435
wenzelm@14788
   436
wenzelm@14788
   437
(* user parameters *)
wenzelm@14788
   438
wenzelm@14788
   439
fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
wenzelm@14788
   440
fun param i (x, S) = TVar (("?" ^ x, i), S);
wenzelm@14788
   441
wenzelm@18339
   442
val paramify_dummies =
wenzelm@18339
   443
  let
wenzelm@18339
   444
    fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
wenzelm@18339
   445
wenzelm@18339
   446
    fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
wenzelm@18339
   447
      | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
wenzelm@18339
   448
      | paramify (Type (a, Ts)) maxidx =
wenzelm@18339
   449
          let val (Ts', maxidx') = fold_map paramify Ts maxidx
wenzelm@18339
   450
          in (Type (a, Ts'), maxidx') end
wenzelm@18339
   451
      | paramify T maxidx = (T, maxidx);
wenzelm@18339
   452
  in paramify end;
wenzelm@14788
   453
wenzelm@14788
   454
wenzelm@14788
   455
(* decode sort constraints *)
wenzelm@14788
   456
wenzelm@14788
   457
fun get_sort tsig def_sort map_sort raw_env =
wenzelm@14788
   458
  let
wenzelm@16668
   459
    fun eq ((xi: indexname, S), (xi', S')) =
wenzelm@14788
   460
      xi = xi' andalso Type.eq_sort tsig (S, S');
wenzelm@14788
   461
wenzelm@19046
   462
    val env = distinct eq (map (apsnd map_sort) raw_env);
wenzelm@18964
   463
    val _ = (case duplicates (eq_fst (op =)) env of [] => ()
wenzelm@14828
   464
      | dups => error ("Inconsistent sort constraints for type variable(s) "
wenzelm@14828
   465
          ^ commas_quote (map (Syntax.string_of_vname' o fst) dups)));
wenzelm@14788
   466
wenzelm@14788
   467
    fun get xi =
haftmann@17271
   468
      (case (AList.lookup (op =) env xi, def_sort xi) of
skalberg@15531
   469
        (NONE, NONE) => Type.defaultS tsig
skalberg@15531
   470
      | (NONE, SOME S) => S
skalberg@15531
   471
      | (SOME S, NONE) => S
skalberg@15531
   472
      | (SOME S, SOME S') =>
wenzelm@14788
   473
          if Type.eq_sort tsig (S, S') then S'
wenzelm@14788
   474
          else error ("Sort constraint inconsistent with default for type variable " ^
wenzelm@14788
   475
            quote (Syntax.string_of_vname' xi)));
wenzelm@14788
   476
  in get end;
wenzelm@2957
   477
wenzelm@4957
   478
wenzelm@14788
   479
(* decode_types -- transform parse tree into raw term *)
wenzelm@14788
   480
wenzelm@14788
   481
fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
wenzelm@14788
   482
  let
wenzelm@18939
   483
    fun get_type xi = the_default dummyT (def_type xi);
wenzelm@16195
   484
    fun is_free x = is_some (def_type (x, ~1));
wenzelm@14788
   485
    val raw_env = Syntax.raw_term_sorts tm;
wenzelm@14788
   486
    val sort_of = get_sort tsig def_sort map_sort raw_env;
wenzelm@14788
   487
wenzelm@14993
   488
    val certT = Type.cert_typ tsig o map_type;
wenzelm@14788
   489
    fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
wenzelm@14788
   490
wenzelm@14788
   491
    fun decode (Const ("_constrain", _) $ t $ typ) =
wenzelm@14788
   492
          constrain (decode t) (decodeT typ)
wenzelm@14788
   493
      | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
wenzelm@14788
   494
          if T = dummyT then Abs (x, decodeT typ, decode t)
wenzelm@14788
   495
          else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
wenzelm@14788
   496
      | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
wenzelm@14788
   497
      | decode (t $ u) = decode t $ decode u
wenzelm@18996
   498
      | decode (Const (x, T)) =
wenzelm@18996
   499
          let val c = (case try (unprefix Syntax.constN) x of SOME c => c | NONE => map_const x)
wenzelm@18996
   500
          in Const (c, certT T) end
wenzelm@14788
   501
      | decode (Free (x, T)) =
wenzelm@14788
   502
          let val c = map_const x in
wenzelm@14788
   503
            if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
wenzelm@14788
   504
              Const (c, certT T)
wenzelm@14788
   505
            else if T = dummyT then Free (x, get_type (x, ~1))
wenzelm@14788
   506
            else constrain (Free (x, certT T)) (get_type (x, ~1))
wenzelm@14788
   507
          end
wenzelm@14788
   508
      | decode (Var (xi, T)) =
wenzelm@14788
   509
          if T = dummyT then Var (xi, get_type xi)
wenzelm@14788
   510
          else constrain (Var (xi, certT T)) (get_type xi)
wenzelm@18996
   511
      | decode (t as Bound _) = t;
wenzelm@14788
   512
  in decode tm end;
wenzelm@14788
   513
wenzelm@14788
   514
wenzelm@14788
   515
(* infer_types *)
wenzelm@14788
   516
wenzelm@14788
   517
(*Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
wenzelm@14788
   518
  unifies with Ti (for i=1,...,n).
wenzelm@14788
   519
wenzelm@14788
   520
  tsig: type signature
wenzelm@14788
   521
  const_type: name mapping and signature lookup
wenzelm@16195
   522
  def_type: partial map from indexnames to types (constrains Frees and Vars)
wenzelm@16195
   523
  def_sort: partial map from indexnames to sorts (constrains TFrees and TVars)
wenzelm@14788
   524
  used: list of already used type variables
wenzelm@14788
   525
  freeze: if true then generated parameters are turned into TFrees, else TVars*)
wenzelm@14788
   526
wenzelm@14828
   527
fun infer_types pp tsig const_type def_type def_sort
wenzelm@14788
   528
    map_const map_type map_sort used freeze pat_Ts raw_ts =
wenzelm@14788
   529
  let
wenzelm@14993
   530
    val pat_Ts' = map (Type.cert_typ tsig) pat_Ts;
wenzelm@16195
   531
    val is_const = is_some o const_type;
wenzelm@14788
   532
    val raw_ts' =
wenzelm@14788
   533
      map (decode_types tsig is_const def_type def_sort map_const map_type map_sort) raw_ts;
wenzelm@19465
   534
    val (ts, Ts, unifier) =
wenzelm@19465
   535
      basic_infer_types pp tsig const_type used freeze is_param raw_ts' pat_Ts';
wenzelm@14788
   536
  in (ts, unifier) end;
wenzelm@14788
   537
wenzelm@2957
   538
end;