src/Pure/type.ML
author wenzelm
Fri Dec 14 11:54:47 2001 +0100 (2001-12-14)
changeset 12501 36b2ac65e18d
parent 12314 160013745a92
child 12528 b8bc541a4544
permissions -rw-r--r--
varify returns newly introduced variables;
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@2964
     5
Type signatures, unification of types, interface to type inference.
clasohm@0
     6
*)
clasohm@0
     7
clasohm@0
     8
signature TYPE =
wenzelm@2964
     9
sig
wenzelm@7641
    10
  (*TFrees and TVars*)
wenzelm@621
    11
  val no_tvars: typ -> typ
wenzelm@621
    12
  val varifyT: typ -> typ
wenzelm@621
    13
  val unvarifyT: typ -> typ
wenzelm@12501
    14
  val varify: term * string list -> term * (string * indexname) list
wenzelm@10495
    15
  val freeze_thaw_type : typ -> typ * (typ -> typ)
paulson@3411
    16
  val freeze_thaw : term -> term * (term -> term)
wenzelm@2964
    17
wenzelm@2964
    18
  (*type signatures*)
clasohm@0
    19
  type type_sig
nipkow@200
    20
  val rep_tsig: type_sig ->
wenzelm@256
    21
    {classes: class list,
wenzelm@7069
    22
     classrel: Sorts.classrel,
wenzelm@256
    23
     default: sort,
wenzelm@7069
    24
     tycons: int Symtab.table,
wenzelm@7641
    25
     log_types: string list,
wenzelm@7641
    26
     univ_witness: (typ * sort) option,
wenzelm@7069
    27
     abbrs: (string list * typ) Symtab.table,
wenzelm@7069
    28
     arities: Sorts.arities}
wenzelm@7641
    29
  val classes: type_sig -> class list
clasohm@0
    30
  val defaultS: type_sig -> sort
wenzelm@2964
    31
  val logical_types: type_sig -> string list
wenzelm@7641
    32
  val univ_witness: type_sig -> (typ * sort) option
wenzelm@2964
    33
  val subsort: type_sig -> sort * sort -> bool
wenzelm@2964
    34
  val eq_sort: type_sig -> sort * sort -> bool
wenzelm@2964
    35
  val norm_sort: type_sig -> sort -> sort
wenzelm@8899
    36
  val cert_class: type_sig -> class -> class
wenzelm@8899
    37
  val cert_sort: type_sig -> sort -> sort
wenzelm@7641
    38
  val witness_sorts: type_sig -> sort list -> sort list -> (typ * sort) list
wenzelm@2964
    39
  val rem_sorts: typ -> typ
wenzelm@416
    40
  val tsig0: type_sig
wenzelm@621
    41
  val ext_tsig_classes: type_sig -> (class * class list) list -> type_sig
wenzelm@2964
    42
  val ext_tsig_classrel: type_sig -> (class * class) list -> type_sig
wenzelm@422
    43
  val ext_tsig_defsort: type_sig -> sort -> type_sig
wenzelm@582
    44
  val ext_tsig_types: type_sig -> (string * int) list -> type_sig
wenzelm@621
    45
  val ext_tsig_abbrs: type_sig -> (string * string list * typ) list -> type_sig
nipkow@963
    46
  val ext_tsig_arities: type_sig -> (string * sort list * sort)list -> type_sig
wenzelm@256
    47
  val merge_tsigs: type_sig * type_sig -> type_sig
wenzelm@2964
    48
  val typ_errors: type_sig -> typ * string list -> string list
wenzelm@256
    49
  val cert_typ: type_sig -> typ -> typ
wenzelm@9504
    50
  val cert_typ_no_norm: type_sig -> typ -> typ
wenzelm@256
    51
  val norm_typ: type_sig -> typ -> typ
wenzelm@7069
    52
  val norm_term: type_sig -> term -> term
wenzelm@256
    53
  val inst_term_tvars: type_sig * (indexname * typ) list -> term -> term
berghofe@8406
    54
  val inst_typ_tvars: type_sig * (indexname * typ) list -> typ -> typ
wenzelm@2964
    55
wenzelm@2964
    56
  (*type matching*)
wenzelm@2964
    57
  exception TYPE_MATCH
berghofe@8406
    58
  val typ_match: type_sig -> typ Vartab.table * (typ * typ)
berghofe@8406
    59
    -> typ Vartab.table
wenzelm@2964
    60
  val typ_instance: type_sig * typ * typ -> bool
wenzelm@3175
    61
  val of_sort: type_sig -> typ * sort -> bool
wenzelm@2964
    62
wenzelm@2964
    63
  (*type unification*)
wenzelm@2964
    64
  exception TUNIFY
wenzelm@8610
    65
  val unify: type_sig -> int -> typ Vartab.table -> typ * typ -> typ Vartab.table * int
wenzelm@450
    66
  val raw_unify: typ * typ -> bool
clasohm@0
    67
wenzelm@2964
    68
  (*type inference*)
wenzelm@3790
    69
  val get_sort: type_sig -> (indexname -> sort option) -> (sort -> sort)
wenzelm@3790
    70
    -> (indexname * sort) list -> indexname -> sort
wenzelm@2964
    71
  val constrain: term -> typ -> term
wenzelm@4603
    72
  val param: string list -> string * sort -> typ
wenzelm@2979
    73
  val infer_types: (term -> Pretty.T) -> (typ -> Pretty.T)
wenzelm@2979
    74
    -> type_sig -> (string -> typ option) -> (indexname -> typ option)
wenzelm@3790
    75
    -> (indexname -> sort option) -> (string -> string) -> (typ -> typ)
wenzelm@3790
    76
    -> (sort -> sort) -> string list -> bool -> typ list -> term list
wenzelm@2964
    77
    -> term list * (indexname * typ) list
wenzelm@2964
    78
end;
wenzelm@2964
    79
wenzelm@2964
    80
structure Type: TYPE =
clasohm@0
    81
struct
clasohm@0
    82
wenzelm@2964
    83
wenzelm@7641
    84
(*** TFrees and TVars ***)
wenzelm@621
    85
wenzelm@621
    86
