src/Pure/type.ML
author nipkow
Fri Mar 17 15:52:55 1995 +0100 (1995-03-17 ago)
changeset 963 7a78fda77104
parent 949 83c588d6fee9
child 1215 a206f722bef9
permissions -rw-r--r--
Corrected a silly old bug in merge_tsigs.
Rewrote a lot of Nimmermann's code.
wenzelm@256
     1
(*  Title:      Pure/type.ML
clasohm@0
     2
    ID:         $Id$
wenzelm@416
     3
    Author:     Tobias Nipkow & Lawrence C Paulson
clasohm@0
     4
wenzelm@416
     5
Type classes and sorts. Type signatures. Type unification and inference.
wenzelm@256
     6
wenzelm@256
     7
TODO:
wenzelm@416
     8
  move type unification and inference to type_unify.ML (TypeUnify) (?)
clasohm@0
     9
*)
clasohm@0
    10
clasohm@0
    11
signature TYPE =
clasohm@0
    12
sig
wenzelm@256
    13
  structure Symtab: SYMTAB
wenzelm@621
    14
  val no_tvars: typ -> typ
wenzelm@621
    15
  val varifyT: typ -> typ
wenzelm@621
    16
  val unvarifyT: typ -> typ
wenzelm@621
    17
  val varify: term * string list -> term
wenzelm@416
    18
  val str_of_sort: sort -> string
wenzelm@416
    19
  val str_of_arity: string * sort list * sort -> string
clasohm@0
    20
  type type_sig
nipkow@200
    21
  val rep_tsig: type_sig ->
wenzelm@256
    22
    {classes: class list,
wenzelm@256
    23
     subclass: (class * class list) list,
wenzelm@256
    24
     default: sort,
nipkow@963
    25
     tycons: (string * int) list,
wenzelm@621
    26
     abbrs: (string * (string list * typ)) list,
nipkow@963
    27
     arities: (string * (class * sort list) list) list}
clasohm@0
    28
  val defaultS: type_sig -> sort
wenzelm@416
    29
  val tsig0: type_sig
wenzelm@256
    30
  val logical_types: type_sig -> string list
wenzelm@621
    31
  val ext_tsig_classes: type_sig -> (class * class list) list -> type_sig
wenzelm@422
    32
  val ext_tsig_subclass: type_sig -> (class * class) list -> type_sig
wenzelm@422
    33
  val ext_tsig_defsort: type_sig -> sort -> type_sig
wenzelm@582
    34
  val ext_tsig_types: type_sig -> (string * int) list -> type_sig
wenzelm@621
    35
  val ext_tsig_abbrs: type_sig -> (string * string list * typ) list -> type_sig
nipkow@963
    36
  val ext_tsig_arities: type_sig -> (string * sort list * sort)list -> type_sig
wenzelm@256
    37
  val merge_tsigs: type_sig * type_sig -> type_sig
wenzelm@416
    38
  val subsort: type_sig -> sort * sort -> bool
wenzelm@416
    39
  val norm_sort: type_sig -> sort -> sort
wenzelm@416
    40
  val rem_sorts: typ -> typ
wenzelm@256
    41
  val cert_typ: type_sig -> typ -> typ
wenzelm@256
    42
  val norm_typ: type_sig -> typ -> typ
nipkow@949
    43
  val freeze: term -> term
clasohm@0
    44
  val freeze_vars: typ -> typ
nipkow@949
    45
  val infer_types: type_sig * (string -> typ option) *
nipkow@949
    46
                   (indexname -> typ option) * (indexname -> sort option) *
nipkow@949
    47
                   string list * bool * typ * term
nipkow@949
    48
                   -> term * (indexname * typ) list
wenzelm@256
    49
  val inst_term_tvars: type_sig * (indexname * typ) list -> term -> term
clasohm@0
    50
  val thaw_vars: typ -> typ
wenzelm@256
    51
  val typ_errors: type_sig -> typ * string list -> string list
clasohm@0
    52
  val typ_instance: type_sig * typ * typ -> bool
wenzelm@256
    53
  val typ_match: type_sig -> (indexname * typ) list * (typ * typ)
wenzelm@256
    54
    -> (indexname * typ) list
wenzelm@256
    55
  val unify: type_sig -> (typ * typ) * (indexname * typ) list
wenzelm@256
    56
    -> (indexname * typ) list
wenzelm@450
    57
  val raw_unify: typ * typ -> bool
clasohm@0
    58
  exception TUNIFY
wenzelm@256
    59
  exception TYPE_MATCH
clasohm@0
    60
end;
clasohm@0
    61
wenzelm@416
    62
functor TypeFun(structure Symtab: SYMTAB and Syntax: SYNTAX): TYPE =
clasohm@0
    63
struct
clasohm@0
    64
wenzelm@256
    65
structure Symtab = Symtab;
clasohm@0
    66
clasohm@0
    67
wenzelm@621
    68
(*** TFrees vs TVars ***)
wenzelm@621
    69
wenzelm@621
    70
(*disallow TVars*)
wenzelm@621
    71
fun no_tvars T =
wenzelm@621
    72
  if null (typ_tvars T) then T
wenzelm@621
    73
  else raise_type "Illegal schematic type variable(s)" [T] [];
wenzelm@621
    74
wenzelm@621
    75
(*turn TFrees into TVars to allow types & axioms to be written without "?"*)
nipkow@949
    76
val varifyT = map_type_tfree (fn (a, S) => TVar((a, 0), S));
wenzelm@621
    77
wenzelm@621
    78
(*inverse of varifyT*)
wenzelm@621
    79
fun unvarifyT (Type (a, Ts)) = Type (a, map unvarifyT Ts)
wenzelm@621
    80
  | unvarifyT (TVar ((a, 0), S)) = TFree (a, S)
wenzelm@621
    81
  | unvarifyT T = T;
wenzelm@621
    82
wenzelm@621
    83
(*turn TFrees except those in fixed into new TVars*)
wenzelm@621
    84
fun varify (t, fixed) =
wenzelm@621
    85
  let
wenzelm@621
    86
    val fs = add_term_tfree_names (t, []) \\ fixed;
wenzelm@621
    87
    val ixns = add_term_tvar_ixns (t, []);
