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