fun no_tvars T =
wenzelm@12501
    87
  (case typ_tvars T of [] => T
wenzelm@12501
    88
  | vs => raise TYPE ("Illegal schematic type variable(s): " ^
wenzelm@12501
    89
      commas (map (Syntax.string_of_vname o #1) vs), [T], []));
wenzelm@621
    90
wenzelm@7641
    91
wenzelm@2964
    92
(* varify, unvarify *)
wenzelm@621
    93
wenzelm@2964
    94
val varifyT = map_type_tfree (fn (a, S) => TVar ((a, 0), S));
wenzelm@2964
    95
wenzelm@621
    96
fun unvarifyT (Type (a, Ts)) = Type (a, map unvarifyT Ts)
wenzelm@621
    97
  | unvarifyT (TVar ((a, 0), S)) = TFree (a, S)
wenzelm@621
    98
  | unvarifyT T = T;
wenzelm@621
    99
wenzelm@621
   100
fun varify (t, fixed) =
wenzelm@621
   101
  let
wenzelm@621
   102
    val fs = add_term_tfree_names (t, []) \\ fixed;
wenzelm@621
   103
    val ixns = add_term_tvar_ixns (t, []);
wenzelm@12501
   104
    val fmap = fs ~~ map (rpair 0) (variantlist (fs, map #1 ixns))
wenzelm@2964
   105
    fun thaw (f as (a, S)) =
wenzelm@2964
   106
      (case assoc (fmap, a) of
wenzelm@2964
   107
        None => TFree f
wenzelm@12501
   108
      | Some b => TVar (b, S));
wenzelm@12501
   109
  in (map_term_types (map_type_tfree thaw) t, fmap) end;
wenzelm@2964
   110
wenzelm@2964
   111
wenzelm@7641
   112
(* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
paulson@3411
   113
wenzelm@7641
   114
local
wenzelm@7641
   115
wenzelm@7641
   116
fun new_name (ix, (pairs,used)) =
paulson@3411
   117
      let val v = variant used (string_of_indexname ix)
paulson@3411
   118
      in  ((ix,v)::pairs, v::used)  end;
wenzelm@621
   119
wenzelm@7641
   120
fun freeze_one alist (ix,sort) =
wenzelm@3790
   121
  TFree (the (assoc (alist, ix)), sort)
wenzelm@4142
   122
    handle OPTION =>
wenzelm@3790
   123
      raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
wenzelm@2964
   124
wenzelm@7641
   125
fun thaw_one alist (a,sort) = TVar (the (assoc (alist,a)), sort)
wenzelm@4142
   126
      handle OPTION => TFree(a,sort);
wenzelm@416
   127
wenzelm@10495
   128
in
wenzelm@10495
   129
wenzelm@10495
   130
(*this sort of code could replace unvarifyT*)
wenzelm@7641
   131
fun freeze_thaw_type T =
wenzelm@7641
   132
  let
wenzelm@7641
   133
    val used = add_typ_tfree_names (T, [])
wenzelm@7641
   134
    and tvars = map #1 (add_typ_tvars (T, []));
wenzelm@7641
   135
    val (alist, _) = foldr new_name (tvars, ([], used));
wenzelm@7641
   136
  in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
wenzelm@7641
   137
paulson@3411
   138
fun freeze_thaw t =
wenzelm@7641
   139
  let
wenzelm@7641
   140
    val used = it_term_types add_typ_tfree_names (t, [])
wenzelm@7641
   141
    and tvars = map #1 (it_term_types add_typ_tvars (t, []));
wenzelm@7641
   142
    val (alist, _) = foldr new_name (tvars, ([], used));
wenzelm@7641
   143
  in
wenzelm@7641
   144
    (case alist of
wenzelm@7641
   145
      [] => (t, fn x => x) (*nothing to do!*)
wenzelm@7641
   146
    | _ => (map_term_types (map_type_tvar (freeze_one alist)) t,
wenzelm@7641
   147
      map_term_types (map_type_tfree (thaw_one (map swap alist)))))
wenzelm@7641
   148
  end;
wenzelm@7641
   149
wenzelm@7641
   150
end;
wenzelm@7641
   151
wenzelm@256
   152
wenzelm@256
   153
wenzelm@416
   154
(*** type signatures ***)
wenzelm@256
   155
wenzelm@2964
   156
(* type type_sig *)
wenzelm@2964
   157
wenzelm@256
   158
(*
wenzelm@7641
   159
  classes: list of all declared classes;
wenzelm@7641
   160
  classrel: (see Pure/sorts.ML)
wenzelm@7641
   161
  default: default sort attached to all unconstrained type vars;
wenzelm@7641
   162
  tycons: table of all declared types with the number of their arguments;
wenzelm@7641
   163
  log_types: list of logical type constructors sorted by number of arguments;
wenzelm@7641
   164
  univ_witness: type witnessing non-emptiness of least sort
wenzelm@7641
   165
  abbrs: table of type abbreviations;
wenzelm@7641
   166
  arities: (see Pure/sorts.ML)
clasohm@0
   167
*)
clasohm@0
   168
wenzelm@256
   169
datatype type_sig =
wenzelm@256
   170
  TySg of {
wenzelm@256
   171
    classes: class list,
wenzelm@7069
   172
    classrel: Sorts.classrel,
wenzelm@256
   173
    default: sort,
wenzelm@7069
   174
    tycons: int Symtab.table,
wenzelm@7641
   175
    log_types: string list,
wenzelm@7641
   176
    univ_witness: (typ * sort) option,
wenzelm@7069
   177
    abbrs: (string list * typ) Symtab.table,
wenzelm@7069
   178
    arities: Sorts.arities};
wenzelm@256
   179
nipkow@189
   180
fun rep_tsig (TySg comps) = comps;
clasohm@0
   181
wenzelm@7641
   182
fun classes (TySg {classes = cs, ...}) = cs;
wenzelm@256
   183
fun defaultS (TySg {default, ...}) = default;
wenzelm@7641
   184
fun logical_types (TySg {log_types, ...}) = log_types;
wenzelm@7641
   185
fun univ_witness (TySg {univ_witness, ...}) = univ_witness;
wenzelm@8899
   186
wenzelm@8899
   187
wenzelm@8899
   188
(* error messages *)
wenzelm@8899
   189
wenzelm@8899
   190
fun undeclared_class c = "Undeclared class: " ^ quote c;
wenzelm@8899
   191
fun undeclared_classes cs = "Undeclared class(es): " ^ commas_quote cs;
wenzelm@8899
   192
wenzelm@8899
   193
fun err_undeclared_class s = error (undeclared_class s);
wenzelm@8899
   194
wenzelm@8899
   195
fun err_dup_classes cs =
wenzelm@8899
   196
  error ("Duplicate declaration of class(es): " ^ commas_quote cs);
wenzelm@8899
   197
wenzelm@8899
   198
fun undeclared_type c = "Undeclared type constructor: " ^ quote c;
wenzelm@8899
   199
wenzelm@8899
   200
fun err_neg_args c =
wenzelm@8899
   201
  error ("Negative number of arguments of type constructor: " ^ quote c);
wenzelm@8899
   202
wenzelm@8899
   203
fun err_dup_tycon c =
wenzelm@8899
   204
  error ("Duplicate declaration of type constructor: " ^ quote c);
wenzelm@8899
   205
wenzelm@8899
   206
fun dup_tyabbrs ts =
wenzelm@8899
   207
  "Duplicate declaration of type abbreviation(s): " ^ commas_quote ts;
wenzelm@8899
   208
wenzelm@8899
   209
fun ty_confl c = "Conflicting type constructor and abbreviation: " ^ quote c;
wenzelm@2964
   210
wenzelm@2964
   211
wenzelm@2964
   212
(* sorts *)
wenzelm@2964
   213
wenzelm@2964
   214
fun subsort (TySg {classrel, ...}) = Sorts.sort_le classrel;
wenzelm@2964
   215
fun eq_sort (TySg {classrel, ...}) = Sorts.sort_eq classrel;
wenzelm@2964
   216
fun norm_sort (TySg {classrel, ...}) = Sorts.norm_sort classrel;
wenzelm@2964
   217
wenzelm@8899
   218
fun cert_class (TySg {classes, ...}) c =
wenzelm@8899
   219
  if c mem_string classes then c else raise TYPE (undeclared_class c, [], []);
wenzelm@8899
   220
wenzelm@8899
   221
fun cert_sort tsig S = norm_sort tsig (map (cert_class tsig) S);
wenzelm@8899
   222
wenzelm@7641
   223
fun witness_sorts (tsig as TySg {classrel, arities, log_types, ...}) =
wenzelm@7641
   224
  Sorts.witness_sorts (classrel, arities, log_types);
wenzelm@2964
   225
wenzelm@2964
   226
fun rem_sorts (Type (a, tys)) = Type (a, map rem_sorts tys)
wenzelm@2964
   227
  | rem_sorts (TFree (x, _)) = TFree (x, [])
wenzelm@2964
   228
  | rem_sorts (TVar (xi, _)) = TVar (xi, []);
wenzelm@2964
   229
wenzelm@256
   230
wenzelm@8899
   231
(* FIXME err_undeclared_class! *)
clasohm@0
   232
(* 'leq' checks the partial order on classes according to the
wenzelm@7641
   233
   statements in classrel 'a'
clasohm@0
   234
*)
clasohm@0
   235
wenzelm@7069
   236
fun less a (C, D) = case Symtab.lookup (a, C) of
paulson@2182
   237
     Some ss => D mem_string ss
wenzelm@8899
   238
   | None => err_undeclared_class C;
clasohm@0
   239
wenzelm@256
   240
fun leq a (C, D)  =  C = D orelse less a (C, D);
clasohm@0
   241
clasohm@0
   242
clasohm@0
   243
wenzelm@2964
   244
(* FIXME *)
nipkow@200
   245
(*Instantiation of type variables in types*)
nipkow@200
   246
(*Pre: instantiations obey restrictions! *)
nipkow@200
   247
fun inst_typ tye =
nipkow@949
   248
  let fun inst(var as (v, _)) = case assoc(tye, v) of
nipkow@949
   249
                                  Some U => inst_typ tye U
nipkow@949
   250
                                | None => TVar(var)
nipkow@949
   251
  in map_type_tvar inst end;
clasohm@0
   252
clasohm@0
   253
wenzelm@3175
   254
wenzelm@7641
   255
fun of_sort (TySg {classrel, arities, ...}) = Sorts.of_sort (classrel, arities);
wenzelm@3175
   256
wenzelm@3175
   257
fun check_has_sort (tsig, T, S) =
wenzelm@3175
   258
  if of_sort tsig (T, S) then ()
wenzelm@3790
   259
  else raise TYPE ("Type not of sort " ^ Sorts.str_of_sort S, [T], []);
clasohm@0
   260
clasohm@0
   261
clasohm@0
   262
(*Instantiation of type variables in types *)
wenzelm@256
   263
fun inst_typ_tvars(tsig, tye) =
nipkow@949
   264
  let fun inst(var as (v, S)) = case assoc(tye, v) of
nipkow@949
   265
              Some U => (check_has_sort(tsig, U, S); U)
nipkow@949
   266
            | None => TVar(var)
nipkow@949
   267
  in map_type_tvar inst end;
clasohm@0
   268
clasohm@0
   269
(*Instantiation of type variables in terms *)
paulson@2617
   270
fun inst_term_tvars (_,[]) t = t
paulson@2617
   271
  | inst_term_tvars arg    t = map_term_types (inst_typ_tvars arg) t;
nipkow@200
   272
nipkow@200
   273
wenzelm@7069
   274
(* norm_typ, norm_term *)
nipkow@200
   275
wenzelm@2991
   276
(*expand abbreviations and normalize sorts*)
wenzelm@2991
   277
fun norm_typ (tsig as TySg {abbrs, ...}) ty =
wenzelm@256
   278
  let
wenzelm@621
   279
    val idx = maxidx_of_typ ty + 1;
wenzelm@621
   280
wenzelm@2991
   281
    fun norm (Type (a, Ts)) =
wenzelm@7069
   282
          (case Symtab.lookup (abbrs, a) of
wenzelm@2991
   283
            Some (vs, U) => norm (inst_typ (map (rpair idx) vs ~~ Ts) (incr_tvar idx U))
wenzelm@2991
   284
          | None => Type (a, map norm Ts))
wenzelm@2991
   285
      | norm (TFree (x, S)) = TFree (x, norm_sort tsig S)
wenzelm@2991
   286
      | norm (TVar (xi, S)) = TVar (xi, norm_sort tsig S);
wenzelm@7069
   287
wenzelm@7069
   288
    val ty' = norm ty;
wenzelm@7069
   289
  in if ty = ty' then ty else ty' end;  (*dumb tuning to avoid copying*)
wenzelm@256
   290
wenzelm@7069
   291
fun norm_term tsig t =
wenzelm@7069
   292
  let val t' = map_term_types (norm_typ tsig) t
wenzelm@7069
   293
  in if t = t' then t else t' end;  (*dumb tuning to avoid copying*)
wenzelm@256
   294
wenzelm@256
   295
wenzelm@256
   296
wenzelm@256
   297
(** build type signatures **)
wenzelm@256
   298
wenzelm@7641
   299
fun make_tsig (classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities) =
wenzelm@7641
   300
  TySg {classes = classes, classrel = classrel, default = default, tycons = tycons,
wenzelm@7641
   301
    log_types = log_types, univ_witness = univ_witness, abbrs = abbrs, arities = arities};
wenzelm@7641
   302
wenzelm@7641
   303
fun rebuild_tsig (TySg {classes, classrel, default, tycons, log_types = _, univ_witness = _, abbrs, arities}) =
wenzelm@7641
   304
  let
wenzelm@7641
   305
    fun log_class c = Sorts.class_le classrel (c, logicC);
wenzelm@7641
   306
    fun log_type (t, _) = exists (log_class o #1) (Symtab.lookup_multi (arities, t));
wenzelm@7641
   307
    val ts = filter log_type (Symtab.dest tycons);
wenzelm@416
   308
wenzelm@7641
   309
    val log_types = map #1 (Library.sort (Library.int_ord o pairself #2) ts);
wenzelm@7641
   310
    val univ_witness =
wenzelm@7641
   311
      (case Sorts.witness_sorts (classrel, arities, log_types) [] [classes] of
wenzelm@7641
   312
        [w] => Some w | _ => None);
wenzelm@7641
   313
  in make_tsig (classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities) end;
wenzelm@256
   314
wenzelm@7641
   315
val tsig0 =
wenzelm@7641
   316
  make_tsig ([], Symtab.empty, [], Symtab.empty, [], None, Symtab.empty, Symtab.empty)
wenzelm@7641
   317
  |> rebuild_tsig;
wenzelm@1215
   318
wenzelm@1215
   319
wenzelm@416
   320
(* typ_errors *)
wenzelm@256
   321
wenzelm@416
   322
(*check validity of (not necessarily normal) type; accumulate error messages*)
wenzelm@256
   323
wenzelm@416
   324
fun typ_errors tsig (typ, errors) =
wenzelm@256
   325
  let
wenzelm@7069
   326
    val {classes, tycons, abbrs, ...} = rep_tsig tsig;
wenzelm@416
   327
wenzelm@416
   328
    fun class_err (errs, c) =
paulson@2182
   329
      if c mem_string classes then errs
wenzelm@8899
   330
      else undeclared_class c ins_string errs;
wenzelm@256
   331
wenzelm@256
   332
    val sort_err = foldl class_err;
clasohm@0
   333
wenzelm@7069
   334
    fun typ_errs (errs, Type (c, Us)) =
wenzelm@256
   335
          let
wenzelm@7069
   336
            val errs' = foldl typ_errs (errs, Us);
wenzelm@256
   337
            fun nargs n =
wenzelm@256
   338
              if n = length Us then errs'
paulson@2182
   339
              else ("Wrong number of arguments: " ^ quote c) ins_string errs';
wenzelm@256
   340
          in
wenzelm@7069
   341
            (case Symtab.lookup (tycons, c) of
wenzelm@256
   342
              Some n => nargs n
wenzelm@256
   343
            | None =>
wenzelm@7069
   344
                (case Symtab.lookup (abbrs, c) of
wenzelm@256
   345
                  Some (vs, _) => nargs (length vs)
wenzelm@8899
   346
                | None => undeclared_type c ins_string errs))
wenzelm@256
   347
          end
wenzelm@7069
   348
    | typ_errs (errs, TFree (_, S)) = sort_err (errs, S)
wenzelm@7069
   349
    | typ_errs (errs, TVar ((x, i), S)) =
wenzelm@416
   350
        if i < 0 then
paulson@2182
   351
          ("Negative index for TVar " ^ quote x) ins_string sort_err (errs, S)
wenzelm@416
   352
        else sort_err (errs, S);
wenzelm@7069
   353
  in typ_errs (errors, typ) end;
wenzelm@256
   354
wenzelm@256
   355
wenzelm@8899
   356
(* cert_typ *)           (*exception TYPE*)
wenzelm@256
   357
wenzelm@9504
   358
fun cert_typ_no_norm tsig T =
wenzelm@2964
   359
  (case typ_errors tsig (T, []) of
wenzelm@9504
   360
    [] => T
wenzelm@3790
   361
  | errs => raise TYPE (cat_lines errs, [T], []));
wenzelm@256
   362
wenzelm@9504
   363
fun cert_typ tsig T = norm_typ tsig (cert_typ_no_norm tsig T);
wenzelm@9504
   364
wenzelm@256
   365
wenzelm@256
   366
wenzelm@422
   367
(** merge type signatures **)
wenzelm@256
   368
wenzelm@7641
   369
(* merge classrel *)
clasohm@0
   370
wenzelm@422
   371
fun assoc_union (as1, []) = as1
wenzelm@422
   372
  | assoc_union (as1, (key, l2) :: as2) =
paulson@2182
   373
      (case assoc_string (as1, key) of
wenzelm@7641
   374
        Some l1 => assoc_union (overwrite (as1, (key, l1 union_string l2)), as2)
wenzelm@422
   375
      | None => assoc_union ((key, l2) :: as1, as2));
clasohm@0
   376
wenzelm@2964
   377
fun merge_classrel (classrel1, classrel2) =
wenzelm@7069
   378
  let
wenzelm@7069
   379
    val classrel = transitive_closure (assoc_union (Symtab.dest classrel1, Symtab.dest classrel2))
paulson@2182
   380
  in
wenzelm@2964
   381
    if exists (op mem_string) classrel then
wenzelm@422
   382
      error ("Cyclic class structure!")   (* FIXME improve msg, raise TERM *)
wenzelm@7069
   383
    else Symtab.make classrel
wenzelm@416
   384
  end;
wenzelm@416
   385
wenzelm@416
   386
wenzelm@422
   387
(* coregularity *)
clasohm@0
   388
wenzelm@7641
   389
local
wenzelm@7641
   390
clasohm@0
   391
(* 'is_unique_decl' checks if there exists just one declaration t:(Ss)C *)
clasohm@0
   392
nipkow@963
   393
fun is_unique_decl ars (t,(C,w)) = case assoc (ars, C) of
clasohm@0
   394
      Some(w1) => if w = w1 then () else
wenzelm@256
   395
        error("There are two declarations\n" ^
wenzelm@2964
   396
              Sorts.str_of_arity(t, w, [C]) ^ " and\n" ^
wenzelm@2964
   397
              Sorts.str_of_arity(t, w1, [C]) ^ "\n" ^
clasohm@0
   398
              "with the same result class.")
clasohm@0
   399
    | None => ();
clasohm@0
   400
nipkow@963
   401
(* 'coreg' checks if there are two declarations t:(Ss1)C1 and t:(Ss2)C2
clasohm@0
   402
   such that C1 >= C2 then Ss1 >= Ss2 (elementwise) *)
clasohm@0
   403
nipkow@963
   404
fun coreg_err(t, (C1,w1), (C2,w2)) =
wenzelm@2964
   405
    error("Declarations " ^ Sorts.str_of_arity(t, w1, [C1]) ^ " and "
wenzelm@2964
   406
                          ^ Sorts.str_of_arity(t, w2, [C2]) ^ " are in conflict");
clasohm@0
   407
wenzelm@2964
   408
fun coreg classrel (t, Cw1) =
wenzelm@2964
   409
  let
wenzelm@2964
   410
    fun check1(Cw1 as (C1,w1), Cw2 as (C2,w2)) =
wenzelm@2964
   411
      if leq classrel (C1,C2) then
wenzelm@2964
   412
        if Sorts.sorts_le classrel (w1,w2) then ()
wenzelm@2964
   413
        else coreg_err(t, Cw1, Cw2)
wenzelm@2964
   414
      else ()
wenzelm@2964
   415
    fun check(Cw2) = (check1(Cw1,Cw2); check1(Cw2,Cw1))
nipkow@963
   416
  in seq check end;
clasohm@0
   417
wenzelm@7641
   418
in
wenzelm@7641
   419
wenzelm@2964
   420
fun add_arity classrel ars (tCw as (_,Cw)) =
wenzelm@2964
   421
      (is_unique_decl ars tCw; coreg classrel tCw ars; Cw ins ars);
clasohm@0
   422
wenzelm@7641
   423
end;
clasohm@0
   424
clasohm@0
   425
nipkow@963
   426
(* 'merge_arities' builds the union of two 'arities' lists;
wenzelm@422
   427
   it only checks the two restriction conditions and inserts afterwards
wenzelm@422
   428
   all elements of the second list into the first one *)
wenzelm@422
   429
wenzelm@7641
   430
local
wenzelm@7641
   431
wenzelm@7069
   432
fun merge_arities_aux classrel =
wenzelm@2964
   433
  let fun test_ar t (ars1, sw) = add_arity classrel ars1 (t,sw);
wenzelm@422
   434
nipkow@963
   435
      fun merge_c (arities1, (c as (t, ars2))) = case assoc (arities1, t) of
nipkow@963
   436
          Some(ars1) =>
nipkow@963
   437
            let val ars = foldl (test_ar t) (ars1, ars2)
nipkow@963
   438
            in overwrite (arities1, (t,ars)) end
nipkow@963
   439
        | None => c::arities1
wenzelm@422
   440
  in foldl merge_c end;
wenzelm@422
   441
wenzelm@7641
   442
in
wenzelm@7641
   443
wenzelm@7069
   444
fun merge_arities classrel (a1, a2) =
wenzelm@7069
   445
  Symtab.make (merge_arities_aux classrel (Symtab.dest a1, Symtab.dest a2));
wenzelm@422
   446
wenzelm@7641
   447
end;
wenzelm@7641
   448
wenzelm@7641
   449
wenzelm@7641
   450
(* tycons *)
wenzelm@7641
   451
wenzelm@7641
   452
fun varying_decls t =
wenzelm@7641
   453
  error ("Type constructor " ^ quote t ^ " has varying number of arguments");
wenzelm@7641
   454
wenzelm@7069
   455
fun add_tycons (tycons, tn as (t,n)) =
wenzelm@7069
   456
  (case Symtab.lookup (tycons, t) of
wenzelm@7069
   457
    Some m => if m = n then tycons else varying_decls t
wenzelm@7069
   458
  | None => Symtab.update (tn, tycons));
wenzelm@7069
   459
wenzelm@7641
   460
wenzelm@7641
   461
(* merge_abbrs *)
wenzelm@7641
   462
wenzelm@7069
   463
fun merge_abbrs abbrs =
wenzelm@7069
   464
  Symtab.merge (op =) abbrs handle Symtab.DUPS dups => raise TERM (dup_tyabbrs dups, []);
wenzelm@422
   465
wenzelm@422
   466
wenzelm@7641
   467
(* merge_tsigs *)
wenzelm@422
   468
wenzelm@7641
   469
fun merge_tsigs
wenzelm@7641
   470
 (TySg {classes = classes1, default = default1, classrel = classrel1, tycons = tycons1,
wenzelm@7641
   471
    log_types = _, univ_witness = _, arities = arities1, abbrs = abbrs1},
wenzelm@7641
   472
  TySg {classes = classes2, default = default2, classrel = classrel2, tycons = tycons2,
wenzelm@7641
   473
    log_types = _, univ_witness = _, arities = arities2, abbrs = abbrs2}) =
wenzelm@7641
   474
  let
wenzelm@7641
   475
    val classes' = classes1 union_string classes2;
wenzelm@7641
   476
    val classrel' = merge_classrel (classrel1, classrel2);
wenzelm@7641
   477
    val arities' = merge_arities classrel' (arities1, arities2);
wenzelm@7641
   478
    val tycons' = foldl add_tycons (tycons1, Symtab.dest tycons2);
wenzelm@7641
   479
    val default' = Sorts.norm_sort classrel' (default1 @ default2);
wenzelm@7641
   480
    val abbrs' = merge_abbrs (abbrs1, abbrs2);
wenzelm@7641
   481
  in
wenzelm@7641
   482
    make_tsig (classes', classrel', default', tycons', [], None, abbrs', arities')
wenzelm@7641
   483
    |> rebuild_tsig
wenzelm@7641
   484
  end;
wenzelm@422
   485
wenzelm@422
   486
wenzelm@422
   487
wenzelm@422
   488
(*** extend type signatures ***)
wenzelm@422
   489
wenzelm@2964
   490
(** add classes and classrel relations **)
wenzelm@422
   491
wenzelm@422
   492
fun add_classes classes cs =
paulson@2182
   493
  (case cs inter_string classes of
wenzelm@422
   494
    [] => cs @ classes
wenzelm@422
   495
  | dups => err_dup_classes cs);
wenzelm@422
   496
wenzelm@422
   497
wenzelm@2964
   498
(*'add_classrel' adds a tuple consisting of a new class (the new class has
wenzelm@422
   499
  already been inserted into the 'classes' list) and its superclasses (they
wenzelm@2964
   500
  must be declared in 'classes' too) to the 'classrel' list of the given type
wenzelm@422
   501
  signature; furthermore all inherited superclasses according to the
wenzelm@422
   502
  superclasses brought with are inserted and there is a check that there are
wenzelm@422
   503
  no cycles (i.e. C <= D <= C, with C <> D);*)
wenzelm@422
   504
wenzelm@2964
   505
fun add_classrel classes (classrel, (s, ges)) =
wenzelm@621
   506
  let
wenzelm@2964
   507
    fun upd (classrel, s') =
paulson@2182
   508
      if s' mem_string classes then
wenzelm@7069
   509
        let val ges' = the (Symtab.lookup (classrel, s))
wenzelm@7069
   510
        in case Symtab.lookup (classrel, s') of
paulson@2182
   511
             Some sups => if s mem_string sups
wenzelm@422
   512
                           then error(" Cycle :" ^ s^" <= "^ s'^" <= "^ s )
wenzelm@7069
   513
                           else Symtab.update ((s, sups union_string ges'), classrel)
wenzelm@2964
   514
           | None => classrel
wenzelm@621
   515
        end
wenzelm@8899
   516
      else err_undeclared_class s'
wenzelm@7069
   517
  in foldl upd (Symtab.update ((s, ges), classrel), ges) end;
wenzelm@422
   518
wenzelm@422
   519
wenzelm@422
   520
(* 'extend_classes' inserts all new classes into the corresponding
wenzelm@2964
   521
   lists ('classes', 'classrel') if possible *)
wenzelm@422
   522
wenzelm@2964
   523
fun extend_classes (classes, classrel, new_classes) =
wenzelm@621
   524
  let
wenzelm@621
   525
    val classes' = add_classes classes (map fst new_classes);
wenzelm@2964
   526
    val classrel' = foldl (add_classrel classes') (classrel, new_classes);
wenzelm@2964
   527
  in (classes', classrel') end;
wenzelm@422
   528
wenzelm@422
   529
wenzelm@621
   530
(* ext_tsig_classes *)
wenzelm@621
   531
wenzelm@621
   532
fun ext_tsig_classes tsig new_classes =
wenzelm@621
   533
  let
wenzelm@7641
   534
    val TySg {classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities} = tsig;
wenzelm@11022
   535
    val (classes', classrel') = extend_classes (classes,classrel, new_classes);
wenzelm@12222
   536
  in
wenzelm@12222
   537
    make_tsig (classes', classrel', default, tycons, log_types, univ_witness, abbrs, arities)
wenzelm@12222
   538
    |> rebuild_tsig
wenzelm@12222
   539
  end;
wenzelm@621
   540
wenzelm@621
   541
wenzelm@2964
   542
(* ext_tsig_classrel *)
wenzelm@422
   543
wenzelm@2964
   544
fun ext_tsig_classrel tsig pairs =
wenzelm@422
   545
  let
wenzelm@7641
   546
    val TySg {classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities} = tsig;
wenzelm@11022
   547
    val cert = cert_class tsig;
wenzelm@422
   548
wenzelm@422
   549
    (* FIXME clean! *)
wenzelm@2964
   550
    val classrel' =
wenzelm@11022
   551
      merge_classrel (classrel, Symtab.make (map (fn (c1, c2) => (cert c1, [cert c2])) pairs));
wenzelm@422
   552
  in
wenzelm@7641
   553
    make_tsig (classes, classrel', default, tycons, log_types, univ_witness, abbrs, arities)
wenzelm@7641
   554
    |> rebuild_tsig
wenzelm@422
   555
  end;
wenzelm@422
   556
wenzelm@422
   557
wenzelm@422
   558
(* ext_tsig_defsort *)
wenzelm@422
   559
wenzelm@7641
   560
fun ext_tsig_defsort
wenzelm@7641
   561
    (TySg {classes, classrel, default = _, tycons, log_types, univ_witness, abbrs, arities, ...}) default =
wenzelm@7641
   562
  make_tsig (classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities);
wenzelm@422
   563
wenzelm@422
   564
wenzelm@422
   565
wenzelm@621
   566
(** add types **)
wenzelm@582
   567
wenzelm@7641
   568
fun ext_tsig_types (TySg {classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities}) ts =
wenzelm@582
   569
  let
wenzelm@582
   570
    fun check_type (c, n) =
wenzelm@582
   571
      if n < 0 then err_neg_args c
wenzelm@7069
   572
      else if is_some (Symtab.lookup (tycons, c)) then err_dup_tycon c
wenzelm@7069
   573
      else if is_some (Symtab.lookup (abbrs, c)) then error (ty_confl c)
wenzelm@582
   574
      else ();
wenzelm@7641
   575
    val _ = seq check_type ts;
wenzelm@7641
   576
    val tycons' = Symtab.extend (tycons, ts);
wenzelm@7641
   577
    val arities' = Symtab.extend (arities, map (rpair [] o #1) ts);
wenzelm@7641
   578
  in make_tsig (classes, classrel, default, tycons', log_types, univ_witness, abbrs, arities') end;
wenzelm@582
   579
wenzelm@582
   580
wenzelm@582
   581
wenzelm@582
   582
(** add type abbreviations **)
wenzelm@582
   583
wenzelm@582
   584
fun abbr_errors tsig (a, (lhs_vs, rhs)) =
wenzelm@582
   585
  let
nipkow@963
   586
    val TySg {tycons, abbrs, ...} = tsig;
wenzelm@621
   587
    val rhs_vs = map (#1 o #1) (typ_tvars rhs);
wenzelm@582
   588
wenzelm@582
   589
    val dup_lhs_vars =
wenzelm@582
   590
      (case duplicates lhs_vs of
wenzelm@582
   591
        [] => []
wenzelm@621
   592
      | vs => ["Duplicate variables on lhs: " ^ commas_quote vs]);
wenzelm@582
   593
wenzelm@582
   594
    val extra_rhs_vars =
wenzelm@582
   595
      (case gen_rems (op =) (rhs_vs, lhs_vs) of
wenzelm@582
   596
        [] => []
wenzelm@621
   597
      | vs => ["Extra variables on rhs: " ^ commas_quote vs]);
wenzelm@582
   598
wenzelm@582
   599
    val tycon_confl =
wenzelm@7069
   600
      if is_none (Symtab.lookup (tycons, a)) then []
wenzelm@582
   601
      else [ty_confl a];
wenzelm@582
   602
wenzelm@582
   603
    val dup_abbr =
wenzelm@7069
   604
      if is_none (Symtab.lookup (abbrs, a)) then []
wenzelm@582
   605
      else ["Duplicate declaration of abbreviation"];
wenzelm@582
   606
  in
wenzelm@582
   607
    dup_lhs_vars @ extra_rhs_vars @ tycon_confl @ dup_abbr @
wenzelm@582
   608
      typ_errors tsig (rhs, [])
wenzelm@582
   609
  end;
wenzelm@582
   610
wenzelm@621
   611
fun prep_abbr tsig (a, vs, raw_rhs) =
wenzelm@621
   612
  let
wenzelm@4974
   613
    fun err msgs = (seq error_msg msgs;
wenzelm@621
   614
      error ("The error(s) above occurred in type abbreviation " ^ quote a));
wenzelm@621
   615
wenzelm@621
   616
    val rhs = rem_sorts (varifyT (no_tvars raw_rhs))
wenzelm@621
   617
      handle TYPE (msg, _, _) => err [msg];
wenzelm@621
   618
    val abbr = (a, (vs, rhs));
wenzelm@621
   619
  in
wenzelm@582
   620
    (case abbr_errors tsig abbr of
wenzelm@621
   621
      [] => abbr
wenzelm@621
   622
    | msgs => err msgs)
wenzelm@582
   623
  end;
wenzelm@582
   624
wenzelm@7641
   625
fun add_abbr
wenzelm@7641
   626
    (tsig as TySg {classes, classrel, default, tycons, log_types, univ_witness, arities, abbrs}, abbr) =
wenzelm@7641
   627
  make_tsig (classes, classrel, default, tycons, log_types, univ_witness,
wenzelm@7641
   628
    Symtab.update (prep_abbr tsig abbr, abbrs), arities);
wenzelm@621
   629
wenzelm@621
   630
fun ext_tsig_abbrs tsig raw_abbrs = foldl add_abbr (tsig, raw_abbrs);
wenzelm@582
   631
wenzelm@582
   632
wenzelm@582
   633
wenzelm@422
   634
(** add arities **)
wenzelm@422
   635
clasohm@0
   636
(* 'coregular' checks
nipkow@963
   637
   - the two restrictions 'is_unique_decl' and 'coreg'
wenzelm@256
   638
   - if the classes in the new type declarations are known in the
clasohm@0
   639
     given type signature
clasohm@0
   640
   - if one type constructor has always the same number of arguments;
wenzelm@256
   641
   if one type declaration has passed all checks it is inserted into
nipkow@963
   642
   the 'arities' association list of the given type signatrure  *)
clasohm@0
   643
wenzelm@2964
   644
fun coregular (classes, classrel, tycons) =
wenzelm@8899
   645
  let fun ex C = if C mem_string classes then () else err_undeclared_class(C);
clasohm@0
   646
wenzelm@7069
   647
      fun addar(arities, (t, (w, C))) = case Symtab.lookup (tycons, t) of
clasohm@0
   648
            Some(n) => if n <> length w then varying_decls(t) else
nipkow@963
   649
                     ((seq o seq) ex w; ex C;
wenzelm@7069
   650
                      let val ars = the (Symtab.lookup (arities, t))
wenzelm@2964
   651
                          val ars' = add_arity classrel ars (t,(C,w))
wenzelm@7069
   652
                      in Symtab.update ((t,ars'), arities) end)
wenzelm@8899
   653
          | None => error (undeclared_type t);
clasohm@0
   654
nipkow@963
   655
  in addar end;
clasohm@0
   656
clasohm@0
   657
nipkow@963
   658
(* 'close' extends the 'arities' association list after all new type
clasohm@0
   659
   declarations have been inserted successfully:
clasohm@0
   660
   for every declaration t:(Ss)C , for all classses D with C <= D:
clasohm@0
   661
      if there is no declaration t:(Ss')C' with C < C' and C' <= D
nipkow@963
   662
      then insert the declaration t:(Ss)D into 'arities'
clasohm@0
   663
   this means, if there exists a declaration t:(Ss)C and there is
clasohm@0
   664
   no declaration t:(Ss')D with C <=D then the declaration holds
wenzelm@256
   665
   for all range classes more general than C *)
wenzelm@256
   666
wenzelm@2964
   667
fun close classrel arities =
wenzelm@7069
   668
  let fun check sl (l, (s, dom)) = case Symtab.lookup (classrel, s) of
wenzelm@621
   669
          Some sups =>
wenzelm@256
   670
            let fun close_sup (l, sup) =
wenzelm@2964
   671
                  if exists (fn s'' => less classrel (s, s'') andalso
wenzelm@2964
   672
                                       leq classrel (s'', sup)) sl
clasohm@0
   673
                  then l
wenzelm@256
   674
                  else (sup, dom)::l
wenzelm@256
   675
            in foldl close_sup (l, sups) end
clasohm@0
   676
        | None => l;
wenzelm@256
   677
      fun ext (s, l) = (s, foldl (check (map #1 l)) (l, l));
nipkow@963
   678
  in map ext arities end;
clasohm@0
   679
wenzelm@422
   680
wenzelm@621
   681
(* ext_tsig_arities *)
wenzelm@256
   682
wenzelm@2964
   683
fun norm_domain classrel =
wenzelm@2964
   684
  let fun one_min (f, (doms, ran)) = (f, (map (Sorts.norm_sort classrel) doms, ran))
wenzelm@2964
   685
  in map one_min end;
wenzelm@2964
   686
wenzelm@621
   687
fun ext_tsig_arities tsig sarities =
wenzelm@416
   688
  let
wenzelm@7641
   689
    val TySg {classes, classrel, default, tycons, log_types, univ_witness, arities, abbrs} = tsig;
nipkow@963
   690
    val arities1 =
wenzelm@7641
   691
      flat (map (fn (t, ss, cs) => map (fn c => (t, (ss, c))) cs) sarities);
wenzelm@7641
   692
    val arities2 =
wenzelm@7641
   693
      foldl (coregular (classes, classrel, tycons)) (arities, norm_domain classrel arities1)
wenzelm@7069
   694
      |> Symtab.dest |> close classrel |> Symtab.make;
wenzelm@416
   695
  in
wenzelm@7641
   696
    make_tsig (classes, classrel, default, tycons, log_types, univ_witness, abbrs, arities2)
wenzelm@7641
   697
    |> rebuild_tsig
wenzelm@416
   698
  end;
clasohm@0
   699
clasohm@0
   700
wenzelm@416
   701
wenzelm@2964
   702
(*** type unification and friends ***)
clasohm@0
   703
wenzelm@2964
   704
(** matching **)
clasohm@0
   705
wenzelm@2964
   706
exception TYPE_MATCH;
clasohm@0
   707
wenzelm@2964
   708
fun typ_match tsig =
wenzelm@2964
   709
  let
wenzelm@2964
   710
    fun match (subs, (TVar (v, S), T)) =
berghofe@8406
   711
          (case Vartab.lookup (subs, v) of
berghofe@8406
   712
            None => (Vartab.update_new ((v, (check_has_sort (tsig, T, S); T)), subs)
wenzelm@2964
   713
              handle TYPE _ => raise TYPE_MATCH)
wenzelm@2964
   714
          | Some U => if U = T then subs else raise TYPE_MATCH)
wenzelm@2964
   715
      | match (subs, (Type (a, Ts), Type (b, Us))) =
wenzelm@2964
   716
          if a <> b then raise TYPE_MATCH
wenzelm@2964
   717
          else foldl match (subs, Ts ~~ Us)
wenzelm@2964
   718
      | match (subs, (TFree x, TFree y)) =
wenzelm@2964
   719
          if x = y then subs else raise TYPE_MATCH
wenzelm@2964
   720
      | match _ = raise TYPE_MATCH;
wenzelm@2964
   721
  in match end;
clasohm@0
   722
wenzelm@2964
   723
fun typ_instance (tsig, T, U) =
berghofe@8406
   724
  (typ_match tsig (Vartab.empty, (U, T)); true) handle TYPE_MATCH => false;
wenzelm@2964
   725
clasohm@0
   726
wenzelm@2964
   727
wenzelm@2964
   728
(** unification **)
wenzelm@2964
   729
clasohm@0
   730
exception TUNIFY;
clasohm@0
   731
clasohm@0
   732
wenzelm@2964
   733
(* occurs check *)
clasohm@0
   734
wenzelm@2964
   735
fun occurs v tye =
wenzelm@2964
   736
  let
wenzelm@2964
   737
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   738
      | occ (TFree _) = false
wenzelm@2964
   739
      | occ (TVar (w, _)) =
wenzelm@2964
   740
          eq_ix (v, w) orelse
berghofe@8406
   741
            (case Vartab.lookup (tye, w) of
wenzelm@2964
   742
              None => false
wenzelm@2964
   743
            | Some U => occ U);
clasohm@0
   744
  in occ end;
clasohm@0
   745
wenzelm@2964
   746
wenzelm@2964
   747
(* chase variable assignments *)
wenzelm@2964
   748
wenzelm@2964
   749
(*if devar returns a type var then it must be unassigned*)
wenzelm@2964
   750
fun devar (T as TVar (v, _), tye) =
berghofe@8406
   751
      (case  Vartab.lookup (tye, v) of
wenzelm@2964
   752
        Some U => devar (U, tye)
wenzelm@2964
   753
      | None => T)
wenzelm@256
   754
  | devar (T, tye) = T;
clasohm@0
   755
berghofe@1627
   756
wenzelm@2964
   757
(* add_env *)
clasohm@0
   758
wenzelm@2964
   759
(*avoids chains 'a |-> 'b |-> 'c ...*)
berghofe@8406
   760
fun add_env (vT as (v, T), tab) = Vartab.update_new (vT, Vartab.map
berghofe@8406
   761
  (fn (U as (TVar (w, S))) => if eq_ix (v, w) then T else U | U => U) tab);
clasohm@0
   762
wenzelm@2964
   763
(* unify *)
wenzelm@2964
   764
wenzelm@2964
   765
fun unify (tsig as TySg {classrel, arities, ...}) maxidx tyenv TU =
wenzelm@2964
   766
  let
wenzelm@2964
   767
    val tyvar_count = ref maxidx;
wenzelm@2964
   768
    fun gen_tyvar S = TVar (("'a", inc tyvar_count), S);
wenzelm@2964
   769
wenzelm@2964
   770
    fun mg_domain a S =
wenzelm@7641
   771
      Sorts.mg_domain (classrel, arities) a S handle Sorts.DOMAIN _ => raise TUNIFY;
wenzelm@2964
   772
wenzelm@2964
   773
    fun meet ((_, []), tye) = tye
wenzelm@2964
   774
      | meet ((TVar (xi, S'), S), tye) =
wenzelm@2964
   775
          if Sorts.sort_le classrel (S', S) then tye
wenzelm@2964
   776
          else add_env ((xi, gen_tyvar (Sorts.inter_sort classrel (S', S))), tye)
wenzelm@2964
   777
      | meet ((TFree (_, S'), S), tye) =
wenzelm@2964
   778
          if Sorts.sort_le classrel (S', S) then tye
wenzelm@2964
   779
          else raise TUNIFY
wenzelm@2964
   780
      | meet ((Type (a, Ts), S), tye) = meets ((Ts, mg_domain a S), tye)
wenzelm@2964
   781
    and meets (([], []), tye) = tye
wenzelm@2964
   782
      | meets ((T :: Ts, S :: Ss), tye) =
wenzelm@2964
   783
          meets ((Ts, Ss), meet ((devar (T, tye), S), tye))
wenzelm@2964
   784
      | meets _ = sys_error "meets";
wenzelm@2964
   785
wenzelm@2964
   786
    fun unif ((ty1, ty2), tye) =
wenzelm@2964
   787
      (case (devar (ty1, tye), devar (ty2, tye)) of
wenzelm@2964
   788
        (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@2964
   789
          if eq_ix (v, w) then tye
wenzelm@2964
   790
          else if Sorts.sort_le classrel (S1, S2) then add_env ((w, T), tye)
wenzelm@2964
   791
          else if Sorts.sort_le classrel (S2, S1) then add_env ((v, U), tye)
wenzelm@2964
   792
          else
wenzelm@2964
   793
            let val S = gen_tyvar (Sorts.inter_sort classrel (S1, S2)) in
wenzelm@2964
   794
              add_env ((v, S), add_env ((w, S), tye))
wenzelm@2964
   795
            end
wenzelm@2964
   796
      | (TVar (v, S), T) =>
wenzelm@2964
   797
          if occurs v tye T then raise TUNIFY
wenzelm@2964
   798
          else meet ((T, S), add_env ((v, T), tye))
wenzelm@2964
   799
      | (T, TVar (v, S)) =>
wenzelm@2964
   800
          if occurs v tye T then raise TUNIFY
wenzelm@2964
   801
          else meet ((T, S), add_env ((v, T), tye))
wenzelm@2964
   802
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   803
          if a <> b then raise TUNIFY
wenzelm@2964
   804
          else foldr unif (Ts ~~ Us, tye)
wenzelm@2964
   805
      | (T, U) => if T = U then tye else raise TUNIFY);
wenzelm@2964
   806
  in
wenzelm@2964
   807
    (unif (TU, tyenv), ! tyvar_count)
wenzelm@2964
   808
  end;
clasohm@0
   809
clasohm@0
   810
wenzelm@2964
   811
(* raw_unify *)
clasohm@0
   812
wenzelm@2964
   813
(*purely structural unification -- ignores sorts*)
wenzelm@450
   814
fun raw_unify (ty1, ty2) =
berghofe@8406
   815
  (unify tsig0 0 Vartab.empty (rem_sorts ty1, rem_sorts ty2); true)
wenzelm@450
   816
    handle TUNIFY => false;
wenzelm@450
   817
wenzelm@450
   818
clasohm@0
   819
wenzelm@2964
   820
(** type inference **)
nipkow@1435
   821
wenzelm@3790
   822
(* sort constraints *)
wenzelm@3790
   823
wenzelm@3790
   824
fun get_sort tsig def_sort map_sort raw_env =
wenzelm@3790
   825
  let
wenzelm@3790
   826
    fun eq ((xi, S), (xi', S')) =
wenzelm@3790
   827
      xi = xi' andalso eq_sort tsig (S, S');
wenzelm@3790
   828
wenzelm@3790
   829
    val env = gen_distinct eq (map (apsnd map_sort) raw_env);
wenzelm@3790
   830
    val _ =
wenzelm@3790
   831
      (case gen_duplicates eq_fst env of
wenzelm@3790
   832
        [] => ()
wenzelm@3790
   833
      | dups => error ("Inconsistent sort constraints for type variable(s) " ^
wenzelm@3790
   834
          commas (map (quote o Syntax.string_of_vname' o fst) dups)));
wenzelm@2587
   835
wenzelm@3790
   836
    fun get xi =
wenzelm@3790
   837
      (case (assoc (env, xi), def_sort xi) of
wenzelm@3790
   838
        (None, None) => defaultS tsig
wenzelm@3790
   839
      | (None, Some S) => S
wenzelm@3790
   840
      | (Some S, None) => S
wenzelm@3790
   841
      | (Some S, Some S') =>
wenzelm@3804
   842
          if eq_sort tsig (S, S') then S'
wenzelm@3790
   843
          else error ("Sort constraint inconsistent with default for type variable " ^
wenzelm@3790
   844
            quote (Syntax.string_of_vname' xi)));
wenzelm@3790
   845
  in get end;
wenzelm@3790
   846
wenzelm@3790
   847
wenzelm@3790
   848
(* type constraints *)
wenzelm@2587
   849
wenzelm@2964
   850
fun constrain t T =
wenzelm@2964
   851
  if T = dummyT then t
wenzelm@2964
   852
  else Const ("_type_constraint_", T) $ t;
clasohm@0
   853
clasohm@0
   854
wenzelm@4603
   855
(* user parameters *)
wenzelm@4603
   856
wenzelm@4603
   857
fun is_param (x, _) = size x > 0 andalso ord x = ord "?";
wenzelm@5345
   858
fun param used (x, S) = TVar ((variant used ("?" ^ x), 0), S);
wenzelm@4603
   859
wenzelm@4603
   860
wenzelm@2964
   861
(* decode_types *)
clasohm@0
   862
wenzelm@3804
   863
(*transform parse tree into raw term*)
wenzelm@3790
   864
fun decode_types tsig is_const def_type def_sort map_const map_type map_sort tm =
wenzelm@2964
   865
  let
wenzelm@2964
   866
    fun get_type xi = if_none (def_type xi) dummyT;
wenzelm@5080
   867
    fun is_free x = is_some (def_type (x, ~1));
wenzelm@3790
   868
    val raw_env = Syntax.raw_term_sorts tm;
wenzelm@3790
   869
    val sort_of = get_sort tsig def_sort map_sort raw_env;
wenzelm@2964
   870
wenzelm@3804
   871
    val certT = cert_typ tsig o map_type;
wenzelm@12314
   872
    fun decodeT t = certT (Syntax.typ_of_term sort_of map_sort t);
clasohm@0
   873
wenzelm@2964
   874
    fun decode (Const ("_constrain", _) $ t $ typ) =
wenzelm@2964
   875
          constrain (decode t) (decodeT typ)
wenzelm@3804
   876
      | decode (Const ("_constrainAbs", _) $ (Abs (x, T, t)) $ typ) =
wenzelm@2964
   877
          if T = dummyT then Abs (x, decodeT typ, decode t)
wenzelm@3804
   878
          else constrain (Abs (x, certT T, decode t)) (decodeT typ --> dummyT)
wenzelm@3804
   879
      | decode (Abs (x, T, t)) = Abs (x, certT T, decode t)
wenzelm@2964
   880
      | decode (t $ u) = decode t $ decode u
wenzelm@3804
   881
      | decode (Free (x, T)) =
wenzelm@3790
   882
          let val c = map_const x in
wenzelm@8721
   883
            if not (is_free x) andalso (is_const c orelse NameSpace.is_qualified c) then
wenzelm@5080
   884
              Const (c, certT T)
wenzelm@3790
   885
            else if T = dummyT then Free (x, get_type (x, ~1))
wenzelm@3804
   886
            else constrain (Free (x, certT T)) (get_type (x, ~1))
wenzelm@3790
   887
          end
wenzelm@3804
   888
      | decode (Var (xi, T)) =
wenzelm@2964
   889
          if T = dummyT then Var (xi, get_type xi)
wenzelm@3804
   890
          else constrain (Var (xi, certT T)) (get_type xi)
wenzelm@2964
   891
      | decode (t as Bound _) = t
wenzelm@3804
   892
      | decode (Const (c, T)) = Const (map_const c, certT T);
wenzelm@8610
   893
  in decode tm end;
clasohm@0
   894
clasohm@0
   895
wenzelm@2964
   896
(* infer_types *)
nipkow@949
   897
nipkow@949
   898
(*
wenzelm@2964
   899
  Given [T1,...,Tn] and [t1,...,tn], ensure that the type of ti
wenzelm@2964
   900
  unifies with Ti (for i=1,...,n).
wenzelm@2964
   901
wenzelm@2964
   902
  tsig: type signature
wenzelm@3790
   903
  const_type: name mapping and signature lookup
wenzelm@2964
   904
  def_type: partial map from indexnames to types (constrains Frees, Vars)
wenzelm@2964
   905
  def_sort: partial map from indexnames to sorts (constrains TFrees, TVars)
wenzelm@2964
   906
  used: list of already used type variables
wenzelm@2964
   907
  freeze: if true then generated parameters are turned into TFrees, else TVars
nipkow@949
   908
*)
clasohm@0
   909
wenzelm@3790
   910
fun infer_types prt prT tsig const_type def_type def_sort
wenzelm@3790
   911
    map_const map_type map_sort used freeze pat_Ts raw_ts =
wenzelm@565
   912
  let
wenzelm@2964
   913
    val TySg {classrel, arities, ...} = tsig;
wenzelm@2964
   914
    val pat_Ts' = map (cert_typ tsig) pat_Ts;
wenzelm@3790
   915
    val is_const = is_some o const_type;
wenzelm@2964
   916
    val raw_ts' =
wenzelm@3790
   917
      map (decode_types tsig is_const def_type def_sort map_const map_type map_sort) raw_ts;
wenzelm@2964
   918
    val (ts, Ts, unifier) =
wenzelm@2979
   919
      TypeInfer.infer_types prt prT const_type classrel arities used freeze
wenzelm@4603
   920
        is_param raw_ts' pat_Ts';
wenzelm@7641
   921
  in (ts, unifier) end;
clasohm@0
   922
wenzelm@3790
   923
clasohm@0
   924
end;