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