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