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