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