src/Pure/type.ML
author nipkow
Tue Dec 21 16:26:40 1993 +0100 (1993-12-21)
changeset 200 39a931cc6558
parent 189 831a9a7ab9f3
child 256 b401c3d06024
permissions -rw-r--r--
Necessary changes to accomodate type abbreviations.
clasohm@0
     1
(*  Title: 	Types and Sorts
nipkow@200
     2
    Author:	Tobias Nipkow & Lawrence C Paulson
clasohm@0
     3
    ID:         $Id$
clasohm@0
     4
clasohm@0
     5
Maybe type classes should go in a separate module?
clasohm@0
     6
*)
clasohm@0
     7
clasohm@0
     8
clasohm@0
     9
signature TYPE =
clasohm@0
    10
sig
clasohm@0
    11
  structure Symtab:SYMTAB
clasohm@0
    12
  type type_sig
nipkow@200
    13
  val rep_tsig: type_sig ->
nipkow@200
    14
    {classes: class list, default: sort,
nipkow@200
    15
      subclass: (class * class list) list,
nipkow@200
    16
      args: (string * int) list,
nipkow@200
    17
      coreg: (string * (class * sort list) list) list,
nipkow@200
    18
      abbr: (string * (indexname list * typ) ) list}
clasohm@0
    19
  val defaultS: type_sig -> sort
nipkow@200
    20
  val add_abbrs : type_sig * (string * (indexname list * typ)) list
nipkow@200
    21
                    -> type_sig
nipkow@200
    22
  val expand_typ: type_sig -> typ -> typ 
clasohm@0
    23
  val extend: type_sig * (class * class list)list * sort *
clasohm@0
    24
	      (string list * int)list *
clasohm@0
    25
	      (string list * (sort list * class))list -> type_sig
clasohm@0
    26
  val freeze: (indexname -> bool) -> term -> term
clasohm@0
    27
  val freeze_vars: typ -> typ
clasohm@0
    28
  val infer_types: type_sig * typ Symtab.table * (indexname -> typ option) *
clasohm@0
    29
		   (indexname -> sort option) * (typ -> string) * typ * term
clasohm@0
    30
		   -> term * (indexname*typ)list
clasohm@0
    31
  val inst_term_tvars: type_sig * (indexname * typ)list -> term -> term
clasohm@0
    32
  val logical_type: type_sig -> string -> bool
nipkow@189
    33
  val logical_types: type_sig -> string list
clasohm@0
    34
  val merge: type_sig * type_sig -> type_sig
clasohm@0
    35
  val thaw_vars: typ -> typ
clasohm@0
    36
  val tsig0: type_sig
nipkow@200
    37
  val type_errors: type_sig -> typ * string list -> string list
clasohm@0
    38
  val typ_instance: type_sig * typ * typ -> bool
clasohm@0
    39
  val typ_match: type_sig -> (indexname*typ)list * (typ*typ) ->
clasohm@0
    40
		 (indexname*typ)list
clasohm@0
    41
  val unify: type_sig -> (typ*typ) * (indexname*typ)list -> (indexname*typ)list
clasohm@0
    42
  val varifyT: typ -> typ
clasohm@0
    43
  val varify: term * string list -> term
clasohm@0
    44
  exception TUNIFY
clasohm@0
    45
  exception TYPE_MATCH;
clasohm@0
    46
end;
clasohm@0
    47
nipkow@200
    48
functor TypeFun(structure Symtab:SYMTAB and Syntax:SYNTAX) (*: TYPE*) = 
clasohm@0
    49
struct
clasohm@0
    50
structure Symtab = Symtab
clasohm@0
    51
clasohm@0
    52
(* Miscellany *)
clasohm@0
    53
clasohm@0
    54
val commas = space_implode ",";
clasohm@0
    55
fun str_of_sort S = "{" ^ commas S ^ "}";
clasohm@0
    56
fun str_of_dom dom = "(" ^ commas (map str_of_sort dom) ^ ")";
clasohm@0
    57
fun str_of_decl(t,w,C) = t ^ ": " ^ str_of_dom w ^ C;
clasohm@0
    58
clasohm@0
    59
clasohm@0
    60
(* Association list Manipulation  *)
clasohm@0
    61
clasohm@0
    62
clasohm@0
    63
(* two-fold Association list lookup *)
clasohm@0
    64
clasohm@0
    65
fun assoc2 (aal,(key1,key2)) = case assoc (aal,key1) of
clasohm@0
    66
    Some (al) => assoc (al,key2)
clasohm@0
    67
  | None => None;
clasohm@0
    68
clasohm@0
    69
clasohm@0
    70
clasohm@0
    71
(**** TYPE CLASSES ****)
clasohm@0
    72
clasohm@0
    73
type domain = sort list;
clasohm@0
    74
type arity = domain * class;
clasohm@0
    75
clasohm@0
    76
datatype type_sig =
clasohm@0
    77
   TySg of {classes: class list,
clasohm@0
    78
	    default: sort,
clasohm@0
    79
	    subclass: (class * class list) list,
clasohm@0
    80
	    args: (string * int) list,
nipkow@200
    81
	    coreg: (string * (class * domain) list) list,
nipkow@200
    82
            abbr: (string * (indexname list * typ) ) list };
clasohm@0
    83
clasohm@0
    84
(* classes: a list of all declared classes;
clasohm@0
    85
   default: the default sort attached to all unconstrained TVars
clasohm@0
    86
            occurring in a term to be type-inferred;
clasohm@0
    87
   subclass: association list representation of subclass relationship;
clasohm@0
    88
             (c,cs) is interpreted as "c is a proper subclass of all
clasohm@0
    89
             elemenst of cs". Note that c itself is not a memeber of cs.
clasohm@0
    90
   args: an association list of all declared types with the number of their
clasohm@0
    91
         arguments
clasohm@0
    92
   coreg: a two-fold association list of all type arities; (t,al) means that
clasohm@0
    93
          type constructor t has the arities in al; an element (c,ss) of al
clasohm@0
    94
          represents the arity (ss)c
nipkow@200
    95
   abbr: an association list of type abbreviations
clasohm@0
    96
*)
clasohm@0
    97
nipkow@189
    98
fun rep_tsig (TySg comps) = comps;
nipkow@200
    99
 
clasohm@0
   100
clasohm@0
   101
val tsig0 = TySg{classes = [],
clasohm@0
   102
		 default = [],
clasohm@0
   103
		 subclass = [],
clasohm@0
   104
		 args = [],
nipkow@200
   105
		 coreg = [],
nipkow@200
   106
                 abbr = []};
clasohm@0
   107
clasohm@0
   108
fun undcl_class (s) = error("Class " ^ s ^ " has not been declared");
clasohm@0
   109
clasohm@0
   110
fun undcl_type(c) = "Undeclared type: " ^ c;
clasohm@0
   111
fun undcl_type_err(c) = error(undcl_type(c));
clasohm@0
   112
clasohm@0
   113
clasohm@0
   114
(* 'leq' checks the partial order on classes according to the
clasohm@0
   115
   statements in the association list 'a' (i.e.'subclass')
clasohm@0
   116
*)
clasohm@0
   117
clasohm@0
   118
