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