src/Pure/type.ML
author nipkow
Mon Mar 13 09:38:10 1995 +0100 (1995-03-13)
changeset 949 83c588d6fee9
parent 621 9d8791da0208
child 963 7a78fda77104
permissions -rw-r--r--
Changed treatment of during type inference internally generated type
variables.

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