fun less a (C,D) = case assoc (a,C) of
clasohm@0
   119
     Some(ss) => D mem ss
clasohm@0
   120
   | None => undcl_class (C) ;
clasohm@0
   121
clasohm@0
   122
fun leq a (C,D)  =  C = D orelse less a (C,D);
clasohm@0
   123
clasohm@0
   124
clasohm@0
   125
fun defaultS(TySg{default,...}) = default;
clasohm@0
   126
clasohm@0
   127
(* 'logical_type' checks if some type declaration t has as range
clasohm@0
   128
   a class which is a subclass of "logic" *)
clasohm@0
   129
clasohm@0
   130
fun logical_type(tsig as TySg{subclass,coreg,...}) t =
clasohm@0
   131
  let fun is_log C = leq subclass (C,"logic")
clasohm@0
   132
  in case assoc (coreg,t) of
clasohm@0
   133
      Some(ars) => exists (is_log o #1) ars
clasohm@0
   134
    | None => undcl_type_err(t)
clasohm@0
   135
  end;
clasohm@0
   136
nipkow@162
   137
fun logical_types (tsig as TySg {args, ...}) =
nipkow@162
   138
  filter (logical_type tsig) (map #1 args);
nipkow@162
   139
clasohm@0
   140
(* 'sortorder' checks the ordering on sets of classes,i.e. on sorts:
clasohm@0
   141
   S1 <= S2 ,iff for every class C2 in S2 there exists a class C1 in S1
clasohm@0
   142
   with C1 <= C2 (according to an association list 'a')
clasohm@0
   143
*)
clasohm@0
   144
clasohm@0
   145
fun sortorder a (S1,S2) =
clasohm@0
   146
  forall  (fn C2 => exists  (fn C1 => leq a (C1,C2))  S1)  S2;
clasohm@0
   147
clasohm@0
   148
clasohm@0
   149
(* 'inj' inserts a new class C into a given class set S (i.e.sort) only if
clasohm@0
   150
  there exists no class in S which is <= C;
clasohm@0
   151
  the resulting set is minimal if S was minimal
clasohm@0
   152
*)
clasohm@0
   153
clasohm@0
   154
fun inj a (C,S) =
clasohm@0
   155
  let fun inj1 [] = [C]
clasohm@0
   156
        | inj1 (D::T) = if leq a (D,C) then D::T
clasohm@0
   157
                        else if leq a (C,D) then inj1 T
clasohm@0
   158
                             else D::(inj1 T)
clasohm@0
   159
  in inj1 S end;
clasohm@0
   160
clasohm@0
   161
clasohm@0
   162
(* 'union_sort' forms the minimal union set of two sorts S1 and S2
clasohm@0
   163
   under the assumption that S2 is minimal *)
clasohm@0
   164
clasohm@0
   165
fun union_sort a = foldr (inj a);
clasohm@0
   166
clasohm@0
   167
clasohm@0
   168
(* 'elementwise_union' forms elementwise the minimal union set of two
clasohm@0
   169
   sort lists under the assumption that the two lists have the same length
clasohm@0
   170
*) 
clasohm@0
   171
clasohm@0
   172
fun elementwise_union a (Ss1,Ss2) = map (union_sort a) (Ss1~~Ss2);
clasohm@0
   173
   
clasohm@0
   174
clasohm@0
   175
(* 'lew' checks for two sort lists the ordering for all corresponding list
clasohm@0
   176
   elements (i.e. sorts) *)
clasohm@0
   177
clasohm@0
   178
fun lew a (w1,w2) = forall (sortorder a)  (w1~~w2);
clasohm@0
   179
clasohm@0
   180
 
clasohm@0
   181
(* 'is_min' checks if a class C is minimal in a given sort S under the 
clasohm@0
   182
   assumption that S contains C *) 
clasohm@0
   183
clasohm@0
   184
fun is_min a S C = not (exists (fn (D) => less a (D,C)) S);
clasohm@0
   185
clasohm@0
   186
clasohm@0
   187
(* 'min_sort' reduces a sort to its minimal classes *)
clasohm@0
   188
clasohm@0
   189
fun min_sort a S = distinct(filter (is_min a S) S);
clasohm@0
   190
clasohm@0
   191
clasohm@0
   192
(* 'min_domain' minimizes the domain sorts of type declarationsl;
clasohm@0
   193
   the function will be applied on the type declarations in extensions *) 
clasohm@0
   194
clasohm@0
   195
fun min_domain subclass =
clasohm@0
   196
  let fun one_min (f,(doms,ran)) = (f, (map (min_sort subclass) doms, ran))
clasohm@0
   197
  in map one_min end;
clasohm@0
   198
clasohm@0
   199
clasohm@0
   200
(* 'min_filter' filters a list 'ars' consisting of arities (domain * class)
clasohm@0
   201
   and gives back a list of those range classes whose domains meet the 
clasohm@0
   202
   predicate 'pred' *)
clasohm@0
   203
   
clasohm@0
   204
fun min_filter a pred ars =
clasohm@0
   205
  let fun filt ([],l) = l
clasohm@0
   206
        | filt ((c,x)::xs,l) = if pred(x) then filt (xs,inj a (c,l))
clasohm@0
   207
                               else filt (xs,l)
clasohm@0
   208
  in filt (ars,[]) end;
clasohm@0
   209
clasohm@0
   210
clasohm@0
   211
(* 'cod_above' filters all arities whose domains are elementwise >= than
clasohm@0
   212
   a given domain 'w' and gives back a list of the corresponding range 
clasohm@0
   213
   classes *)
clasohm@0
   214
clasohm@0
   215
fun cod_above (a,w,ars) = min_filter a (fn w' => lew a (w,w')) ars;
clasohm@0
   216
nipkow@200
   217
(*Instantiation of type variables in types*)
nipkow@200
   218
(*Pre: instantiations obey restrictions! *)
nipkow@200
   219
fun inst_typ tye =
nipkow@200
   220
  let fun inst(Type(a,Ts)) = Type(a, map inst Ts)
nipkow@200
   221
        | inst(T as TFree _) = T
nipkow@200
   222
        | inst(T as TVar(v,_)) =
nipkow@200
   223
            (case assoc(tye,v) of Some U => inst U | None => T)
nipkow@200
   224
  in inst end;
clasohm@0
   225
clasohm@0
   226
(* 'least_sort' returns for a given type its maximum sort:
clasohm@0
   227
   - type variables, free types: the sort brought with
clasohm@0
   228
   - type constructors: recursive determination of the maximum sort of the
clasohm@0
   229
                    arguments if the type is declared in 'coreg' of the 
clasohm@0
   230
                    given type signature  *) 
clasohm@0
   231
nipkow@200
   232
fun least_sort (tsig as TySg{subclass,coreg,abbr,...}) =
clasohm@0
   233
  let fun ls(T as Type(a,Ts)) =
nipkow@200
   234
            (case assoc(abbr,a) of
nipkow@200
   235
               Some(v,U) => ls(inst_typ(v~~Ts) U)
nipkow@200
   236
             | None => (case assoc (coreg,a) of
nipkow@200
   237
                          Some(ars) => cod_above(subclass,map ls Ts,ars)
nipkow@200
   238
			| None => raise TYPE(undcl_type a,[T],[])))
clasohm@0
   239
	| ls(TFree(a,S)) = S
clasohm@0
   240
	| ls(TVar(a,S)) = S
clasohm@0
   241
  in ls end;
clasohm@0
   242
clasohm@0
   243
clasohm@0
   244
fun check_has_sort(tsig as TySg{subclass,coreg,...},T,S) =
clasohm@0
   245
  if sortorder subclass ((least_sort tsig T),S) then ()
clasohm@0
   246
  else raise TYPE("Type not of sort " ^ (str_of_sort S),[T],[])
clasohm@0
   247
clasohm@0
   248
clasohm@0
   249
(*Instantiation of type variables in types *)
clasohm@0
   250
fun inst_typ_tvars(tsig,tye) =
clasohm@0
   251
  let fun inst(Type(a,Ts)) = Type(a, map inst Ts)
clasohm@0
   252
	| inst(T as TFree _) = T
clasohm@0
   253
	| inst(T as TVar(v,S)) = (case assoc(tye,v) of
clasohm@0
   254
		None => T | Some(U) => (check_has_sort(tsig,U,S); U))
clasohm@0
   255
  in inst end;
clasohm@0
   256
clasohm@0
   257
(*Instantiation of type variables in terms *)
clasohm@0
   258
fun inst_term_tvars(tsig,tye) = map_term_types (inst_typ_tvars(tsig,tye));
clasohm@0
   259
nipkow@200
   260
nipkow@200
   261
(* expand1_typ *)
nipkow@200
   262
nipkow@200
   263
fun expand1_typ(abbr,a,Ts) =
nipkow@200
   264
         ( case assoc(abbr,a) of Some(v,U) => Some(inst_typ(v~~Ts) U)
nipkow@200
   265
                               | None      => None );
nipkow@200
   266
nipkow@200
   267
(* expand_typ *)
nipkow@200
   268
nipkow@200
   269
fun expand_typ(tsig as TySg{abbr,...}) =
nipkow@200
   270
  let fun exptyp(Type(a,Ts)) =
nipkow@200
   271
           ( case assoc(abbr,a) of
nipkow@200
   272
             Some (v,U) => exptyp(inst_typ(v~~Ts) U)
nipkow@200
   273
           | None       => Type(a, map exptyp Ts)    )
nipkow@200
   274
        | exptyp(T) = T
nipkow@200
   275
  in exptyp end;
nipkow@200
   276
clasohm@0
   277
exception TYPE_MATCH;
clasohm@0
   278
clasohm@0
   279
(* Typ matching
clasohm@0
   280
   typ_match(ts,s,(U,T)) = s' <=> s'(U)=T and s' is an extension of s *)
nipkow@200
   281
fun typ_match (tsig as TySg{abbr,...}) =
clasohm@0
   282
let fun tm(subs, (TVar(v,S), T)) = (case assoc(subs,v) of
clasohm@0
   283
		None => ( (v, (check_has_sort(tsig,T,S); T))::subs
clasohm@0
   284
			handle TYPE _ => raise TYPE_MATCH )
nipkow@200
   285
	      | Some(U) => if expand_typ tsig U = expand_typ tsig T
nipkow@200
   286
                           then subs
nipkow@200
   287
                           else raise TYPE_MATCH)
nipkow@200
   288
      | tm(subs, (T as Type(a,Ts), U as Type(b,Us))) =
nipkow@200
   289
        if a<>b then
nipkow@200
   290
            (case (expand1_typ(abbr,a,Ts), expand1_typ(abbr,b,Us)) of
nipkow@200
   291
                             (None,None) => raise TYPE_MATCH
nipkow@200
   292
                           | (None,Some(U)) => tm(subs,(T,U))
nipkow@200
   293
                           | (Some(T),None) => tm(subs,(T,U))
nipkow@200
   294
                           | (Some(T),Some(U)) => tm(subs,(T,U)))
clasohm@0
   295
	else foldl tm (subs, Ts~~Us)
clasohm@0
   296
      | tm(subs, (TFree(x), TFree(y))) =
clasohm@0
   297
	if x=y then subs else raise TYPE_MATCH
clasohm@0
   298
      | tm _ = raise TYPE_MATCH
clasohm@0
   299
in tm end;
clasohm@0
   300
clasohm@0
   301
fun typ_instance(tsig,T,U) = let val x = typ_match tsig ([],(U,T)) in true end
clasohm@0
   302
			     handle TYPE_MATCH => false;
clasohm@0
   303
clasohm@0
   304
clasohm@0
   305
(* EXTENDING AND MERGIN TYPE SIGNATURES *)
clasohm@0
   306
clasohm@0
   307
fun not_ident(s) = error("Must be an identifier: " ^ s);
clasohm@0
   308
clasohm@0
   309
fun twice(a) = error("Type constructor " ^a^ " has already been declared.");
clasohm@0
   310
nipkow@200
   311
fun tyab_conflict(a) = error("Canīt declare type "^(quote a)^"!\nAn abbreviation with this name exists already.");
nipkow@200
   312
clasohm@0
   313
(*Is the type valid? Accumulates error messages in "errs".*)
nipkow@200
   314
fun type_errors (tsig as TySg{classes,args,abbr,...}) =
nipkow@200
   315
  let fun class_err(errs,C) =
nipkow@200
   316
            if C mem classes then errs
nipkow@200
   317
	    else ("Class " ^ quote C ^ " has not been declared") :: errs
nipkow@200
   318
      val sort_err = foldl class_err
nipkow@200
   319
      fun errors(Type(c,Us), errs) =
clasohm@0
   320
	let val errs' = foldr errors (Us,errs)
nipkow@200
   321
            fun nargs n = if n=length(Us) then errs'
nipkow@200
   322
		          else ("Wrong number of arguments: " ^ c) :: errs'
clasohm@0
   323
	in case assoc(args,c) of
nipkow@200
   324
	     Some(n) => nargs n
nipkow@200
   325
	   | None => (case assoc(abbr,c) of
nipkow@200
   326
                        Some(v,_) => nargs(length v)
nipkow@200
   327
                      | None => (undcl_type c) :: errs)
clasohm@0
   328
	end
nipkow@200
   329
      | errors(TFree(_,S), errs) = sort_err(errs,S)
nipkow@200
   330
      | errors(TVar(_,S), errs) = sort_err(errs,S)
nipkow@200
   331
  in errors end;
clasohm@0
   332
clasohm@0
   333
clasohm@0
   334
(* 'add_class' adds a new class to the list of all existing classes *) 
clasohm@0
   335
clasohm@0
   336
fun add_class (classes,(s,_)) =
clasohm@0
   337
  if s mem classes then error("Class " ^ s ^ " declared twice.")
clasohm@0
   338
  else s::classes;
clasohm@0
   339
clasohm@0
   340
(* 'add_subclass' adds a tuple consisiting of a new class (the new class
clasohm@0
   341
   has already been inserted into the 'classes' list) and its
clasohm@0
   342
   superclasses (they must be declared in 'classes' too) to the 'subclass' 
clasohm@0
   343
   list of the given type signature; 
clasohm@0
   344
   furthermore all inherited superclasses according to the superclasses 
clasohm@0
   345
   brought with are inserted and there is a check that there are no
clasohm@0
   346
   cycles (i.e. C <= D <= C, with C <> D); *)
clasohm@0
   347
clasohm@0
   348
fun add_subclass classes (subclass,(s,ges)) =
clasohm@0
   349
let fun upd (subclass,s') = if s' mem classes then
clasohm@0
   350
        let val Some(ges') = assoc (subclass,s)
clasohm@0
   351
        in case assoc (subclass,s') of
clasohm@0
   352
             Some(sups) => if s mem sups
clasohm@0
   353
                           then error(" Cycle :" ^ s^" <= "^ s'^" <= "^ s )
clasohm@0
   354
                           else overwrite (subclass,(s,sups union ges'))
clasohm@0
   355
           | None => subclass
clasohm@0
   356
         end
clasohm@0
   357
         else undcl_class(s')
clasohm@0
   358
in foldl upd (subclass@[(s,ges)],ges) end;
clasohm@0
   359
clasohm@0
   360
clasohm@0
   361
(* 'extend_classes' inserts all new classes into the corresponding
clasohm@0
   362
   lists ('classes','subclass') if possible *)
clasohm@0
   363
clasohm@0
   364
fun extend_classes (classes,subclass,newclasses) =
clasohm@0
   365
  if newclasses = [] then (classes,subclass) else
clasohm@0
   366
  let val classes' = foldl add_class (classes,newclasses);
clasohm@0
   367
      val subclass' = foldl (add_subclass classes') (subclass,newclasses);
clasohm@0
   368
  in (classes',subclass') end;
clasohm@0
   369
clasohm@0
   370
(* Corregularity *)
clasohm@0
   371
clasohm@0
   372
(* 'is_unique_decl' checks if there exists just one declaration t:(Ss)C *)
clasohm@0
   373
clasohm@0
   374
fun is_unique_decl coreg (t,(s,w)) = case assoc2 (coreg,(t,s)) of
clasohm@0
   375
      Some(w1) => if w = w1 then () else
clasohm@0
   376
	error("There are two declarations\n" ^
clasohm@0
   377
              str_of_decl(t,w,s) ^ " and\n" ^
clasohm@0
   378
	      str_of_decl(t,w1,s) ^ "\n" ^
clasohm@0
   379
              "with the same result class.")
clasohm@0
   380
    | None => ();
clasohm@0
   381
clasohm@0
   382
(* 'restr2' checks if there are two declarations t:(Ss1)C1 and t:(Ss2)C2
clasohm@0
   383
   such that C1 >= C2 then Ss1 >= Ss2 (elementwise) *)
clasohm@0
   384
clasohm@0
   385
fun subs (classes,subclass) C = 
clasohm@0
   386
  let fun sub (rl,l) = if leq subclass (l,C) then l::rl else rl
clasohm@0
   387
  in foldl sub ([],classes) end;
clasohm@0
   388
clasohm@0
   389
fun coreg_err(t,(w1,C),(w2,D)) =
clasohm@0
   390
    error("Declarations " ^ str_of_decl(t,w1,C) ^ " and "
clasohm@0
   391
                          ^ str_of_decl(t,w2,D) ^ " are in conflict");
clasohm@0
   392
clasohm@0
   393
fun restr2 classes (subclass,coreg) (t,(s,w)) =
clasohm@0
   394
  let fun restr ([],test) = ()
clasohm@0
   395
        | restr (s1::Ss,test) = (case assoc2 (coreg,(t,s1)) of
clasohm@0
   396
              Some (dom) => if lew subclass (test (w,dom)) then restr (Ss,test)
clasohm@0
   397
                            else coreg_err (t,(w,s),(dom,s1))
clasohm@0
   398
            | None => restr (Ss,test))
clasohm@0
   399
      fun forward (t,(s,w)) =
clasohm@0
   400
        let val s_sups = case assoc (subclass,s) of
clasohm@0
   401
                   Some(s_sups) => s_sups | None => undcl_class(s);
clasohm@0
   402
        in restr (s_sups,I) end
clasohm@0
   403
      fun backward (t,(s,w)) =
clasohm@0
   404
        let val s_subs = subs (classes,subclass) s
clasohm@0
   405
        in restr (s_subs,fn (x,y) => (y,x)) end
clasohm@0
   406
  in (backward (t,(s,w)); forward (t,(s,w))) end;
clasohm@0
   407
clasohm@0
   408
clasohm@0
   409
fun varying_decls(t) =
clasohm@0
   410
    error("Type constructor "^t^" has varying number of arguments.");
clasohm@0
   411
clasohm@0
   412
clasohm@0
   413
clasohm@0
   414
(* 'coregular' checks
clasohm@0
   415
   - the two restriction conditions 'is_unique_decl' and 'restr2'
clasohm@0
   416
   - if the classes in the new type declarations are known in the 
clasohm@0
   417
     given type signature
clasohm@0
   418
   - if one type constructor has always the same number of arguments;
clasohm@0
   419
   if one type declaration has passed all checks it is inserted into 
clasohm@0
   420
   the 'coreg' association list of the given type signatrure  *)
clasohm@0
   421
clasohm@0
   422
fun coregular (classes,subclass,args) =
clasohm@0
   423
  let fun ex C = if C mem classes then () else undcl_class(C);
clasohm@0
   424
clasohm@0
   425
      fun addar(w,C) (coreg,t) = case assoc(args,t) of
clasohm@0
   426
            Some(n) => if n <> length w then varying_decls(t) else
clasohm@0
   427
                     (is_unique_decl coreg (t,(C,w));
clasohm@0
   428
	              (seq o seq) ex w;
clasohm@0
   429
	              restr2 classes (subclass,coreg) (t,(C,w));
clasohm@0
   430
                      let val Some(ars) = assoc(coreg,t)
clasohm@0
   431
                      in overwrite(coreg,(t,(C,w) ins ars)) end)
clasohm@0
   432
          | None => undcl_type_err(t);
clasohm@0
   433
clasohm@0
   434
      fun addts(coreg,(ts,ar)) = foldl (addar ar) (coreg,ts)
clasohm@0
   435
clasohm@0
   436
  in addts end;
clasohm@0
   437
clasohm@0
   438
clasohm@0
   439
(* 'close' extends the 'coreg' association list after all new type
clasohm@0
   440
   declarations have been inserted successfully:
clasohm@0
   441
   for every declaration t:(Ss)C , for all classses D with C <= D:
clasohm@0
   442
      if there is no declaration t:(Ss')C' with C < C' and C' <= D
clasohm@0
   443
      then insert the declaration t:(Ss)D into 'coreg'
clasohm@0
   444
   this means, if there exists a declaration t:(Ss)C and there is
clasohm@0
   445
   no declaration t:(Ss')D with C <=D then the declaration holds
clasohm@0
   446
   for all range classes more general than C *)   
clasohm@0
   447
   
clasohm@0
   448
fun close (coreg,subclass) =
clasohm@0
   449
  let fun check sl (l,(s,dom)) = case assoc (subclass,s) of
clasohm@0
   450
          Some(sups) =>
clasohm@0
   451
            let fun close_sup (l,sup) =
clasohm@0
   452
                  if exists (fn s'' => less subclass (s,s'') andalso
clasohm@0
   453
                                       leq subclass (s'',sup)) sl
clasohm@0
   454
                  then l
clasohm@0
   455
                  else (sup,dom)::l
clasohm@0
   456
            in foldl close_sup (l,sups) end
clasohm@0
   457
        | None => l;
clasohm@0
   458
      fun ext (s,l) = (s, foldl (check (map #1 l)) (l,l));
clasohm@0
   459
  in map ext coreg end;
clasohm@0
   460
nipkow@200
   461
fun add_types(aca,(ts,n)) =
nipkow@200
   462
  let fun add_type((args,coreg,abbr),t) = case assoc(args,t) of
nipkow@200
   463
          Some _ => twice(t) 
nipkow@200
   464
        | None => (case assoc(abbr,t) of Some _ => tyab_conflict(t)
nipkow@200
   465
                                       | None => ((t,n)::args,(t,[])::coreg,abbr))
clasohm@0
   466
  in if n<0
clasohm@0
   467
     then error("Type constructor cannot have negative number of arguments")
nipkow@200
   468
     else foldl add_type (aca,ts)
clasohm@0
   469
  end;
clasohm@0
   470
nipkow@200
   471
(* check_abbr *)
nipkow@200
   472
nipkow@200
   473
fun check_abbr( (a,(vs,U)), tsig as TySg{abbr,args,...} ) =
nipkow@200
   474
  let val (ndxname,_) = split_list(add_typ_tvars(U,[]))
nipkow@200
   475
      fun err_abbr a = ("ERROR in abbreviation "^ quote a)
nipkow@200
   476
  in if not( (ndxname subset vs) andalso (vs subset ndxname) )
nipkow@200
   477
     then [err_abbr a,("Not the same set of variables on lhs and rhs")]
nipkow@200
   478
     else
nipkow@200
   479
      (case findrep(vs) of
nipkow@200
   480
        (v,_)::_ => [err_abbr a,("Variable "^v^" occurs twice on lhs")]
nipkow@200
   481
        |[] =>
nipkow@200
   482
       (case assoc(args,a) of
nipkow@200
   483
         Some _ => [err_abbr a,("A type with this name exists already")]
nipkow@200
   484
        |None => 
nipkow@200
   485
          (case assoc(abbr,a) of
nipkow@200
   486
            Some _ => [err_abbr a,("An abbreviation with this name exists already")]
nipkow@200
   487
           |None =>
nipkow@200
   488
             (case type_errors (tsig) (U,[]) of
nipkow@200
   489
               []  => []
nipkow@200
   490
              |errs => (err_abbr a) :: errs
nipkow@200
   491
             )
nipkow@200
   492
           )
nipkow@200
   493
         )
nipkow@200
   494
        )
nipkow@200
   495
  end;
nipkow@200
   496
nipkow@200
   497
(* add_abbrs *)
nipkow@200
   498
nipkow@200
   499
fun add_abbr (tsig as TySg{classes,default,subclass,args,coreg,abbr},
nipkow@200
   500
                newabbr) =
nipkow@200
   501
  case check_abbr (newabbr,tsig) of
nipkow@200
   502
     []   => TySg{classes=classes,default=default,subclass=subclass,args=args,
nipkow@200
   503
                  coreg=coreg, abbr = (newabbr) :: abbr}
nipkow@200
   504
   | errs => error(cat_lines errs) ;
nipkow@200
   505
nipkow@200
   506
val add_abbrs = foldl add_abbr;
nipkow@200
   507
nipkow@200
   508
clasohm@0
   509
(* 'extend' takes the above described check- and extend-functions to
clasohm@0
   510
   extend a given type signature with new classes and new type declarations *)
clasohm@0
   511
nipkow@200
   512
fun extend (TySg{classes,default,subclass,args,coreg,abbr},
clasohm@0
   513
            newclasses,newdefault,types,arities) =
clasohm@0
   514
let val (classes',subclass') = extend_classes(classes,subclass,newclasses);
nipkow@200
   515
    val (args',coreg',_) = foldl add_types ((args,coreg,abbr),types);
clasohm@0
   516
    val old_coreg = map #1 coreg;
clasohm@0
   517
    fun is_old(c) = if c mem old_coreg then () else undcl_type_err(c);
clasohm@0
   518
    fun is_new(c) = if c mem old_coreg then twice(c) else ();
clasohm@0
   519
    val coreg'' = foldl (coregular (classes',subclass',args'))
clasohm@0
   520
                        (coreg',min_domain subclass' arities);
clasohm@0
   521
    val coreg''' = close (coreg'',subclass');
clasohm@0
   522
    val default' = if null newdefault then default else newdefault;
clasohm@0
   523
in TySg{classes=classes', default=default',subclass=subclass', args=args',
nipkow@200
   524
	coreg=coreg''',abbr=abbr} end;
clasohm@0
   525
clasohm@0
   526
clasohm@0
   527
(* 'assoc_union' merges two association lists if the contents associated
clasohm@0
   528
   the keys are lists *)
clasohm@0
   529
clasohm@0
   530
fun assoc_union (as1,[]) = as1
clasohm@0
   531
  | assoc_union (as1,(key,l2)::as2) = case assoc (as1,key) of
clasohm@0
   532
        Some(l1) => assoc_union (overwrite(as1,(key,l1 union l2)),as2)
clasohm@0
   533
      | None => assoc_union ((key,l2)::as1,as2);
clasohm@0
   534
clasohm@0
   535
clasohm@0
   536
fun trcl r =
clasohm@0
   537
  let val r' = transitive_closure r
clasohm@0
   538
  in if exists (op mem) r' then error("Cyclic class structure!") else r' end;
clasohm@0
   539
clasohm@0
   540
clasohm@0
   541
(* 'merge_coreg' builds the union of two 'coreg' lists;
clasohm@0
   542
   it only checks the two restriction conditions and inserts afterwards
clasohm@0
   543
   all elements of the second list into the first one *) 
clasohm@0
   544
clasohm@0
   545
fun merge_coreg classes subclass1 =
clasohm@0
   546
  let fun test_ar classes (t,ars1) (coreg1,(s,w)) =
clasohm@0
   547
        (is_unique_decl coreg1 (t,(s,w));
clasohm@0
   548
	 restr2 classes (subclass1,coreg1) (t,(s,w));
clasohm@0
   549
	 overwrite (coreg1,(t,(s,w) ins ars1)));
clasohm@0
   550
clasohm@0
   551
      fun merge_c (coreg1,(c as (t,ars2))) = case assoc (coreg1,t) of
clasohm@0
   552
          Some(ars1) => foldl (test_ar classes (t,ars1)) (coreg1,ars2)
clasohm@0
   553
        | None => c::coreg1
clasohm@0
   554
  in foldl merge_c end;
clasohm@0
   555
clasohm@0
   556
fun merge_args(args,(t,n)) = case assoc(args,t) of
clasohm@0
   557
      Some(m) => if m=n then args else varying_decls(t)
clasohm@0
   558
    | None => (t,n)::args;
clasohm@0
   559
nipkow@200
   560
fun merge_abbrs(abbr1,abbr2) =
nipkow@200
   561
  let val abbru = abbr1 union abbr2
nipkow@200
   562
      val names = map fst abbru
nipkow@200
   563
  in ( case findrep names of
nipkow@200
   564
        []   => abbru
nipkow@200
   565
       |a::_ => error("ERROR in Type.merge: abbreviation "^a^" declared twice") ) end;
nipkow@200
   566
clasohm@0
   567
(* 'merge' takes the above declared functions to merge two type signatures *)
clasohm@0
   568
clasohm@0
   569
fun merge(TySg{classes=classes1,default=default1,subclass=subclass1,args=args1,
nipkow@200
   570
           coreg=coreg1,abbr=abbr1},
clasohm@0
   571
	  TySg{classes=classes2,default=default2,subclass=subclass2,args=args2,
nipkow@200
   572
           coreg=coreg2,abbr=abbr2}) =
clasohm@0
   573
  let val classes' = classes1 union classes2;
clasohm@0
   574
      val subclass' = trcl (assoc_union (subclass1,subclass2));
clasohm@0
   575
      val args' = foldl merge_args (args1,args2)
clasohm@0
   576
      val coreg' = merge_coreg classes' subclass' (coreg1,coreg2);
nipkow@200
   577
      val default' = min_sort subclass' (default1 @ default2);
nipkow@200
   578
      val abbr' = merge_abbrs(abbr1, abbr2);
clasohm@0
   579
  in TySg{classes=classes' , default=default',subclass=subclass', args=args',
nipkow@200
   580
	  coreg=coreg' , abbr = abbr' } 
clasohm@0
   581
  end;
clasohm@0
   582
nipkow@200
   583
clasohm@0
   584
(**** TYPE INFERENCE ****)
clasohm@0
   585
clasohm@0
   586
(*
clasohm@0
   587
clasohm@0
   588
Input:
clasohm@0
   589
- a 'raw' term which contains only dummy types and some explicit type
clasohm@0
   590
  constraints encoded as terms.
clasohm@0
   591
- the expected type of the term.
clasohm@0
   592
clasohm@0
   593
Output:
clasohm@0
   594
- the correctly typed term
clasohm@0
   595
- the substitution needed to unify the actual type of the term with its
clasohm@0
   596
  expected type; only the TVars in the expected type are included.
clasohm@0
   597
clasohm@0
   598
During type inference all TVars in the term have negative index. This keeps
clasohm@0
   599
them apart from normal TVars, which is essential, because at the end the type
clasohm@0
   600
of the term is unified with the expected type, which contains normal TVars.
clasohm@0
   601
clasohm@0
   602
1. Add initial type information to the term (add_types).
clasohm@0
   603
   This freezes (freeze_vars) TVars in explicitly provided types (eg
clasohm@0
   604
   constraints or defaults) by turning them into TFrees.
clasohm@0
   605
2. Carry out type inference, possibly introducing new negative TVars.
clasohm@0
   606
3. Unify actual and expected type.
clasohm@0
   607
4. Turn all (negative) TVars into unique new TFrees (freeze).
clasohm@0
   608
5. Thaw all TVars frozen in step 1 (thaw_vars).
clasohm@0
   609
clasohm@0
   610
*)
clasohm@0
   611
clasohm@0
   612
(*Raised if types are not unifiable*)
clasohm@0
   613
exception TUNIFY;
clasohm@0
   614
clasohm@0
   615
val tyvar_count = ref(~1);
clasohm@0
   616
clasohm@0
   617
fun tyinit() = (tyvar_count := ~1);
clasohm@0
   618
clasohm@0
   619
fun new_tvar_inx() = (tyvar_count := !tyvar_count-1; !tyvar_count)
clasohm@0
   620
clasohm@0
   621
(*
clasohm@0
   622
Generate new TVar.  Index is < ~1 to distinguish it from TVars generated from
clasohm@0
   623
variable names (see id_type).  Name is arbitrary because index is new.
clasohm@0
   624
*)
clasohm@0
   625
clasohm@0
   626
fun gen_tyvar(S) = TVar(("'a", new_tvar_inx()),S);
clasohm@0
   627
clasohm@0
   628
(*Occurs check: type variable occurs in type?*)
clasohm@0
   629
fun occ v tye =
clasohm@0
   630
  let fun occ(Type(_,Ts)) = exists occ Ts
clasohm@0
   631
        | occ(TFree _) = false
clasohm@0
   632
        | occ(TVar(w,_)) = v=w orelse
clasohm@0
   633
                           (case assoc(tye,w) of
clasohm@0
   634
                              None   => false
clasohm@0
   635
                            | Some U => occ U);
clasohm@0
   636
  in occ end;
clasohm@0
   637
clasohm@0
   638
(*Chase variable assignments in tye.  
clasohm@0
   639
  If devar (T,tye) returns a type var then it must be unassigned.*) 
clasohm@0
   640
fun devar (T as TVar(v,_), tye) = (case  assoc(tye,v)  of
clasohm@0
   641
          Some U =>  devar (U,tye)
clasohm@0
   642
        | None   =>  T)
clasohm@0
   643
  | devar (T,tye) = T;
clasohm@0
   644
clasohm@0
   645
clasohm@0
   646
(* 'dom' returns for a type constructor t the list of those domains
clasohm@0
   647
   which deliver a given range class C *)
clasohm@0
   648
clasohm@0
   649
fun dom coreg t C = case assoc2 (coreg, (t,C)) of
clasohm@0
   650
    Some(Ss) => Ss
clasohm@0
   651
  | None => raise TUNIFY;
clasohm@0
   652
clasohm@0
   653
clasohm@0
   654
(* 'Dom' returns the union of all domain lists of 'dom' for a given sort S
clasohm@0
   655
   (i.e. a set of range classes ); the union is carried out elementwise
clasohm@0
   656
   for the seperate sorts in the domains *)
clasohm@0
   657
clasohm@0
   658
fun Dom (subclass,coreg) (t,S) =
clasohm@0
   659
  let val domlist = map (dom coreg t) S;
clasohm@0
   660
  in if null domlist then []
clasohm@0
   661
     else foldl (elementwise_union subclass) (hd domlist,tl domlist)
clasohm@0
   662
  end;
clasohm@0
   663
clasohm@0
   664
clasohm@0
   665
fun W ((T,S),tsig as TySg{subclass,coreg,...},tye) =
clasohm@0
   666
  let fun Wd ((T,S),tye) = W ((devar (T,tye),S),tsig,tye)
clasohm@0
   667
      fun Wk(T as TVar(v,S')) = 
clasohm@0
   668
	      if sortorder subclass (S',S) then tye
clasohm@0
   669
	      else (v,gen_tyvar(union_sort subclass (S',S)))::tye
clasohm@0
   670
	| Wk(T as TFree(v,S')) = if sortorder subclass (S',S) then tye
clasohm@0
   671
				 else raise TUNIFY
clasohm@0
   672
	| Wk(T as Type(f,Ts)) = 
clasohm@0
   673
	   if null S then tye 
clasohm@0
   674
	   else foldr Wd (Ts~~(Dom (subclass,coreg) (f,S)) ,tye)
clasohm@0
   675
  in Wk(T) end;
clasohm@0
   676
clasohm@0
   677
clasohm@0
   678
(* Order-sorted Unification of Types (U)  *)
clasohm@0
   679
clasohm@0
   680
(* Precondition: both types are well-formed w.r.t. type constructor arities *)
nipkow@200
   681
fun unify (tsig as TySg{subclass,coreg,abbr,...}) = 
clasohm@0
   682
  let fun unif ((T,U),tye) =
clasohm@0
   683
        case (devar(T,tye), devar(U,tye)) of
clasohm@0
   684
	  (T as TVar(v,S1), U as TVar(w,S2)) =>
clasohm@0
   685
             if v=w then tye else
clasohm@0
   686
             if sortorder subclass (S1,S2) then (w,T)::tye else
clasohm@0
   687
             if sortorder subclass (S2,S1) then (v,U)::tye
clasohm@0
   688
             else let val nu = gen_tyvar (union_sort subclass (S1,S2))
clasohm@0
   689
                  in (v,nu)::(w,nu)::tye end
clasohm@0
   690
        | (T as TVar(v,S), U) =>
clasohm@0
   691
             if occ v tye U then raise TUNIFY else W ((U,S),tsig,(v,U)::tye)
clasohm@0
   692
        | (U, T as TVar (v,S)) =>
clasohm@0
   693
             if occ v tye U then raise TUNIFY else W ((U,S),tsig,(v,U)::tye)
nipkow@200
   694
        | (T as Type(a,Ts),U as Type(b,Us)) =>
nipkow@200
   695
             if a<>b then
nipkow@200
   696
                 (case (expand1_typ(abbr,a,Ts), expand1_typ(abbr,b,Us)) of
nipkow@200
   697
                             (None,None) => raise TUNIFY
nipkow@200
   698
                           | (None,Some(U)) => unif((T,U),tye)
nipkow@200
   699
                           | (Some(T),None) => unif((T,U),tye)
nipkow@200
   700
                           | (Some(T),Some(U)) => unif((T,U),tye))
nipkow@200
   701
             else foldr unif (Ts~~Us,tye)
clasohm@0
   702
        | (T,U) => if T=U then tye else raise TUNIFY
clasohm@0
   703
  in unif end;
clasohm@0
   704
clasohm@0
   705
clasohm@0
   706
(*Type inference for polymorphic term*)
clasohm@0
   707
fun infer tsig =
clasohm@0
   708
  let fun inf(Ts, Const (_,T), tye) = (T,tye)
clasohm@0
   709
        | inf(Ts, Free  (_,T), tye) = (T,tye)
clasohm@0
   710
        | inf(Ts, Bound i, tye) = ((nth_elem(i,Ts) , tye)
clasohm@0
   711
          handle LIST _=> raise TYPE ("loose bound variable", [], [Bound i]))
clasohm@0
   712
        | inf(Ts, Var (_,T), tye) = (T,tye)
clasohm@0
   713
        | inf(Ts, Abs (_,T,body), tye) = 
clasohm@0
   714
	    let val (U,tye') = inf(T::Ts, body, tye) in  (T-->U, tye')  end
clasohm@0
   715
        | inf(Ts, f$u, tye) =
clasohm@0
   716
	    let val (U,tyeU) = inf(Ts, u, tye);
clasohm@0
   717
	        val (T,tyeT) = inf(Ts, f, tyeU);
clasohm@0
   718
                fun err s =
clasohm@0
   719
                  raise TYPE(s, [inst_typ tyeT T, inst_typ tyeT U], [f$u])
clasohm@0
   720
	    in case T of
clasohm@0
   721
	         Type("fun",[T1,T2]) =>
clasohm@0
   722
		   ( (T2, unify tsig ((T1,U), tyeT))
clasohm@0
   723
                     handle TUNIFY => err"type mismatch in application" )
clasohm@0
   724
	       | TVar _ => 
clasohm@0
   725
                   let val T2 = gen_tyvar([])
clasohm@0
   726
                   in (T2, unify tsig ((T, U-->T2), tyeT))
clasohm@0
   727
                      handle TUNIFY => err"type mismatch in application"
clasohm@0
   728
                   end
clasohm@0
   729
               | _ => err"rator must have function type"
clasohm@0
   730
           end
clasohm@0
   731
  in inf end;
clasohm@0
   732
clasohm@0
   733
fun freeze_vars(Type(a,Ts)) = Type(a,map freeze_vars Ts)
clasohm@0
   734
  | freeze_vars(T as TFree _) = T
clasohm@0
   735
  | freeze_vars(TVar(v,S)) = TFree(Syntax.string_of_vname v, S);
clasohm@0
   736
clasohm@0
   737
(* Attach a type to a constant *)
clasohm@0
   738
fun type_const (a,T) = Const(a, incr_tvar (new_tvar_inx()) T);
clasohm@0
   739
clasohm@0
   740
(*Find type of ident.  If not in table then use ident's name for tyvar
clasohm@0
   741
  to get consistent typing.*)
nipkow@200
   742
fun new_id_type a = TVar(("'"^a,new_tvar_inx()),[]);
clasohm@0
   743
fun type_of_ixn(types,ixn as (a,_)) =
nipkow@200
   744
	case types ixn of Some T => freeze_vars T | None => TVar(("'"^a,~1),[]);
clasohm@0
   745
clasohm@0
   746
fun constrain(term,T) = Const(Syntax.constrainC,T-->T) $ term;
clasohm@0
   747
fun constrainAbs(Abs(a,_,body),T) = Abs(a,T,body);
clasohm@0
   748
clasohm@0
   749
(*
clasohm@0
   750
clasohm@0
   751
Attach types to a term.  Input is a "parse tree" containing dummy types.
clasohm@0
   752
Type constraints are translated and checked for validity wrt tsig.
clasohm@0
   753
TVars in constraints are frozen.
clasohm@0
   754
clasohm@0
   755
The atoms in the resulting term satisfy the following spec:
clasohm@0
   756
clasohm@0
   757
Const(a,T):
clasohm@0
   758
  T is a renamed copy of the generic type of a; renaming decreases index of
clasohm@0
   759
  all TVars by new_tvar_inx(), which is less than ~1. The index of all TVars
clasohm@0
   760
  in the generic type must be 0 for this to work!
clasohm@0
   761
clasohm@0
   762
Free(a,T), Var(ixn,T):
clasohm@0
   763
  T is either the frozen default type of a or TVar(("'"^a,~1),[])
clasohm@0
   764
clasohm@0
   765
Abs(a,T,_):
clasohm@0
   766
  T is either a type constraint or TVar(("'"^a,i),[]), where i is generated
clasohm@0
   767
  by new_tvar_inx(). Thus different abstractions can have the bound variables
clasohm@0
   768
  of the same name but different types.
clasohm@0
   769
clasohm@0
   770
*)
clasohm@0
   771
clasohm@0
   772
fun add_types (tsig, const_tab, types, sorts, string_of_typ) =
clasohm@0
   773
  let val S0 = defaultS tsig;
clasohm@0
   774
      fun defS0 ixn = case sorts ixn of Some S => S | None => S0;
clasohm@0
   775
      fun prepareT(typ) =
clasohm@0
   776
	let val T = Syntax.typ_of_term defS0 typ;
clasohm@0
   777
	    val T' = freeze_vars T
nipkow@200
   778
	in case type_errors (tsig) (T,[]) of
clasohm@0
   779
	     [] => T'
clasohm@0
   780
	   | errs => raise TYPE(cat_lines errs,[T],[])
clasohm@0
   781
	end
clasohm@0
   782
      fun add (Const(a,_)) =
clasohm@0
   783
            (case Symtab.lookup(const_tab, a) of
clasohm@0
   784
               Some T => type_const(a,T)
clasohm@0
   785
             | None => raise TYPE ("No such constant: "^a, [], []))
clasohm@0
   786
        | add (Bound i) = Bound i
clasohm@0
   787
        | add (Free(a,_)) =
clasohm@0
   788
            (case Symtab.lookup(const_tab, a) of
clasohm@0
   789
               Some T => type_const(a,T)
clasohm@0
   790
             | None => Free(a, type_of_ixn(types,(a,~1))))
clasohm@0
   791
        | add (Var(ixn,_)) = Var(ixn, type_of_ixn(types,ixn))
clasohm@0
   792
        | add (Abs(a,_,body)) = Abs(a, new_id_type a, add body)
clasohm@0
   793
        | add ((f as Const(a,_)$t1)$t2) =
clasohm@0
   794
	    if a=Syntax.constrainC then constrain(add t1,prepareT t2) else
clasohm@0
   795
	    if a=Syntax.constrainAbsC then constrainAbs(add t1,prepareT t2)
clasohm@0
   796
	    else add f $ add t2
clasohm@0
   797
        | add (f$t) = add f $ add t
clasohm@0
   798
  in  add  end;
clasohm@0
   799
clasohm@0
   800
clasohm@0
   801
(* Post-Processing *)
clasohm@0
   802
clasohm@0
   803
clasohm@0
   804
(*Instantiation of type variables in terms*)
clasohm@0
   805
fun inst_types tye = map_term_types (inst_typ tye);
clasohm@0
   806
clasohm@0
   807
(*Delete explicit constraints -- occurrences of "_constrain" *)
clasohm@0
   808
fun unconstrain (Abs(a,T,t)) = Abs(a, T, unconstrain t)
clasohm@0
   809
  | unconstrain ((f as Const(a,_)) $ t) =
clasohm@0
   810
      if a=Syntax.constrainC then unconstrain t
clasohm@0
   811
      else unconstrain f $ unconstrain t
clasohm@0
   812
  | unconstrain (f$t) = unconstrain f $ unconstrain t
clasohm@0
   813
  | unconstrain (t) = t;
clasohm@0
   814
clasohm@0
   815
clasohm@0
   816
(* Turn all TVars which satisfy p into new TFrees *)
clasohm@0
   817
fun freeze p t =
clasohm@0
   818
  let val fs = add_term_tfree_names(t,[]);
clasohm@0
   819
      val inxs = filter p (add_term_tvar_ixns(t,[]));
clasohm@0
   820
      val vmap = inxs ~~ variantlist(map #1 inxs, fs);
clasohm@0
   821
      fun free(Type(a,Ts)) = Type(a, map free Ts)
clasohm@0
   822
        | free(T as TVar(v,S)) =
clasohm@0
   823
            (case assoc(vmap,v) of None => T | Some(a) => TFree(a,S))
clasohm@0
   824
        | free(T as TFree _) = T
clasohm@0
   825
  in map_term_types free t end;
clasohm@0
   826
clasohm@0
   827
(* Thaw all TVars that were frozen in freeze_vars *)
clasohm@0
   828
fun thaw_vars(Type(a,Ts)) = Type(a, map thaw_vars Ts)
clasohm@0
   829
  | thaw_vars(T as TFree(a,S)) = (case explode a of
clasohm@0
   830
	  "?"::"'"::vn => let val ((b,i),_) = Syntax.scan_varname vn
clasohm@0
   831
			  in TVar(("'"^b,i),S) end
clasohm@0
   832
	| _ => T)
clasohm@0
   833
  | thaw_vars(T) = T;
clasohm@0
   834
clasohm@0
   835
clasohm@0
   836
fun restrict tye =
clasohm@0
   837
  let fun clean(tye1, ((a,i),T)) =
clasohm@0
   838
	if i < 0 then tye1 else ((a,i),inst_typ tye T) :: tye1
clasohm@0
   839
  in foldl clean ([],tye) end
clasohm@0
   840
clasohm@0
   841
clasohm@0
   842
(*Infer types for term t using tables. Check that t's type and T unify *)
clasohm@0
   843
clasohm@0
   844
fun infer_term (tsig, const_tab, types, sorts, string_of_typ, T, t) =
clasohm@0
   845
  let val u = add_types (tsig, const_tab, types, sorts, string_of_typ) t;
clasohm@0
   846
      val (U,tye) = infer tsig ([], u, []);
clasohm@0
   847
      val uu = unconstrain u;
clasohm@0
   848
      val tye' = unify tsig ((T,U),tye) handle TUNIFY => raise TYPE
clasohm@0
   849
	("Term does not have expected type", [T, U], [inst_types tye uu])
clasohm@0
   850
      val Ttye = restrict tye' (* restriction to TVars in T *)
clasohm@0
   851
      val all = Const("", Type("", map snd Ttye)) $ (inst_types tye' uu)
clasohm@0
   852
        (* all is a dummy term which contains all exported TVars *)
clasohm@0
   853
      val Const(_,Type(_,Ts)) $ u'' =
clasohm@0
   854
            map_term_types thaw_vars (freeze (fn (_,i) => i<0) all)
clasohm@0
   855
        (* turn all internally generated TVars into TFrees
clasohm@0
   856
           and thaw all initially frozen TVars *)
clasohm@0
   857
  in (u'', (map fst Ttye) ~~ Ts) end;
clasohm@0
   858
clasohm@0
   859
fun infer_types args = (tyinit(); infer_term args);
clasohm@0
   860
clasohm@0
   861
clasohm@0
   862
(* Turn TFrees into TVars to allow types & axioms to be written without "?" *)
clasohm@0
   863
fun varifyT(Type(a,Ts)) = Type(a,map varifyT Ts)
clasohm@0
   864
  | varifyT(TFree(a,S)) = TVar((a,0),S)
clasohm@0
   865
  | varifyT(T) = T;
clasohm@0
   866
clasohm@0
   867
(* Turn TFrees except those in fixed into new TVars *)
clasohm@0
   868
fun varify(t,fixed) =
clasohm@0
   869
  let val fs = add_term_tfree_names(t,[]) \\ fixed;
clasohm@0
   870
      val ixns = add_term_tvar_ixns(t,[]);
clasohm@0
   871
      val fmap = fs ~~ variantlist(fs, map #1 ixns)
clasohm@0
   872
      fun thaw(Type(a,Ts)) = Type(a, map thaw Ts)
clasohm@0
   873
        | thaw(T as TVar _) = T
clasohm@0
   874
        | thaw(T as TFree(a,S)) =
clasohm@0
   875
            (case assoc(fmap,a) of None => T | Some b => TVar((b,0),S))
clasohm@0
   876
  in map_term_types thaw t end;
clasohm@0
   877
clasohm@0
   878
clasohm@0
   879
end;