src/Pure/type_infer.ML
author wenzelm
Fri Feb 10 02:22:37 2006 +0100 (2006-02-10)
changeset 18996 1b11052ad601
parent 18964 67f572e03236
child 19012 2577ac76cdc6
permissions -rw-r--r--
decode: observe Syntax.constN;
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@14828
   260
fun unify pp classes arities =
wenzelm@2957
   261
  let
wenzelm@2957
   262
wenzelm@2957
   263
    (* adjust sorts of parameters *)
wenzelm@2957
   264
wenzelm@2957
   265
    fun not_in_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@14828
   269
    fun no_domain (a, c) = "No way to get " ^ Pretty.string_of_arity pp (a, [], [c]);
wenzelm@7639
   270
wenzelm@4957
   271
    fun meet (_, []) = ()
wenzelm@4957
   272
      | meet (Link (r as (ref (Param S'))), S) =
wenzelm@14788
   273
          if Sorts.sort_le classes (S', S) then ()
wenzelm@14788
   274
          else r := mk_param (Sorts.inter_sort classes (S', S))
wenzelm@4957
   275
      | meet (Link (ref T), S) = meet (T, S)
wenzelm@4957
   276
      | meet (PType (a, Ts), S) =
wenzelm@16195
   277
          ListPair.app meet (Ts, Sorts.mg_domain (classes, arities) a S
wenzelm@7639
   278
            handle Sorts.DOMAIN ac => raise NO_UNIFIER (no_domain ac))
wenzelm@4957
   279
      | meet (PTFree (x, S'), S) =
wenzelm@14788
   280
          if Sorts.sort_le classes (S', S) then ()
wenzelm@2957
   281
          else raise NO_UNIFIER (not_in_sort x S' S)
wenzelm@4957
   282
      | meet (PTVar (xi, S'), S) =
wenzelm@14788
   283
          if Sorts.sort_le classes (S', S) then ()
wenzelm@2957
   284
          else raise NO_UNIFIER (not_in_sort (Syntax.string_of_vname xi) S' S)
wenzelm@4957
   285
      | meet (Param _, _) = sys_error "meet";
wenzelm@2957
   286
wenzelm@2957
   287
wenzelm@2957
   288
    (* occurs check and assigment *)
wenzelm@2957
   289
wenzelm@2957
   290
    fun occurs_check r (Link (r' as ref T)) =
wenzelm@2957
   291
          if r = r' then raise NO_UNIFIER "Occurs check!"
wenzelm@2957
   292
          else occurs_check r T
skalberg@15570
   293
      | occurs_check r (PType (_, Ts)) = List.app (occurs_check r) Ts
wenzelm@2957
   294
      | occurs_check _ _ = ();
wenzelm@2957
   295
wenzelm@2957
   296
    fun assign r T S =
wenzelm@2957
   297
      (case deref T of
wenzelm@2957
   298
        T' as Link (r' as ref (Param _)) =>
wenzelm@8087
   299
          if r = r' then () else (meet (T', S); r := T')
wenzelm@8087
   300
      | T' => (occurs_check r T'; meet (T', S); r := T'));
wenzelm@2957
   301
wenzelm@2957
   302
wenzelm@2957
   303
    (* unification *)
wenzelm@2957
   304
wenzelm@4957
   305
    fun unif (Link (r as ref (Param S)), T) = assign r T S
wenzelm@4957
   306
      | unif (T, Link (r as ref (Param S))) = assign r T S
wenzelm@4957
   307
      | unif (Link (ref T), U) = unif (T, U)
wenzelm@4957
   308
      | unif (T, Link (ref U)) = unif (T, U)
wenzelm@4957
   309
      | unif (PType (a, Ts), PType (b, Us)) =
wenzelm@2979
   310
          if a <> b then
wenzelm@14828
   311
            raise NO_UNIFIER ("Clash of types " ^ quote a ^ " and " ^ quote b)
wenzelm@16195
   312
          else ListPair.app unif (Ts, Us)
wenzelm@4957
   313
      | unif (T, U) = if T = U then () else raise NO_UNIFIER "";
wenzelm@2957
   314
wenzelm@2957
   315
  in unif end;
wenzelm@2957
   316
wenzelm@2957
   317
wenzelm@2957
   318
wenzelm@2957
   319
(** type inference **)
wenzelm@2957
   320
wenzelm@14828
   321
fun appl_error pp why t T u U =
wenzelm@8087
   322
 ["Type error in application: " ^ why,
wenzelm@8087
   323
  "",
wenzelm@8087
   324
  Pretty.string_of (Pretty.block
wenzelm@14828
   325
    [Pretty.str "Operator:", Pretty.brk 2, Pretty.term pp t,
wenzelm@14828
   326
      Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T]),
wenzelm@8087
   327
  Pretty.string_of (Pretty.block
wenzelm@14828
   328
    [Pretty.str "Operand:", Pretty.brk 3, Pretty.term pp u,
wenzelm@14828
   329
      Pretty.str " ::", Pretty.brk 1, Pretty.typ pp U]),
wenzelm@8087
   330
  ""];
wenzelm@8087
   331
nipkow@5635
   332
wenzelm@2957
   333
(* infer *)                                     (*DESTRUCTIVE*)
wenzelm@2957
   334
wenzelm@14828
   335
fun infer pp classes arities =
wenzelm@2957
   336
  let
wenzelm@2979
   337
    (* errors *)
wenzelm@2957
   338
wenzelm@2979
   339
    fun unif_failed msg =
wenzelm@14828
   340
      "Type unification failed" ^ (if msg = "" then "" else ": " ^ msg) ^ "\n";
wenzelm@2979
   341
wenzelm@2979
   342
    fun prep_output bs ts Ts =
wenzelm@2957
   343
      let
wenzelm@2957
   344
        val (Ts_bTs', ts') = typs_terms_of [] PTFree "??" (Ts @ map snd bs, ts);
nipkow@13629
   345
        val (Ts',Ts'') = Library.splitAt(length Ts, Ts_bTs');
nipkow@13629
   346
        val xs = map Free (map fst bs ~~ Ts'');
wenzelm@2957
   347
        val ts'' = map (fn t => subst_bounds (xs, t)) ts';
wenzelm@2979
   348
      in (ts'', Ts') end;
wenzelm@2979
   349
wenzelm@2979
   350
    fun err_loose i =
wenzelm@3784
   351
      raise TYPE ("Loose bound variable: B." ^ string_of_int i, [], []);
wenzelm@2979
   352
wenzelm@3510
   353
    fun err_appl msg bs t T u U =
wenzelm@2979
   354
      let
wenzelm@3510
   355
        val ([t', u'], [T', U']) = prep_output bs [t, u] [T, U];
wenzelm@3510
   356
        val why =
wenzelm@3510
   357
          (case T' of
wenzelm@14828
   358
            Type ("fun", _) => "Incompatible operand type"
wenzelm@14828
   359
          | _ => "Operator not of function type");
wenzelm@14828
   360
        val text = unif_failed msg ^ cat_lines (appl_error pp why t' T' u' U');
wenzelm@3784
   361
      in raise TYPE (text, [T', U'], [t', u']) end;
wenzelm@2979
   362
wenzelm@2979
   363
    fun err_constraint msg bs t T U =
wenzelm@2979
   364
      let
wenzelm@2979
   365
        val ([t'], [T', U']) = prep_output bs [t] [T, U];
wenzelm@2979
   366
        val text = cat_lines
wenzelm@2979
   367
         [unif_failed msg,
nipkow@5635
   368
          "Cannot meet type constraint:", "",
wenzelm@14828
   369
          Pretty.string_of (Pretty.block
wenzelm@14828
   370
           [Pretty.str "Term:", Pretty.brk 2, Pretty.term pp t',
wenzelm@14828
   371
            Pretty.str " ::", Pretty.brk 1, Pretty.typ pp T']),
wenzelm@14828
   372
          Pretty.string_of (Pretty.block
wenzelm@14828
   373
           [Pretty.str "Type:", Pretty.brk 2, Pretty.typ pp U']), ""];
wenzelm@3784
   374
      in raise TYPE (text, [T', U'], [t']) end;
wenzelm@2979
   375
wenzelm@2979
   376
wenzelm@2979
   377
    (* main *)
wenzelm@2979
   378
wenzelm@14828
   379
    val unif = unify pp classes arities;
wenzelm@2957
   380
wenzelm@2957
   381
    fun inf _ (PConst (_, T)) = T
wenzelm@2957
   382
      | inf _ (PFree (_, T)) = T
wenzelm@2957
   383
      | inf _ (PVar (_, T)) = T
skalberg@15570
   384
      | inf bs (PBound i) = snd (List.nth (bs, i) handle Subscript => err_loose i)
wenzelm@2957
   385
      | inf bs (PAbs (x, T, t)) = PType ("fun", [T, inf ((x, T) :: bs) t])
wenzelm@2957
   386
      | inf bs (PAppl (t, u)) =
wenzelm@2957
   387
          let
wenzelm@2957
   388
            val T = inf bs t;
wenzelm@2957
   389
            val U = inf bs u;
wenzelm@2957
   390
            val V = mk_param [];
wenzelm@2957
   391
            val U_to_V = PType ("fun", [U, V]);
wenzelm@4957
   392
            val _ = unif (U_to_V, T) handle NO_UNIFIER msg => err_appl msg bs t T u U;
wenzelm@2957
   393
          in V end
wenzelm@2957
   394
      | inf bs (Constraint (t, U)) =
wenzelm@2957
   395
          let val T = inf bs t in
wenzelm@4957
   396
            unif (T, U) handle NO_UNIFIER msg => err_constraint msg bs t T U;
wenzelm@2957
   397
            T
wenzelm@2957
   398
          end;
wenzelm@2957
   399
wenzelm@2957
   400
  in inf [] end;
wenzelm@2957
   401
wenzelm@2957
   402
wenzelm@14788
   403
(* basic_infer_types *)
wenzelm@2957
   404
wenzelm@14828
   405
fun basic_infer_types pp const_type classes arities used freeze is_param ts Ts =
wenzelm@2957
   406
  let
wenzelm@2957
   407
    (*convert to preterms/typs*)
wenzelm@2957
   408
    val (Tps, Ts') = pretyps_of (K true) ([], Ts);
wenzelm@2957
   409
    val ((vps, ps), ts') = preterms_of const_type is_param (([], Tps), ts);
wenzelm@2957
   410
wenzelm@2957
   411
    (*run type inference*)
wenzelm@2957
   412
    val tTs' = ListPair.map Constraint (ts', Ts');
skalberg@15570
   413
    val _ = List.app (fn t => (infer pp classes arities t; ())) tTs';
wenzelm@2957
   414
wenzelm@2957
   415
    (*collect result unifier*)
skalberg@15531
   416
    fun ch_var (xi, Link (r as ref (Param S))) = (r := PTVar (xi, S); NONE)
skalberg@15531
   417
      | ch_var xi_T = SOME xi_T;
skalberg@15570
   418
    val env = List.mapPartial ch_var Tps;
wenzelm@2957
   419
wenzelm@2957
   420
    (*convert back to terms/typs*)
wenzelm@2957
   421
    val mk_var =
wenzelm@2957
   422
      if freeze then PTFree
wenzelm@2957
   423
      else (fn (x, S) => PTVar ((x, 0), S));
wenzelm@2957
   424
    val (final_Ts, final_ts) = typs_terms_of used mk_var "" (Ts', ts');
wenzelm@2957
   425
    val final_env = map (apsnd simple_typ_of) env;
wenzelm@14788
   426
  in (final_ts, final_Ts, final_env) end;
wenzelm@14788
   427
wenzelm@14788
   428
wenzelm@14788
   429
wenzelm@14788
   430
(** type inference **)
wenzelm@14788
   431
wenzelm@14788
   432
(* user constraints *)
wenzelm@14788
   433
wenzelm@14788
   434
fun constrain t T =
wenzelm@14788
   435
  if T = dummyT then t
wenzelm@14788
   436
  else Const ("_type_constraint_", T) $ t;
wenzelm@14788
   437
wenzelm@14788
   438
wenzelm@14788
   439
(* user parameters *)
wenzelm@14788
   440
wenzelm@14788
   441
fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
wenzelm@14788
   442
fun param i (x, S) = TVar (("?" ^ x, i), S);
wenzelm@14788
   443
wenzelm@18339
   444
val paramify_dummies =
wenzelm@18339
   445
  let
wenzelm@18339
   446
    fun dummy S maxidx = (param (maxidx + 1) ("'dummy", S), maxidx + 1);
wenzelm@18339
   447
wenzelm@18339
   448
    fun paramify (TFree ("'_dummy_", S)) maxidx = dummy S maxidx
wenzelm@18339
   449
      | paramify (Type ("dummy", _)) maxidx = dummy [] maxidx
wenzelm@18339
   450
      | paramify (Type (a, Ts)) maxidx =
wenzelm@18339
   451
          let val (Ts', maxidx') = fold_map paramify Ts maxidx
wenzelm@18339
   452
          in (Type (a, Ts'), maxidx') end
wenzelm@18339
   453
      | paramify T maxidx = (T, maxidx);
wenzelm@18339
   454
  in paramify end;
wenzelm@14788
   455
wenzelm@14788
   456
wenzelm@14788
   457
(* decode sort constraints *)
wenzelm@14788
   458
wenzelm@14788
   459
fun get_sort tsig def_sort map_sort raw_env =
wenzelm@14788
   460
  let
wenzelm@16668
   461
    fun eq ((xi: indexname, S), (xi', S')) =
wenzelm@14788
   462
      xi = xi' andalso Type.eq_sort tsig (S, S');
wenzelm@14788
   463
wenzelm@14788
   464
    val env = gen_distinct eq (map (apsnd map_sort) raw_env);
wenzelm@18964
   465
    val _ = (case duplicates (eq_fst (op =)) env of [] => ()
wenzelm@14828
   466
      | dups => error ("Inconsistent sort constraints for type variable(s) "
wenzelm@14828
   467
          ^ commas_quote (map (Syntax.string_of_vname' o fst) dups)));
wenzelm@14788
   468
wenzelm@14788
   469
    fun get xi =
haftmann@17271
   470
      (case (AList.lookup (op =) env xi, def_sort xi) of
skalberg@15531
   471
        (NONE, NONE) => Type.defaultS tsig
skalberg@15531
   472
      | (NONE, SOME S) => S
skalberg@15531
   473
      | (SOME S, NONE) => S
skalberg@15531
   474
      | (SOME S, SOME S') =>
wenzelm@14788
   475
          if Type.eq_sort tsig (S, S') then S'
wenzelm@14788
   476
          else error ("Sort constraint inconsistent with default for type variable " ^
wenzelm@14788
   477
            quote (Syntax.string_of_vname' xi)));
wenzelm@14788
   478
  in get end;
wenzelm@2957
   479
wenzelm@4957
   480
wenzelm@14788
   481
(* decode_types -- transform parse tree into raw term *)
wenzelm@14788
   482
wenzelm@14788
   483
fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
wenzelm@14788
   484
  let
wenzelm@18939
   485
    fun get_type xi = the_default dummyT (def_type xi);
wenzelm@16195
   486
    fun is_free x = is_some (def_type (x, ~1));
wenzelm@14788
   487
    val raw_env = Syntax.raw_term_sorts tm;
wenzelm@14788
   488
    val sort_of = get_sort tsig def_sort map_sort raw_env;
wenzelm@14788
   489
wenzelm@14993
   490
    val certT = Type.cert_typ tsig o map_type;
wenzelm@14788
   491
    fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
wenzelm@14788
   492
wenzelm@14788
   493
    fun decode (Const ("_constrain", _) $ t $ typ) =
wenzelm@14788
   494
          constrain (decode t) (decodeT typ)
wenzelm@14788
   495
      | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
wenzelm@14788
   496
          if T = dummyT then Abs (x, decodeT typ, decode t)
wenzelm@14788
   497
          else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
wenzelm@14788
   498
      | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
wenzelm@14788
   499
      | decode (t $ u) = decode t $ decode u
wenzelm@18996
   500
      | decode (Const (x, T)) =
wenzelm@18996
   501
          let val c = (case try (unprefix Syntax.constN) x of SOME c => c | NONE => map_const x)
wenzelm@18996
   502
          in Const (c, certT T) end
wenzelm@14788
   503
      | decode (Free (x, T)) =
wenzelm@14788
   504
          let val c = map_const x in
wenzelm@14788
   505
            if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
wenzelm@14788
   506
              Const (c, certT T)
wenzelm@14788
   507
            else if T = dummyT then Free (x, get_type (x, ~1))
wenzelm@14788
   508
            else constrain (Free (x, certT T)) (get_type (x, ~1))
wenzelm@14788
   509
          end
wenzelm@14788
   510
      | decode (Var (xi, T)) =
wenzelm@14788
   511
          if T = dummyT then Var (xi, get_type xi)
wenzelm@14788
   512
          else constrain (Var (xi, certT T)) (get_type xi)
wenzelm@18996
   513
      | decode (t as Bound _) = t;
wenzelm@14788
   514
  in decode tm end;
wenzelm@14788
   515
wenzelm@14788
   516
wenzelm@14788
   517
(* infer_types *)
wenzelm@14788
   518
wenzelm@14788
   519
(*Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
wenzelm@14788
   520
  unifies with Ti (for i=1,...,n).
wenzelm@14788
   521
wenzelm@14788
   522
  tsig: type signature
wenzelm@14788
   523
  const_type: name mapping and signature lookup
wenzelm@16195
   524
  def_type: partial map from indexnames to types (constrains Frees and Vars)
wenzelm@16195
   525
  def_sort: partial map from indexnames to sorts (constrains TFrees and TVars)
wenzelm@14788
   526
  used: list of already used type variables
wenzelm@14788
   527
  freeze: if true then generated parameters are turned into TFrees, else TVars*)
wenzelm@14788
   528
wenzelm@14828
   529
fun infer_types pp tsig const_type def_type def_sort
wenzelm@14788
   530
    map_const map_type map_sort used freeze pat_Ts raw_ts =
wenzelm@14788
   531
  let
wenzelm@14788
   532
    val {classes, arities, ...} = Type.rep_tsig tsig;
wenzelm@14993
   533
    val pat_Ts' = map (Type.cert_typ tsig) pat_Ts;
wenzelm@16195
   534
    val is_const = is_some o const_type;
wenzelm@14788
   535
    val raw_ts' =
wenzelm@14788
   536
      map (decode_types tsig is_const def_type def_sort map_const map_type map_sort) raw_ts;
wenzelm@14828
   537
    val (ts, Ts, unifier) = basic_infer_types pp const_type
wenzelm@16366
   538
      (#2 classes) arities used freeze is_param raw_ts' pat_Ts';
wenzelm@14788
   539
  in (ts, unifier) end;
wenzelm@14788
   540
wenzelm@2957
   541
end;