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