wenzelm@621
    88
    val fmap = fs ~~ variantlist (fs, map #1 ixns)
nipkow@949
    89
    fun thaw(f as (a,S)) = case assoc (fmap, a) of
nipkow@949
    90
                             None => TFree(f)
nipkow@949
    91
                           | Some b => TVar((b, 0), S)
nipkow@949
    92
  in  map_term_types (map_type_tfree thaw) t  end;
wenzelm@621
    93
wenzelm@621
    94
wenzelm@621
    95
wenzelm@416
    96
(*** type classes and sorts ***)
wenzelm@416
    97
wenzelm@416
    98
(*
wenzelm@416
    99
  Classes denote (possibly empty) collections of types (e.g. sets of types)
wenzelm@416
   100
  and are partially ordered by 'inclusion'. They are represented by strings.
wenzelm@416
   101
wenzelm@416
   102
  Sorts are intersections of finitely many classes. They are represented by
wenzelm@416
   103
  lists of classes.
wenzelm@416
   104
*)
clasohm@0
   105
clasohm@0
   106
type domain = sort list;
wenzelm@416
   107
wenzelm@416
   108
wenzelm@416
   109
(* print sorts and arities *)
clasohm@0
   110
wenzelm@416
   111
fun str_of_sort [c] = c
wenzelm@565
   112
  | str_of_sort cs = enclose "{" "}" (commas cs);
wenzelm@416
   113
wenzelm@565
   114
fun str_of_dom dom = enclose "(" ")" (commas (map str_of_sort dom));
wenzelm@416
   115
wenzelm@416
   116
fun str_of_arity (t, [], S) = t ^ " :: " ^ str_of_sort S
wenzelm@416
   117
  | str_of_arity (t, SS, S) =
wenzelm@416
   118
      t ^ " :: " ^ str_of_dom SS ^ " " ^ str_of_sort S;
wenzelm@256
   119
wenzelm@256
   120
wenzelm@256
   121
wenzelm@416
   122
(*** type signatures ***)
wenzelm@256
   123
wenzelm@256
   124
(*
wenzelm@256
   125
  classes:
wenzelm@256
   126
    a list of all declared classes;
clasohm@0
   127
wenzelm@256
   128
  subclass:
wenzelm@416
   129
    an association list representing the subclass relation; (c, cs) is
wenzelm@256
   130
    interpreted as "c is a proper subclass of all elemenst of cs"; note that
wenzelm@256
   131
    c itself is not a memeber of cs;
wenzelm@256
   132
wenzelm@256
   133
  default:
wenzelm@256
   134
    the default sort attached to all unconstrained type vars;
wenzelm@256
   135
nipkow@963
   136
  tycons:
wenzelm@256
   137
    an association list of all declared types with the number of their
wenzelm@256
   138
    arguments;
wenzelm@256
   139
wenzelm@256
   140
  abbrs:
wenzelm@256
   141
    an association list of type abbreviations;
wenzelm@256
   142
nipkow@963
   143
  arities:
wenzelm@256
   144
    a two-fold association list of all type arities; (t, al) means that type
wenzelm@256
   145
    constructor t has the arities in al; an element (c, ss) of al represents
wenzelm@256
   146
    the arity (ss)c;
clasohm@0
   147
*)
clasohm@0
   148
wenzelm@256
   149
datatype type_sig =
wenzelm@256
   150
  TySg of {
wenzelm@256
   151
    classes: class list,
wenzelm@256
   152
    subclass: (class * class list) list,
wenzelm@256
   153
    default: sort,
nipkow@963
   154
    tycons: (string * int) list,
wenzelm@621
   155
    abbrs: (string * (string list * typ)) list,
nipkow@963
   156
    arities: (string * (class * domain) list) list};
wenzelm@256
   157
nipkow@189
   158
fun rep_tsig (TySg comps) = comps;
clasohm@0
   159
wenzelm@256
   160
fun defaultS (TySg {default, ...}) = default;
wenzelm@256
   161
wenzelm@256
   162
wenzelm@582
   163
(* error messages *)
wenzelm@256
   164
wenzelm@416
   165
fun undcl_class c = "Undeclared class " ^ quote c;
wenzelm@256
   166
val err_undcl_class = error o undcl_class;
clasohm@0
   167
wenzelm@422
   168
fun err_dup_classes cs =
wenzelm@422
   169
  error ("Duplicate declaration of class(es) " ^ commas_quote cs);
wenzelm@416
   170
wenzelm@416
   171
fun undcl_type c = "Undeclared type constructor " ^ quote c;
wenzelm@256
   172
val err_undcl_type = error o undcl_type;
wenzelm@256
   173
wenzelm@582
   174
fun err_neg_args c =
wenzelm@582
   175
  error ("Negative number of arguments of type constructor " ^ quote c);
wenzelm@582
   176
wenzelm@416
   177
fun err_dup_tycon c =
wenzelm@416
   178
  error ("Duplicate declaration of type constructor " ^ quote c);
wenzelm@416
   179
wenzelm@621
   180
fun dup_tyabbrs ts =
wenzelm@621
   181
  "Duplicate declaration of type abbreviation(s) " ^ commas_quote ts;
wenzelm@416
   182
wenzelm@416
   183
fun ty_confl c = "Conflicting type constructor and abbreviation " ^ quote c;
wenzelm@416
   184
val err_ty_confl = error o ty_confl;
clasohm@0
   185
clasohm@0
   186
clasohm@0
   187
(* 'leq' checks the partial order on classes according to the
wenzelm@621
   188
   statements in the association list 'a' (i.e. 'subclass')
clasohm@0
   189
*)
clasohm@0
   190
wenzelm@256
   191
fun less a (C, D) = case assoc (a, C) of
wenzelm@621
   192
     Some ss => D mem ss
wenzelm@621
   193
   | None => err_undcl_class C;
clasohm@0
   194
wenzelm@256
   195
fun leq a (C, D)  =  C = D orelse less a (C, D);
clasohm@0
   196
clasohm@0
   197
wenzelm@416
   198
(* logical_types *)
clasohm@0
   199
wenzelm@416
   200
(*return all logical types of tsig, i.e. all types t with some arity t::(ss)c
wenzelm@416
   201
  and c <= logic*)
clasohm@0
   202
wenzelm@416
   203
fun logical_types tsig =
wenzelm@416
   204
  let
nipkow@963
   205
    val TySg {subclass, arities, tycons, ...} = tsig;
wenzelm@416
   206
wenzelm@416
   207
    fun log_class c = leq subclass (c, logicC);
nipkow@963
   208
    fun log_type t = exists (log_class o #1) (assocs arities t);
wenzelm@416
   209
  in
nipkow@963
   210
    filter log_type (map #1 tycons)
clasohm@0
   211
  end;
clasohm@0
   212
nipkow@162
   213
wenzelm@256
   214
(* 'sortorder' checks the ordering on sets of classes, i.e. on sorts:
wenzelm@256
   215
   S1 <= S2 , iff for every class C2 in S2 there exists a class C1 in S1
clasohm@0
   216
   with C1 <= C2 (according to an association list 'a')
clasohm@0
   217
*)
clasohm@0
   218
wenzelm@256
   219
fun sortorder a (S1, S2) =
wenzelm@256
   220
  forall  (fn C2 => exists  (fn C1 => leq a (C1, C2))  S1)  S2;
clasohm@0
   221
clasohm@0
   222
clasohm@0
   223
(* 'inj' inserts a new class C into a given class set S (i.e.sort) only if
clasohm@0
   224
  there exists no class in S which is <= C;
clasohm@0
   225
  the resulting set is minimal if S was minimal
clasohm@0
   226
*)
clasohm@0
   227
wenzelm@256
   228
fun inj a (C, S) =
clasohm@0
   229
  let fun inj1 [] = [C]
wenzelm@256
   230
        | inj1 (D::T) = if leq a (D, C) then D::T
wenzelm@256
   231
                        else if leq a (C, D) then inj1 T
clasohm@0
   232
                             else D::(inj1 T)
clasohm@0
   233
  in inj1 S end;
clasohm@0
   234
clasohm@0
   235
clasohm@0
   236
(* 'union_sort' forms the minimal union set of two sorts S1 and S2
clasohm@0
   237
   under the assumption that S2 is minimal *)
wenzelm@256
   238
(* FIXME rename to inter_sort (?) *)
clasohm@0
   239
clasohm@0
   240
fun union_sort a = foldr (inj a);
clasohm@0
   241
clasohm@0
   242
clasohm@0
   243
(* 'elementwise_union' forms elementwise the minimal union set of two
clasohm@0
   244
   sort lists under the assumption that the two lists have the same length
wenzelm@256
   245
*)
clasohm@0
   246
wenzelm@256
   247
fun elementwise_union a (Ss1, Ss2) = map (union_sort a) (Ss1~~Ss2);
wenzelm@256
   248
clasohm@0
   249
clasohm@0
   250
(* 'lew' checks for two sort lists the ordering for all corresponding list
clasohm@0
   251
   elements (i.e. sorts) *)
clasohm@0
   252
wenzelm@256
   253
fun lew a (w1, w2) = forall (sortorder a)  (w1~~w2);
wenzelm@256
   254
clasohm@0
   255
wenzelm@256
   256
(* 'is_min' checks if a class C is minimal in a given sort S under the
wenzelm@256
   257
   assumption that S contains C *)
clasohm@0
   258
wenzelm@256
   259
fun is_min a S C = not (exists (fn (D) => less a (D, C)) S);
clasohm@0
   260
clasohm@0
   261
clasohm@0
   262
(* 'min_sort' reduces a sort to its minimal classes *)
clasohm@0
   263
clasohm@0
   264
fun min_sort a S = distinct(filter (is_min a S) S);
clasohm@0
   265
clasohm@0
   266
clasohm@0
   267
(* 'min_domain' minimizes the domain sorts of type declarationsl;
wenzelm@256
   268
   the function will be applied on the type declarations in extensions *)
clasohm@0
   269
clasohm@0
   270
fun min_domain subclass =
wenzelm@256
   271
  let fun one_min (f, (doms, ran)) = (f, (map (min_sort subclass) doms, ran))
clasohm@0
   272
  in map one_min end;
clasohm@0
   273
clasohm@0
   274
clasohm@0
   275
(* 'min_filter' filters a list 'ars' consisting of arities (domain * class)
wenzelm@256
   276
   and gives back a list of those range classes whose domains meet the
clasohm@0
   277
   predicate 'pred' *)
wenzelm@256
   278
clasohm@0
   279
fun min_filter a pred ars =
wenzelm@256
   280
  let fun filt ([], l) = l
wenzelm@256
   281
        | filt ((c, x)::xs, l) = if pred(x) then filt (xs, inj a (c, l))
wenzelm@256
   282
                               else filt (xs, l)
wenzelm@256
   283
  in filt (ars, []) end;
clasohm@0
   284
clasohm@0
   285
clasohm@0
   286
(* 'cod_above' filters all arities whose domains are elementwise >= than
wenzelm@256
   287
   a given domain 'w' and gives back a list of the corresponding range
clasohm@0
   288
   classes *)
clasohm@0
   289
wenzelm@256
   290
fun cod_above (a, w, ars) = min_filter a (fn w' => lew a (w, w')) ars;
wenzelm@256
   291
wenzelm@256
   292
clasohm@0
   293
nipkow@200
   294
(*Instantiation of type variables in types*)
nipkow@200
   295
(*Pre: instantiations obey restrictions! *)
nipkow@200
   296
fun inst_typ tye =
nipkow@949
   297
  let fun inst(var as (v, _)) = case assoc(tye, v) of
nipkow@949
   298
                                  Some U => inst_typ tye U
nipkow@949
   299
                                | None => TVar(var)
nipkow@949
   300
  in map_type_tvar inst end;
clasohm@0
   301
clasohm@0
   302
(* 'least_sort' returns for a given type its maximum sort:
clasohm@0
   303
   - type variables, free types: the sort brought with
clasohm@0
   304
   - type constructors: recursive determination of the maximum sort of the
nipkow@963
   305
                    arguments if the type is declared in 'arities' of the
wenzelm@256
   306
                    given type signature  *)
clasohm@0
   307
nipkow@963
   308
fun least_sort (tsig as TySg{subclass, arities, ...}) =
wenzelm@256
   309
  let fun ls(T as Type(a, Ts)) =
nipkow@963
   310
                 (case assoc (arities, a) of
wenzelm@256
   311
                          Some(ars) => cod_above(subclass, map ls Ts, ars)
wenzelm@256
   312
                        | None => raise TYPE(undcl_type a, [T], []))
wenzelm@256
   313
        | ls(TFree(a, S)) = S
wenzelm@256
   314
        | ls(TVar(a, S)) = S
clasohm@0
   315
  in ls end;
clasohm@0
   316
clasohm@0
   317
nipkow@963
   318
fun check_has_sort(tsig as TySg{subclass, arities, ...}, T, S) =
wenzelm@256
   319
  if sortorder subclass ((least_sort tsig T), S) then ()
wenzelm@256
   320
  else raise TYPE("Type not of sort " ^ (str_of_sort S), [T], [])
clasohm@0
   321
clasohm@0
   322
clasohm@0
   323
(*Instantiation of type variables in types *)
wenzelm@256
   324
fun inst_typ_tvars(tsig, tye) =
nipkow@949
   325
  let fun inst(var as (v, S)) = case assoc(tye, v) of
nipkow@949
   326
              Some U => (check_has_sort(tsig, U, S); U)
nipkow@949
   327
            | None => TVar(var)
nipkow@949
   328
  in map_type_tvar inst end;
clasohm@0
   329
clasohm@0
   330
(*Instantiation of type variables in terms *)
wenzelm@256
   331
fun inst_term_tvars(tsig, tye) = map_term_types (inst_typ_tvars(tsig, tye));
nipkow@200
   332
nipkow@200
   333
nipkow@200
   334
(* expand_typ *)
nipkow@200
   335
wenzelm@256
   336
fun expand_typ (TySg {abbrs, ...}) ty =
wenzelm@256
   337
  let
wenzelm@621
   338
    val idx = maxidx_of_typ ty + 1;
wenzelm@621
   339
wenzelm@621
   340
    fun expand (Type (a, Ts)) =
wenzelm@256
   341
          (case assoc (abbrs, a) of
wenzelm@621
   342
            Some (vs, U) =>
wenzelm@621
   343
              expand (inst_typ (map (rpair idx) vs ~~ Ts) (incr_tvar idx U))
wenzelm@621
   344
          | None => Type (a, map expand Ts))
wenzelm@621
   345
      | expand T = T
wenzelm@256
   346
  in
wenzelm@621
   347
    expand ty
wenzelm@256
   348
  end;
wenzelm@256
   349
wenzelm@256
   350
val norm_typ = expand_typ;
wenzelm@256
   351
wenzelm@256
   352
wenzelm@256
   353
wenzelm@256
   354
(** type matching **)
nipkow@200
   355
clasohm@0
   356
exception TYPE_MATCH;
clasohm@0
   357
wenzelm@256
   358
(*typ_match (s, (U, T)) = s' <==> s'(U) = T and s' is an extension of s*)
wenzelm@256
   359
fun typ_match tsig =
wenzelm@256
   360
  let
wenzelm@256
   361
    fun match (subs, (TVar (v, S), T)) =
wenzelm@256
   362
          (case assoc (subs, v) of
wenzelm@256
   363
            None => ((v, (check_has_sort (tsig, T, S); T)) :: subs
wenzelm@256
   364
              handle TYPE _ => raise TYPE_MATCH)
wenzelm@422
   365
          | Some U => if U = T then subs else raise TYPE_MATCH)
wenzelm@256
   366
      | match (subs, (Type (a, Ts), Type (b, Us))) =
wenzelm@256
   367
          if a <> b then raise TYPE_MATCH
wenzelm@256
   368
          else foldl match (subs, Ts ~~ Us)
wenzelm@422
   369
      | match (subs, (TFree x, TFree y)) =
wenzelm@256
   370
          if x = y then subs else raise TYPE_MATCH
wenzelm@256
   371
      | match _ = raise TYPE_MATCH;
wenzelm@256
   372
  in match end;
clasohm@0
   373
clasohm@0
   374
wenzelm@256
   375
fun typ_instance (tsig, T, U) =
wenzelm@256
   376
  (typ_match tsig ([], (U, T)); true) handle TYPE_MATCH => false;
wenzelm@256
   377
wenzelm@256
   378
wenzelm@256
   379
wenzelm@256
   380
(** build type signatures **)
wenzelm@256
   381
nipkow@963
   382
fun make_tsig (classes, subclass, default, tycons, abbrs, arities) =
wenzelm@416
   383
  TySg {classes = classes, subclass = subclass, default = default,
nipkow@963
   384
    tycons = tycons, abbrs = abbrs, arities = arities};
wenzelm@416
   385
wenzelm@416
   386
val tsig0 = make_tsig ([], [], [], [], [], []);
wenzelm@256
   387
clasohm@0
   388
wenzelm@401
   389
(* sorts *)
wenzelm@401
   390
wenzelm@416
   391
fun subsort (TySg {subclass, ...}) (S1, S2) =
wenzelm@416
   392
  sortorder subclass (S1, S2);
wenzelm@416
   393
wenzelm@401
   394
fun norm_sort (TySg {subclass, ...}) S =
wenzelm@401
   395
  sort_strings (min_sort subclass S);
wenzelm@401
   396
wenzelm@416
   397
fun rem_sorts (Type (a, tys)) = Type (a, map rem_sorts tys)
wenzelm@416
   398
  | rem_sorts (TFree (x, _)) = TFree (x, [])
wenzelm@416
   399
  | rem_sorts (TVar (xi, _)) = TVar (xi, []);
wenzelm@401
   400
wenzelm@401
   401
wenzelm@416
   402
(* typ_errors *)
wenzelm@256
   403
wenzelm@416
   404
(*check validity of (not necessarily normal) type; accumulate error messages*)
wenzelm@256
   405
wenzelm@416
   406
fun typ_errors tsig (typ, errors) =
wenzelm@256
   407
  let
nipkow@963
   408
    val TySg {classes, tycons, abbrs, ...} = tsig;
wenzelm@416
   409
wenzelm@416
   410
    fun class_err (errs, c) =
wenzelm@416
   411
      if c mem classes then errs
wenzelm@416
   412
      else undcl_class c ins errs;
wenzelm@256
   413
wenzelm@256
   414
    val sort_err = foldl class_err;
clasohm@0
   415
wenzelm@256
   416
    fun typ_errs (Type (c, Us), errs) =
wenzelm@256
   417
          let
wenzelm@256
   418
            val errs' = foldr typ_errs (Us, errs);
wenzelm@256
   419
            fun nargs n =
wenzelm@256
   420
              if n = length Us then errs'
wenzelm@416
   421
              else ("Wrong number of arguments: " ^ quote c) ins errs';
wenzelm@256
   422
          in
nipkow@963
   423
            (case assoc (tycons, c) of
wenzelm@256
   424
              Some n => nargs n
wenzelm@256
   425
            | None =>
wenzelm@256
   426
                (case assoc (abbrs, c) of
wenzelm@256
   427
                  Some (vs, _) => nargs (length vs)
wenzelm@416
   428
                | None => undcl_type c ins errs))
wenzelm@256
   429
          end
wenzelm@256
   430
    | typ_errs (TFree (_, S), errs) = sort_err (errs, S)
wenzelm@416
   431
    | typ_errs (TVar ((x, i), S), errs) =
wenzelm@416
   432
        if i < 0 then
wenzelm@416
   433
          ("Negative index for TVar " ^ quote x) ins sort_err (errs, S)
wenzelm@416
   434
        else sort_err (errs, S);
wenzelm@256
   435
  in
wenzelm@416
   436
    typ_errs (typ, errors)
wenzelm@256
   437
  end;
wenzelm@256
   438
wenzelm@256
   439
wenzelm@256
   440
(* cert_typ *)
wenzelm@256
   441
wenzelm@256
   442
(*check and normalize typ wrt. tsig; errors are indicated by exception TYPE*)
wenzelm@256
   443
wenzelm@256
   444
fun cert_typ tsig ty =
wenzelm@256
   445
  (case typ_errors tsig (ty, []) of
wenzelm@256
   446
    [] => norm_typ tsig ty
wenzelm@256
   447
  | errs => raise_type (cat_lines errs) [ty] []);
wenzelm@256
   448
wenzelm@256
   449
wenzelm@256
   450
wenzelm@422
   451
(** merge type signatures **)
wenzelm@256
   452
wenzelm@422
   453
(*'assoc_union' merges two association lists if the contents associated
wenzelm@422
   454
  the keys are lists*)
clasohm@0
   455
wenzelm@422
   456
fun assoc_union (as1, []) = as1
wenzelm@422
   457
  | assoc_union (as1, (key, l2) :: as2) =
wenzelm@422
   458
      (case assoc (as1, key) of
wenzelm@422
   459
        Some l1 => assoc_union (overwrite (as1, (key, l1 union l2)), as2)
wenzelm@422
   460
      | None => assoc_union ((key, l2) :: as1, as2));
clasohm@0
   461
clasohm@0
   462
wenzelm@422
   463
(* merge subclass *)
clasohm@0
   464
wenzelm@422
   465
fun merge_subclass (subclass1, subclass2) =
wenzelm@422
   466
  let val subclass = transitive_closure (assoc_union (subclass1, subclass2)) in
wenzelm@422
   467
    if exists (op mem) subclass then
wenzelm@422
   468
      error ("Cyclic class structure!")   (* FIXME improve msg, raise TERM *)
wenzelm@422
   469
    else subclass
wenzelm@416
   470
  end;
wenzelm@416
   471
wenzelm@416
   472
wenzelm@422
   473
(* coregularity *)
clasohm@0
   474
clasohm@0
   475
(* 'is_unique_decl' checks if there exists just one declaration t:(Ss)C *)
clasohm@0
   476
nipkow@963
   477
fun is_unique_decl ars (t,(C,w)) = case assoc (ars, C) of
clasohm@0
   478
      Some(w1) => if w = w1 then () else
wenzelm@256
   479
        error("There are two declarations\n" ^
nipkow@963
   480
              str_of_arity(t, w, [C]) ^ " and\n" ^
nipkow@963
   481
              str_of_arity(t, w1, [C]) ^ "\n" ^
clasohm@0
   482
              "with the same result class.")
clasohm@0
   483
    | None => ();
clasohm@0
   484
nipkow@963
   485
(* 'coreg' checks if there are two declarations t:(Ss1)C1 and t:(Ss2)C2
clasohm@0
   486
   such that C1 >= C2 then Ss1 >= Ss2 (elementwise) *)
clasohm@0
   487
nipkow@963
   488
fun coreg_err(t, (C1,w1), (C2,w2)) =
nipkow@963
   489
    error("Declarations " ^ str_of_arity(t, w1, [C1]) ^ " and "
nipkow@963
   490
                          ^ str_of_arity(t, w2, [C2]) ^ " are in conflict");
clasohm@0
   491
nipkow@963
   492
fun coreg subclass (t, Cw1) =
nipkow@963
   493
  let fun check1(Cw1 as (C1,w1), Cw2 as (C2,w2)) =
nipkow@963
   494
        if leq subclass (C1,C2)
nipkow@963
   495
        then if lew subclass (w1,w2) then () else coreg_err(t, Cw1, Cw2)
nipkow@963
   496
        else ()
nipkow@963
   497
      fun check(Cw2) = (check1(Cw1,Cw2); check1(Cw2,Cw1))
nipkow@963
   498
  in seq check end;
clasohm@0
   499
nipkow@963
   500
fun add_arity subclass ars (tCw as (_,Cw)) =
nipkow@963
   501
      (is_unique_decl ars tCw; coreg subclass tCw ars; Cw ins ars);
clasohm@0
   502
wenzelm@256
   503
fun varying_decls t =
wenzelm@256
   504
  error ("Type constructor " ^ quote t ^ " has varying number of arguments");
clasohm@0
   505
clasohm@0
   506
nipkow@963
   507
(* 'merge_arities' builds the union of two 'arities' lists;
wenzelm@422
   508
   it only checks the two restriction conditions and inserts afterwards
wenzelm@422
   509
   all elements of the second list into the first one *)
wenzelm@422
   510
nipkow@963
   511
fun merge_arities subclass =
nipkow@963
   512
  let fun test_ar t (ars1, sw) = add_arity subclass ars1 (t,sw);
wenzelm@422
   513
nipkow@963
   514
      fun merge_c (arities1, (c as (t, ars2))) = case assoc (arities1, t) of
nipkow@963
   515
          Some(ars1) =>
nipkow@963
   516
            let val ars = foldl (test_ar t) (ars1, ars2)
nipkow@963
   517
            in overwrite (arities1, (t,ars)) end
nipkow@963
   518
        | None => c::arities1
wenzelm@422
   519
  in foldl merge_c end;
wenzelm@422
   520
nipkow@963
   521
fun add_tycons (tycons, tn as (t,n)) =
nipkow@963
   522
  (case assoc (tycons, t) of
nipkow@963
   523
    Some m => if m = n then tycons else varying_decls t
nipkow@963
   524
  | None => tn :: tycons);
wenzelm@422
   525
wenzelm@422
   526
fun merge_abbrs (abbrs1, abbrs2) =
wenzelm@621
   527
  let val abbrs = abbrs1 union abbrs2 in
wenzelm@621
   528
    (case gen_duplicates eq_fst abbrs of
wenzelm@422
   529
      [] => abbrs
wenzelm@621
   530
    | dups => raise_term (dup_tyabbrs (map fst dups)) [])
wenzelm@422
   531
  end;
wenzelm@422
   532
wenzelm@422
   533
wenzelm@422
   534
(* 'merge_tsigs' takes the above declared functions to merge two type
wenzelm@422
   535
  signatures *)
wenzelm@422
   536
nipkow@963
   537
fun merge_tsigs(TySg{classes=classes1, default=default1, subclass=subclass1,
nipkow@963
   538
                     tycons=tycons1, arities=arities1, abbrs=abbrs1},
nipkow@963
   539
                TySg{classes=classes2, default=default2, subclass=subclass2,
nipkow@963
   540
                     tycons=tycons2, arities=arities2, abbrs=abbrs2}) =
wenzelm@422
   541
  let val classes' = classes1 union classes2;
wenzelm@422
   542
      val subclass' = merge_subclass (subclass1, subclass2);
nipkow@963
   543
      val tycons' = foldl add_tycons (tycons1, tycons2)
nipkow@963
   544
      val arities' = merge_arities subclass' (arities1, arities2);
wenzelm@422
   545
      val default' = min_sort subclass' (default1 @ default2);
wenzelm@422
   546
      val abbrs' = merge_abbrs(abbrs1, abbrs2);
nipkow@963
   547
  in make_tsig(classes', subclass', default', tycons', abbrs', arities') end;
wenzelm@422
   548
wenzelm@422
   549
wenzelm@422
   550
wenzelm@422
   551
(*** extend type signatures ***)
wenzelm@422
   552
wenzelm@621
   553
(** add classes and subclass relations**)
wenzelm@422
   554
wenzelm@422
   555
fun add_classes classes cs =
wenzelm@422
   556
  (case cs inter classes of
wenzelm@422
   557
    [] => cs @ classes
wenzelm@422
   558
  | dups => err_dup_classes cs);
wenzelm@422
   559
wenzelm@422
   560
wenzelm@422
   561
(*'add_subclass' adds a tuple consisting of a new class (the new class has
wenzelm@422
   562
  already been inserted into the 'classes' list) and its superclasses (they
wenzelm@422
   563
  must be declared in 'classes' too) to the 'subclass' list of the given type
wenzelm@422
   564
  signature; furthermore all inherited superclasses according to the
wenzelm@422
   565
  superclasses brought with are inserted and there is a check that there are
wenzelm@422
   566
  no cycles (i.e. C <= D <= C, with C <> D);*)
wenzelm@422
   567
wenzelm@422
   568
fun add_subclass classes (subclass, (s, ges)) =
wenzelm@621
   569
  let
wenzelm@621
   570
    fun upd (subclass, s') =
wenzelm@621
   571
      if s' mem classes then
wenzelm@422
   572
        let val ges' = the (assoc (subclass, s))
wenzelm@422
   573
        in case assoc (subclass, s') of
wenzelm@422
   574
             Some sups => if s mem sups
wenzelm@422
   575
                           then error(" Cycle :" ^ s^" <= "^ s'^" <= "^ s )
wenzelm@422
   576
                           else overwrite (subclass, (s, sups union ges'))
wenzelm@422
   577
           | None => subclass
wenzelm@621
   578
        end
wenzelm@621
   579
      else err_undcl_class s'
wenzelm@621
   580
  in foldl upd (subclass @ [(s, ges)], ges) end;
wenzelm@422
   581
wenzelm@422
   582
wenzelm@422
   583
(* 'extend_classes' inserts all new classes into the corresponding
wenzelm@422
   584
   lists ('classes', 'subclass') if possible *)
wenzelm@422
   585
wenzelm@621
   586
fun extend_classes (classes, subclass, new_classes) =
wenzelm@621
   587
  let
wenzelm@621
   588
    val classes' = add_classes classes (map fst new_classes);
wenzelm@621
   589
    val subclass' = foldl (add_subclass classes') (subclass, new_classes);
wenzelm@422
   590
  in (classes', subclass') end;
wenzelm@422
   591
wenzelm@422
   592
wenzelm@621
   593
(* ext_tsig_classes *)
wenzelm@621
   594
wenzelm@621
   595
fun ext_tsig_classes tsig new_classes =
wenzelm@621
   596
  let
nipkow@963
   597
    val TySg {classes, subclass, default, tycons, abbrs, arities} = tsig;
nipkow@963
   598
    val (classes',subclass') = extend_classes (classes,subclass,new_classes);
wenzelm@621
   599
  in
nipkow@963
   600
    make_tsig (classes', subclass', default, tycons, abbrs, arities)
wenzelm@621
   601
  end;
wenzelm@621
   602
wenzelm@621
   603
wenzelm@422
   604
(* ext_tsig_subclass *)
wenzelm@422
   605
wenzelm@422
   606
fun ext_tsig_subclass tsig pairs =
wenzelm@422
   607
  let
nipkow@963
   608
    val TySg {classes, subclass, default, tycons, abbrs, arities} = tsig;
wenzelm@422
   609
wenzelm@422
   610
    (* FIXME clean! *)
wenzelm@422
   611
    val subclass' =
wenzelm@422
   612
      merge_subclass (subclass, map (fn (c1, c2) => (c1, [c2])) pairs);
wenzelm@422
   613
  in
nipkow@963
   614
    make_tsig (classes, subclass', default, tycons, abbrs, arities)
wenzelm@422
   615
  end;
wenzelm@422
   616
wenzelm@422
   617
wenzelm@422
   618
(* ext_tsig_defsort *)
wenzelm@422
   619
nipkow@963
   620
fun ext_tsig_defsort(TySg{classes,subclass,tycons,abbrs,arities,...}) default =
nipkow@963
   621
  make_tsig (classes, subclass, default, tycons, abbrs, arities);
wenzelm@422
   622
wenzelm@422
   623
wenzelm@422
   624
wenzelm@621
   625
(** add types **)
wenzelm@582
   626
nipkow@963
   627
fun ext_tsig_types (TySg {classes, subclass, default, tycons, abbrs, arities}) ts =
wenzelm@582
   628
  let
wenzelm@582
   629
    fun check_type (c, n) =
wenzelm@582
   630
      if n < 0 then err_neg_args c
nipkow@963
   631
      else if is_some (assoc (tycons, c)) then err_dup_tycon c
wenzelm@582
   632
      else if is_some (assoc (abbrs, c)) then err_ty_confl c
wenzelm@582
   633
      else ();
wenzelm@582
   634
  in
wenzelm@582
   635
    seq check_type ts;
nipkow@963
   636
    make_tsig (classes, subclass, default, ts @ tycons, abbrs,
nipkow@963
   637
      map (rpair [] o #1) ts @ arities)
wenzelm@582
   638
  end;
wenzelm@582
   639
wenzelm@582
   640
wenzelm@582
   641
wenzelm@582
   642
(** add type abbreviations **)
wenzelm@582
   643
wenzelm@582
   644
fun abbr_errors tsig (a, (lhs_vs, rhs)) =
wenzelm@582
   645
  let
nipkow@963
   646
    val TySg {tycons, abbrs, ...} = tsig;
wenzelm@621
   647
    val rhs_vs = map (#1 o #1) (typ_tvars rhs);
wenzelm@582
   648
wenzelm@582
   649
    val dup_lhs_vars =
wenzelm@582
   650
      (case duplicates lhs_vs of
wenzelm@582
   651
        [] => []
wenzelm@621
   652
      | vs => ["Duplicate variables on lhs: " ^ commas_quote vs]);
wenzelm@582
   653
wenzelm@582
   654
    val extra_rhs_vars =
wenzelm@582
   655
      (case gen_rems (op =) (rhs_vs, lhs_vs) of
wenzelm@582
   656
        [] => []
wenzelm@621
   657
      | vs => ["Extra variables on rhs: " ^ commas_quote vs]);
wenzelm@582
   658
wenzelm@582
   659
    val tycon_confl =
nipkow@963
   660
      if is_none (assoc (tycons, a)) then []
wenzelm@582
   661
      else [ty_confl a];
wenzelm@582
   662
wenzelm@582
   663
    val dup_abbr =
wenzelm@582
   664
      if is_none (assoc (abbrs, a)) then []
wenzelm@582
   665
      else ["Duplicate declaration of abbreviation"];
wenzelm@582
   666
  in
wenzelm@582
   667
    dup_lhs_vars @ extra_rhs_vars @ tycon_confl @ dup_abbr @
wenzelm@582
   668
      typ_errors tsig (rhs, [])
wenzelm@582
   669
  end;
wenzelm@582
   670
wenzelm@621
   671
fun prep_abbr tsig (a, vs, raw_rhs) =
wenzelm@621
   672
  let
wenzelm@621
   673
    fun err msgs = (seq writeln msgs;
wenzelm@621
   674
      error ("The error(s) above occurred in type abbreviation " ^ quote a));
wenzelm@621
   675
wenzelm@621
   676
    val rhs = rem_sorts (varifyT (no_tvars raw_rhs))
wenzelm@621
   677
      handle TYPE (msg, _, _) => err [msg];
wenzelm@621
   678
    val abbr = (a, (vs, rhs));
wenzelm@621
   679
  in
wenzelm@582
   680
    (case abbr_errors tsig abbr of
wenzelm@621
   681
      [] => abbr
wenzelm@621
   682
    | msgs => err msgs)
wenzelm@582
   683
  end;
wenzelm@582
   684
nipkow@963
   685
fun add_abbr (tsig as TySg{classes,subclass,default,tycons,arities,abbrs},
nipkow@963
   686
              abbr) =
wenzelm@621
   687
  make_tsig
nipkow@963
   688
    (classes,subclass,default,tycons, prep_abbr tsig abbr :: abbrs, arities);
wenzelm@621
   689
wenzelm@621
   690
fun ext_tsig_abbrs tsig raw_abbrs = foldl add_abbr (tsig, raw_abbrs);
wenzelm@582
   691
wenzelm@582
   692
wenzelm@582
   693
wenzelm@422
   694
(** add arities **)
wenzelm@422
   695
clasohm@0
   696
(* 'coregular' checks
nipkow@963
   697
   - the two restrictions 'is_unique_decl' and 'coreg'
wenzelm@256
   698
   - if the classes in the new type declarations are known in the
clasohm@0
   699
     given type signature
clasohm@0
   700
   - if one type constructor has always the same number of arguments;
wenzelm@256
   701
   if one type declaration has passed all checks it is inserted into
nipkow@963
   702
   the 'arities' association list of the given type signatrure  *)
clasohm@0
   703
nipkow@963
   704
fun coregular (classes, subclass, tycons) =
wenzelm@256
   705
  let fun ex C = if C mem classes then () else err_undcl_class(C);
clasohm@0
   706
nipkow@963
   707
      fun addar(arities, (t, (w, C))) = case assoc(tycons, t) of
clasohm@0
   708
            Some(n) => if n <> length w then varying_decls(t) else
nipkow@963
   709
                     ((seq o seq) ex w; ex C;
nipkow@963
   710
                      let val ars = the (assoc(arities, t))
nipkow@963
   711
                          val ars' = add_arity subclass ars (t,(C,w))
nipkow@963
   712
                      in overwrite(arities, (t,ars')) end)
wenzelm@256
   713
          | None => err_undcl_type(t);
clasohm@0
   714
nipkow@963
   715
  in addar end;
clasohm@0
   716
clasohm@0
   717
nipkow@963
   718
(* 'close' extends the 'arities' association list after all new type
clasohm@0
   719
   declarations have been inserted successfully:
clasohm@0
   720
   for every declaration t:(Ss)C , for all classses D with C <= D:
clasohm@0
   721
      if there is no declaration t:(Ss')C' with C < C' and C' <= D
nipkow@963
   722
      then insert the declaration t:(Ss)D into 'arities'
clasohm@0
   723
   this means, if there exists a declaration t:(Ss)C and there is
clasohm@0
   724
   no declaration t:(Ss')D with C <=D then the declaration holds
wenzelm@256
   725
   for all range classes more general than C *)
wenzelm@256
   726
nipkow@963
   727
fun close subclass arities =
wenzelm@256
   728
  let fun check sl (l, (s, dom)) = case assoc (subclass, s) of
wenzelm@621
   729
          Some sups =>
wenzelm@256
   730
            let fun close_sup (l, sup) =
wenzelm@256
   731
                  if exists (fn s'' => less subclass (s, s'') andalso
wenzelm@256
   732
                                       leq subclass (s'', sup)) sl
clasohm@0
   733
                  then l
wenzelm@256
   734
                  else (sup, dom)::l
wenzelm@256
   735
            in foldl close_sup (l, sups) end
clasohm@0
   736
        | None => l;
wenzelm@256
   737
      fun ext (s, l) = (s, foldl (check (map #1 l)) (l, l));
nipkow@963
   738
  in map ext arities end;
clasohm@0
   739
wenzelm@422
   740
wenzelm@621
   741
(* ext_tsig_arities *)
wenzelm@256
   742
wenzelm@621
   743
fun ext_tsig_arities tsig sarities =
wenzelm@416
   744
  let
nipkow@963
   745
    val TySg {classes, subclass, default, tycons, arities, abbrs} = tsig;
nipkow@963
   746
    val arities1 =
nipkow@963
   747
      flat (map (fn (t, ss, cs) => map (fn c => (t, (ss, c))) cs) sarities);
nipkow@963
   748
    val arities2 = foldl (coregular (classes, subclass, tycons))
nipkow@963
   749
                         (arities, min_domain subclass arities1)
wenzelm@621
   750
      |> close subclass;
wenzelm@416
   751
  in
nipkow@963
   752
    make_tsig (classes, subclass, default, tycons, abbrs, arities2)
wenzelm@416
   753
  end;
clasohm@0
   754
clasohm@0
   755
wenzelm@416
   756
wenzelm@416
   757
(*** type unification and inference ***)
clasohm@0
   758
clasohm@0
   759
(*
wenzelm@621
   760
  Input:
wenzelm@621
   761
    - a 'raw' term which contains only dummy types and some explicit type
wenzelm@621
   762
      constraints encoded as terms.
wenzelm@621
   763
    - the expected type of the term.
clasohm@0
   764
wenzelm@621
   765
  Output:
wenzelm@621
   766
    - the correctly typed term
wenzelm@621
   767
    - the substitution needed to unify the actual type of the term with its
wenzelm@621
   768
      expected type; only the TVars in the expected type are included.
clasohm@0
   769
wenzelm@621
   770
  During type inference all TVars in the term have negative index. This keeps
wenzelm@621
   771
  them apart from normal TVars, which is essential, because at the end the
wenzelm@621
   772
  type of the term is unified with the expected type, which contains normal
wenzelm@621
   773
  TVars.
clasohm@0
   774
wenzelm@621
   775
  1. Add initial type information to the term (attach_types).
wenzelm@621
   776
     This freezes (freeze_vars) TVars in explicitly provided types (eg
wenzelm@621
   777
     constraints or defaults) by turning them into TFrees.
wenzelm@621
   778
  2. Carry out type inference, possibly introducing new negative TVars.
wenzelm@621
   779
  3. Unify actual and expected type.
wenzelm@621
   780
  4. Turn all (negative) TVars into unique new TFrees (freeze).
wenzelm@621
   781
  5. Thaw all TVars frozen in step 1 (thaw_vars).
clasohm@0
   782
*)
clasohm@0
   783
clasohm@0
   784
(*Raised if types are not unifiable*)
clasohm@0
   785
exception TUNIFY;
clasohm@0
   786
wenzelm@621
   787
val tyvar_count = ref ~1;
clasohm@0
   788
clasohm@0
   789
fun tyinit() = (tyvar_count := ~1);
clasohm@0
   790
wenzelm@621
   791
fun new_tvar_inx () = (tyvar_count := ! tyvar_count - 1; ! tyvar_count)
clasohm@0
   792
clasohm@0
   793
(*
clasohm@0
   794
Generate new TVar.  Index is < ~1 to distinguish it from TVars generated from
clasohm@0
   795
variable names (see id_type).  Name is arbitrary because index is new.
clasohm@0
   796
*)
clasohm@0
   797
wenzelm@256
   798
fun gen_tyvar(S) = TVar(("'a", new_tvar_inx()), S);
clasohm@0
   799
clasohm@0
   800
(*Occurs check: type variable occurs in type?*)
clasohm@0
   801
fun occ v tye =
wenzelm@256
   802
  let fun occ(Type(_, Ts)) = exists occ Ts
clasohm@0
   803
        | occ(TFree _) = false
wenzelm@256
   804
        | occ(TVar(w, _)) = v=w orelse
wenzelm@256
   805
                           (case assoc(tye, w) of
clasohm@0
   806
                              None   => false
clasohm@0
   807
                            | Some U => occ U);
clasohm@0
   808
  in occ end;
clasohm@0
   809
wenzelm@256
   810
(*Chase variable assignments in tye.
wenzelm@256
   811
  If devar (T, tye) returns a type var then it must be unassigned.*)
wenzelm@256
   812
fun devar (T as TVar(v, _), tye) = (case  assoc(tye, v)  of
wenzelm@256
   813
          Some U =>  devar (U, tye)
clasohm@0
   814
        | None   =>  T)
wenzelm@256
   815
  | devar (T, tye) = T;
clasohm@0
   816
clasohm@0
   817
clasohm@0
   818
(* 'dom' returns for a type constructor t the list of those domains
clasohm@0
   819
   which deliver a given range class C *)
clasohm@0
   820
nipkow@963
   821
fun dom arities t C = case assoc2 (arities, (t, C)) of
clasohm@0
   822
    Some(Ss) => Ss
clasohm@0
   823
  | None => raise TUNIFY;
clasohm@0
   824
clasohm@0
   825
clasohm@0
   826
(* 'Dom' returns the union of all domain lists of 'dom' for a given sort S
clasohm@0
   827
   (i.e. a set of range classes ); the union is carried out elementwise
clasohm@0
   828
   for the seperate sorts in the domains *)
clasohm@0
   829
nipkow@963
   830
fun Dom (subclass, arities) (t, S) =
nipkow@963
   831
  let val domlist = map (dom arities t) S;
clasohm@0
   832
  in if null domlist then []
wenzelm@256
   833
     else foldl (elementwise_union subclass) (hd domlist, tl domlist)
clasohm@0
   834
  end;
clasohm@0
   835
clasohm@0
   836
nipkow@963
   837
fun W ((T, S), tsig as TySg{subclass, arities, ...}, tye) =
wenzelm@256
   838
  let fun Wd ((T, S), tye) = W ((devar (T, tye), S), tsig, tye)
wenzelm@256
   839
      fun Wk(T as TVar(v, S')) =
wenzelm@256
   840
              if sortorder subclass (S', S) then tye
wenzelm@256
   841
              else (v, gen_tyvar(union_sort subclass (S', S)))::tye
wenzelm@256
   842
        | Wk(T as TFree(v, S')) = if sortorder subclass (S', S) then tye
wenzelm@256
   843
                                 else raise TUNIFY
wenzelm@256
   844
        | Wk(T as Type(f, Ts)) =
wenzelm@256
   845
           if null S then tye
nipkow@963
   846
           else foldr Wd (Ts~~(Dom (subclass, arities) (f, S)) , tye)
clasohm@0
   847
  in Wk(T) end;
clasohm@0
   848
clasohm@0
   849
clasohm@0
   850
(* Order-sorted Unification of Types (U)  *)
clasohm@0
   851
clasohm@0
   852
(* Precondition: both types are well-formed w.r.t. type constructor arities *)
nipkow@963
   853
fun unify (tsig as TySg{subclass, arities, ...}) =
wenzelm@256
   854
  let fun unif ((T, U), tye) =
wenzelm@256
   855
        case (devar(T, tye), devar(U, tye)) of
wenzelm@256
   856
          (T as TVar(v, S1), U as TVar(w, S2)) =>
clasohm@0
   857
             if v=w then tye else
wenzelm@256
   858
             if sortorder subclass (S1, S2) then (w, T)::tye else
wenzelm@256
   859
             if sortorder subclass (S2, S1) then (v, U)::tye
wenzelm@256
   860
             else let val nu = gen_tyvar (union_sort subclass (S1, S2))
wenzelm@256
   861
                  in (v, nu)::(w, nu)::tye end
wenzelm@256
   862
        | (T as TVar(v, S), U) =>
nipkow@963
   863
             if occ v tye U then raise TUNIFY else W ((U,S), tsig, (v, U)::tye)
wenzelm@256
   864
        | (U, T as TVar (v, S)) =>
nipkow@963
   865
             if occ v tye U then raise TUNIFY else W ((U,S), tsig, (v, U)::tye)
wenzelm@256
   866
        | (Type(a, Ts), Type(b, Us)) =>
wenzelm@256
   867
             if a<>b then raise TUNIFY else foldr unif (Ts~~Us, tye)
wenzelm@256
   868
        | (T, U) => if T=U then tye else raise TUNIFY
clasohm@0
   869
  in unif end;
clasohm@0
   870
clasohm@0
   871
wenzelm@450
   872
(* raw_unify (ignores sorts) *)
wenzelm@450
   873
wenzelm@450
   874
fun raw_unify (ty1, ty2) =
wenzelm@450
   875
  (unify tsig0 ((rem_sorts ty1, rem_sorts ty2), []); true)
wenzelm@450
   876
    handle TUNIFY => false;
wenzelm@450
   877
wenzelm@450
   878
clasohm@0
   879
(*Type inference for polymorphic term*)
clasohm@0
   880
fun infer tsig =
wenzelm@256
   881
  let fun inf(Ts, Const (_, T), tye) = (T, tye)
wenzelm@256
   882
        | inf(Ts, Free  (_, T), tye) = (T, tye)
wenzelm@256
   883
        | inf(Ts, Bound i, tye) = ((nth_elem(i, Ts) , tye)
clasohm@0
   884
          handle LIST _=> raise TYPE ("loose bound variable", [], [Bound i]))
wenzelm@256
   885
        | inf(Ts, Var (_, T), tye) = (T, tye)
wenzelm@256
   886
        | inf(Ts, Abs (_, T, body), tye) =
wenzelm@256
   887
            let val (U, tye') = inf(T::Ts, body, tye) in  (T-->U, tye')  end
clasohm@0
   888
        | inf(Ts, f$u, tye) =
wenzelm@256
   889
            let val (U, tyeU) = inf(Ts, u, tye);
wenzelm@256
   890
                val (T, tyeT) = inf(Ts, f, tyeU);
clasohm@0
   891
                fun err s =
clasohm@0
   892
                  raise TYPE(s, [inst_typ tyeT T, inst_typ tyeT U], [f$u])
wenzelm@256
   893
            in case T of
wenzelm@256
   894
                 Type("fun", [T1, T2]) =>
wenzelm@256
   895
                   ( (T2, unify tsig ((T1, U), tyeT))
clasohm@0
   896
                     handle TUNIFY => err"type mismatch in application" )
wenzelm@256
   897
               | TVar _ =>
clasohm@0
   898
                   let val T2 = gen_tyvar([])
clasohm@0
   899
                   in (T2, unify tsig ((T, U-->T2), tyeT))
clasohm@0
   900
                      handle TUNIFY => err"type mismatch in application"
clasohm@0
   901
                   end
clasohm@0
   902
               | _ => err"rator must have function type"
clasohm@0
   903
           end
clasohm@0
   904
  in inf end;
clasohm@0
   905
nipkow@949
   906
val freeze_vars =
nipkow@949
   907
      map_type_tvar (fn (v, S) => TFree(Syntax.string_of_vname v, S));
clasohm@0
   908
clasohm@0
   909
(* Attach a type to a constant *)
wenzelm@256
   910
fun type_const (a, T) = Const(a, incr_tvar (new_tvar_inx()) T);
clasohm@0
   911
clasohm@0
   912
(*Find type of ident.  If not in table then use ident's name for tyvar
clasohm@0
   913
  to get consistent typing.*)
wenzelm@256
   914
fun new_id_type a = TVar(("'"^a, new_tvar_inx()), []);
wenzelm@256
   915
fun type_of_ixn(types, ixn as (a, _)) =
wenzelm@565
   916
  case types ixn of Some T => freeze_vars T | None => TVar(("'"^a, ~1), []);
wenzelm@565
   917
wenzelm@565
   918
fun constrain (term, T) = Const (Syntax.constrainC, T --> T) $ term;
clasohm@0
   919
wenzelm@565
   920
fun constrainAbs (Abs (a, _, body), T) = Abs (a, T, body)
wenzelm@565
   921
  | constrainAbs _ = sys_error "constrainAbs";
wenzelm@256
   922
clasohm@0
   923
wenzelm@565
   924
(* attach_types *)
wenzelm@565
   925
clasohm@0
   926
(*
wenzelm@256
   927
  Attach types to a term. Input is a "parse tree" containing dummy types.
wenzelm@256
   928
  Type constraints are translated and checked for validity wrt tsig. TVars in
wenzelm@256
   929
  constraints are frozen.
clasohm@0
   930
wenzelm@256
   931
  The atoms in the resulting term satisfy the following spec:
clasohm@0
   932
wenzelm@256
   933
  Const (a, T):
wenzelm@256
   934
    T is a renamed copy of the generic type of a; renaming decreases index of
wenzelm@256
   935
    all TVars by new_tvar_inx(), which is less than ~1. The index of all
wenzelm@256
   936
    TVars in the generic type must be 0 for this to work!
clasohm@0
   937
wenzelm@256
   938
  Free (a, T), Var (ixn, T):
wenzelm@256
   939
    T is either the frozen default type of a or TVar (("'"^a, ~1), [])
clasohm@0
   940
wenzelm@256
   941
  Abs (a, T, _):
wenzelm@256
   942
    T is either a type constraint or TVar (("'" ^ a, i), []), where i is
wenzelm@256
   943
    generated by new_tvar_inx(). Thus different abstractions can have the
wenzelm@256
   944
    bound variables of the same name but different types.
clasohm@0
   945
*)
clasohm@0
   946
wenzelm@565
   947
(* FIXME consitency of sort_env / sorts (!?) *)
wenzelm@256
   948
wenzelm@565
   949
fun attach_types (tsig, const_type, types, sorts) tm =
wenzelm@256
   950
  let
wenzelm@565
   951
    val sort_env = Syntax.raw_term_sorts tm;
wenzelm@565
   952
    fun def_sort xi = if_none (sorts xi) (defaultS tsig);
wenzelm@256
   953
wenzelm@565
   954
    fun prepareT t =
wenzelm@565
   955
      freeze_vars (cert_typ tsig (Syntax.typ_of_term sort_env def_sort t));
wenzelm@256
   956
wenzelm@256
   957
    fun add (Const (a, _)) =
wenzelm@565
   958
          (case const_type a of
wenzelm@256
   959
            Some T => type_const (a, T)
wenzelm@256
   960
          | None => raise_type ("No such constant: " ^ quote a) [] [])
wenzelm@256
   961
      | add (Free (a, _)) =
wenzelm@565
   962
          (case const_type a of
wenzelm@256
   963
            Some T => type_const (a, T)
wenzelm@256
   964
          | None => Free (a, type_of_ixn (types, (a, ~1))))
wenzelm@256
   965
      | add (Var (ixn, _)) = Var (ixn, type_of_ixn (types, ixn))
wenzelm@565
   966
      | add (Bound i) = Bound i
wenzelm@256
   967
      | add (Abs (a, _, body)) = Abs (a, new_id_type a, add body)
wenzelm@256
   968
      | add ((f as Const (a, _) $ t1) $ t2) =
wenzelm@256
   969
          if a = Syntax.constrainC then
wenzelm@256
   970
            constrain (add t1, prepareT t2)
wenzelm@256
   971
          else if a = Syntax.constrainAbsC then
wenzelm@256
   972
            constrainAbs (add t1, prepareT t2)
wenzelm@256
   973
          else add f $ add t2
wenzelm@256
   974
      | add (f $ t) = add f $ add t;
wenzelm@565
   975
  in add tm end;
clasohm@0
   976
clasohm@0
   977
clasohm@0
   978
(* Post-Processing *)
clasohm@0
   979
clasohm@0
   980
(*Instantiation of type variables in terms*)
clasohm@0
   981
fun inst_types tye = map_term_types (inst_typ tye);
clasohm@0
   982
clasohm@0
   983
(*Delete explicit constraints -- occurrences of "_constrain" *)
wenzelm@256
   984
fun unconstrain (Abs(a, T, t)) = Abs(a, T, unconstrain t)
wenzelm@256
   985
  | unconstrain ((f as Const(a, _)) $ t) =
clasohm@0
   986
      if a=Syntax.constrainC then unconstrain t
clasohm@0
   987
      else unconstrain f $ unconstrain t
clasohm@0
   988
  | unconstrain (f$t) = unconstrain f $ unconstrain t
clasohm@0
   989
  | unconstrain (t) = t;
clasohm@0
   990
nipkow@949
   991
fun nextname(pref,c) = if c="z" then (pref^"a", "a") else (pref,chr(ord(c)+1));
clasohm@0
   992
nipkow@949
   993
fun newtvars used =
nipkow@949
   994
  let fun new([],_,vmap) = vmap
nipkow@949
   995
        | new(ixn::ixns,p as (pref,c),vmap) =
nipkow@949
   996
            let val nm = pref ^ c
nipkow@949
   997
            in if nm mem used then new(ixn::ixns,nextname p, vmap)
nipkow@949
   998
               else new(ixns, nextname p, (ixn,nm)::vmap)
nipkow@949
   999
            end
nipkow@949
  1000
  in new end;
nipkow@949
  1001
nipkow@949
  1002
(*
nipkow@949
  1003
Turn all TVars which satisfy p into new (if freeze then TFrees else TVars).
nipkow@949
  1004
Note that if t contains frozen TVars there is the possibility that a TVar is
nipkow@949
  1005
turned into one of those. This is sound but not complete.
nipkow@949
  1006
*)
nipkow@949
  1007
fun convert used freeze p t =
nipkow@949
  1008
  let val used = if freeze then add_term_tfree_names(t, used)
nipkow@949
  1009
                 else used union
nipkow@949
  1010
                      (map #1 (filter_out p (add_term_tvar_ixns(t, []))))
nipkow@949
  1011
      val ixns = filter p (add_term_tvar_ixns(t, []));
nipkow@949
  1012
      val vmap = newtvars used (ixns,("'","a"),[]);
nipkow@949
  1013
      fun conv(var as (ixn,S)) = case assoc(vmap,ixn) of
nipkow@949
  1014
            None => TVar(var) |
nipkow@949
  1015
            Some(a) => if freeze then TFree(a,S) else TVar((a,0),S);
nipkow@949
  1016
  in map_term_types (map_type_tvar conv) t end;
nipkow@949
  1017
nipkow@949
  1018
fun freeze t = convert (add_term_tfree_names(t,[])) true (K true) t;
clasohm@0
  1019
clasohm@0
  1020
(* Thaw all TVars that were frozen in freeze_vars *)
nipkow@949
  1021
val thaw_vars =
nipkow@949
  1022
  let fun thaw(f as (a, S)) = (case explode a of
wenzelm@256
  1023
          "?"::"'"::vn => let val ((b, i), _) = Syntax.scan_varname vn
wenzelm@256
  1024
                          in TVar(("'"^b, i), S) end
nipkow@949
  1025
        | _ => TFree f)
nipkow@949
  1026
  in map_type_tfree thaw end;
clasohm@0
  1027
clasohm@0
  1028
clasohm@0
  1029
fun restrict tye =
wenzelm@256
  1030
  let fun clean(tye1, ((a, i), T)) =
wenzelm@256
  1031
        if i < 0 then tye1 else ((a, i), inst_typ tye T) :: tye1
wenzelm@256
  1032
  in foldl clean ([], tye) end
clasohm@0
  1033
clasohm@0
  1034
clasohm@0
  1035
(*Infer types for term t using tables. Check that t's type and T unify *)
nipkow@949
  1036
(*freeze determines if internal TVars are turned into TFrees or TVars*)
nipkow@949
  1037
fun infer_term (tsig, const_type, types, sorts, used, freeze, T, t) =
wenzelm@565
  1038
  let
wenzelm@565
  1039
    val u = attach_types (tsig, const_type, types, sorts) t;
wenzelm@565
  1040
    val (U, tye) = infer tsig ([], u, []);
wenzelm@565
  1041
    val uu = unconstrain u;
wenzelm@565
  1042
    val tye' = unify tsig ((T, U), tye) handle TUNIFY => raise TYPE
wenzelm@565
  1043
      ("Term does not have expected type", [T, U], [inst_types tye uu])
wenzelm@565
  1044
    val Ttye = restrict tye' (*restriction to TVars in T*)
wenzelm@565
  1045
    val all = Const("", Type("", map snd Ttye)) $ (inst_types tye' uu)
wenzelm@565
  1046
      (*all is a dummy term which contains all exported TVars*)
wenzelm@565
  1047
    val Const(_, Type(_, Ts)) $ u'' =
nipkow@949
  1048
      map_term_types thaw_vars (convert used freeze (fn (_, i) => i < 0) all)
nipkow@949
  1049
      (*convert all internally generated TVars into TFrees or TVars
wenzelm@565
  1050
        and thaw all initially frozen TVars*)
wenzelm@565
  1051
  in
wenzelm@565
  1052
    (u'', (map fst Ttye) ~~ Ts)
wenzelm@565
  1053
  end;
clasohm@0
  1054
wenzelm@621
  1055
fun infer_types args = (tyinit (); infer_term args);
clasohm@0
  1056
clasohm@0
  1057
clasohm@0
  1058
end;