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