src/Pure/type.ML
author wenzelm
Tue Mar 21 12:18:15 2006 +0100 (2006-03-21 ago)
changeset 19305 5c16895d548b
parent 19250 932a50e2332f
child 19464 d13309e30aba
permissions -rw-r--r--
avoid polymorphic equality;
wenzelm@256
     1
(*  Title:      Pure/type.ML
clasohm@0
     2
    ID:         $Id$
wenzelm@14790
     3
    Author:     Tobias Nipkow, Lawrence C Paulson, and Markus Wenzel
clasohm@0
     4
wenzelm@14790
     5
Type signatures and certified types, special treatment of type vars,
wenzelm@14790
     6
matching and unification of types, extend and merge type signatures.
clasohm@0
     7
*)
clasohm@0
     8
clasohm@0
     9
signature TYPE =
wenzelm@2964
    10
sig
wenzelm@14790
    11
  (*type signatures and certified types*)
wenzelm@14790
    12
  datatype decl =
wenzelm@14790
    13
    LogicalType of int |
wenzelm@14989
    14
    Abbreviation of string list * typ * bool |
wenzelm@14790
    15
    Nonterminal
wenzelm@14790
    16
  type tsig
wenzelm@14790
    17
  val rep_tsig: tsig ->
wenzelm@16370
    18
   {classes: NameSpace.T * Sorts.classes,
wenzelm@14790
    19
    default: sort,
wenzelm@16370
    20
    types: (decl * stamp) NameSpace.table,
wenzelm@14790
    21
    arities: Sorts.arities,
wenzelm@14790
    22
    log_types: string list,
wenzelm@14790
    23
    witness: (typ * sort) option}
wenzelm@14790
    24
  val empty_tsig: tsig
wenzelm@14790
    25
  val classes: tsig -> class list
wenzelm@14790
    26
  val defaultS: tsig -> sort
wenzelm@14790
    27
  val logical_types: tsig -> string list
wenzelm@14790
    28
  val universal_witness: tsig -> (typ * sort) option
wenzelm@14790
    29
  val eq_sort: tsig -> sort * sort -> bool
wenzelm@14790
    30
  val subsort: tsig -> sort * sort -> bool
wenzelm@14790
    31
  val of_sort: tsig -> typ * sort -> bool
wenzelm@14790
    32
  val cert_class: tsig -> class -> class
wenzelm@14790
    33
  val cert_sort: tsig -> sort -> sort
wenzelm@14790
    34
  val witness_sorts: tsig -> sort list -> sort list -> (typ * sort) list
wenzelm@14993
    35
  val cert_typ: tsig -> typ -> typ
wenzelm@14993
    36
  val cert_typ_syntax: tsig -> typ -> typ
wenzelm@16340
    37
  val cert_typ_abbrev: tsig -> typ -> typ
wenzelm@14790
    38
wenzelm@14790
    39
  (*special treatment of type vars*)
wenzelm@14790
    40
  val strip_sorts: typ -> typ
wenzelm@621
    41
  val no_tvars: typ -> typ
wenzelm@621
    42
  val varifyT: typ -> typ
wenzelm@621
    43
  val unvarifyT: typ -> typ
berghofe@15797
    44
  val varify: term * (string * sort) list -> term * ((string * sort) * indexname) list
wenzelm@16289
    45
  val freeze_thaw_type: typ -> typ * (typ -> typ)
wenzelm@16289
    46
  val freeze_type: typ -> typ
wenzelm@16289
    47
  val freeze_thaw: term -> term * (term -> term)
wenzelm@16289
    48
  val freeze: term -> term
wenzelm@2964
    49
wenzelm@14790
    50
  (*matching and unification*)
wenzelm@2964
    51
  exception TYPE_MATCH
berghofe@15797
    52
  type tyenv
berghofe@15797
    53
  val lookup: tyenv * (indexname * sort) -> typ option
wenzelm@16946
    54
  val typ_match: tsig -> typ * typ -> tyenv -> tyenv
wenzelm@14790
    55
  val typ_instance: tsig -> typ * typ -> bool
wenzelm@16946
    56
  val raw_match: typ * typ -> tyenv -> tyenv
wenzelm@16946
    57
  val raw_instance: typ * typ -> bool
wenzelm@2964
    58
  exception TUNIFY
wenzelm@16946
    59
  val unify: tsig -> typ * typ -> tyenv * int -> tyenv * int
wenzelm@16946
    60
  val raw_unify: typ * typ -> tyenv -> tyenv
wenzelm@17804
    61
  val could_unify: typ * typ -> bool
berghofe@16650
    62
  val eq_type: tyenv -> typ * typ -> bool
clasohm@0
    63
wenzelm@14790
    64
  (*extend and merge type signatures*)
wenzelm@16370
    65
  val add_classes: Pretty.pp -> NameSpace.naming -> (bstring * class list) list -> tsig -> tsig
wenzelm@16370
    66
  val hide_classes: bool -> string list -> tsig -> tsig
wenzelm@14830
    67
  val add_classrel: Pretty.pp -> (class * class) list -> tsig -> tsig
wenzelm@14790
    68
  val set_defsort: sort -> tsig -> tsig
wenzelm@16370
    69
  val add_types: NameSpace.naming -> (bstring * int) list -> tsig -> tsig
wenzelm@16370
    70
  val add_abbrevs: NameSpace.naming -> (string * string list * typ) list -> tsig -> tsig
wenzelm@16370
    71
  val add_nonterminals: NameSpace.naming -> string list -> tsig -> tsig
wenzelm@16370
    72
  val hide_types: bool -> string list -> tsig -> tsig
wenzelm@14830
    73
  val add_arities: Pretty.pp -> arity list -> tsig -> tsig
wenzelm@14830
    74
  val merge_tsigs: Pretty.pp -> tsig * tsig -> tsig
wenzelm@2964
    75
end;
wenzelm@2964
    76
wenzelm@2964
    77
structure Type: TYPE =
clasohm@0
    78
struct
clasohm@0
    79
wenzelm@14790
    80
(** type signatures and certified types **)
wenzelm@2964
    81
wenzelm@14790
    82
(* type declarations *)
wenzelm@14790
    83
wenzelm@14790
    84
datatype decl =
wenzelm@14790
    85
  LogicalType of int |
wenzelm@14989
    86
  Abbreviation of string list * typ * bool |
wenzelm@14790
    87
  Nonterminal;
wenzelm@14790
    88
wenzelm@14790
    89
fun str_of_decl (LogicalType _) = "logical type constructor"
wenzelm@14790
    90
  | str_of_decl (Abbreviation _) = "type abbreviation"
wenzelm@14790
    91
  | str_of_decl Nonterminal = "syntactic type";
wenzelm@14790
    92
wenzelm@14790
    93
wenzelm@14790
    94
(* type tsig *)
wenzelm@14790
    95
wenzelm@14790
    96
datatype tsig =
wenzelm@14790
    97
  TSig of {
wenzelm@16370
    98
    classes: NameSpace.T * Sorts.classes,   (*declared classes with proper subclass relation*)
wenzelm@16370
    99
    default: sort,                          (*default sort on input*)
wenzelm@16370
   100
    types: (decl * stamp) NameSpace.table,  (*declared types*)
wenzelm@16370
   101
    arities: Sorts.arities,                 (*image specification of types wrt. sorts*)
wenzelm@16370
   102
    log_types: string list,                 (*logical types sorted by number of arguments*)
wenzelm@16370
   103
    witness: (typ * sort) option};          (*witness for non-emptiness of strictest sort*)
wenzelm@14790
   104
wenzelm@14790
   105
fun rep_tsig (TSig comps) = comps;
wenzelm@14790
   106
wenzelm@14790
   107
fun make_tsig (classes, default, types, arities, log_types, witness) =
wenzelm@14790
   108
  TSig {classes = classes, default = default, types = types, arities = arities,
wenzelm@14790
   109
    log_types = log_types, witness = witness};
wenzelm@14790
   110
wenzelm@14790
   111
fun build_tsig (classes, default, types, arities) =
wenzelm@14790
   112
  let
wenzelm@14790
   113
    val log_types =
wenzelm@17756
   114
      Symtab.fold (fn (c, (LogicalType n, _)) => cons (c, n) | _ => I) (snd types) []
wenzelm@17756
   115
      |> Library.sort (Library.int_ord o pairself snd) |> map fst;
wenzelm@14790
   116
    val witness =
wenzelm@17756
   117
      (case Sorts.witness_sorts (snd classes, arities) log_types [] [Graph.keys (snd classes)] of
skalberg@15531
   118
        [w] => SOME w | _ => NONE);
wenzelm@14790
   119
  in make_tsig (classes, default, types, arities, log_types, witness) end;
wenzelm@14790
   120
wenzelm@16370
   121
fun map_tsig f (TSig {classes, default, types, arities, log_types = _, witness = _}) =
wenzelm@14790
   122
  build_tsig (f (classes, default, types, arities));
wenzelm@14790
   123
wenzelm@16370
   124
val empty_tsig =
wenzelm@16370
   125
  build_tsig ((NameSpace.empty, Graph.empty), [], NameSpace.empty_table, Symtab.empty);
wenzelm@14790
   126
wenzelm@14790
   127
wenzelm@14790
   128
(* classes and sorts *)
wenzelm@14790
   129
wenzelm@16370
   130
fun classes (TSig {classes = (_, C), ...}) = Graph.keys C;
wenzelm@14790
   131
fun defaultS (TSig {default, ...}) = default;
wenzelm@14790
   132
fun logical_types (TSig {log_types, ...}) = log_types;
wenzelm@14790
   133
fun universal_witness (TSig {witness, ...}) = witness;
wenzelm@14790
   134
wenzelm@16370
   135
fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq (#2 classes);
wenzelm@16370
   136
fun subsort (TSig {classes, ...}) = Sorts.sort_le (#2 classes);
wenzelm@16370
   137
fun of_sort (TSig {classes, arities, ...}) = Sorts.of_sort (#2 classes, arities);
wenzelm@14790
   138
wenzelm@16370
   139
fun cert_class (TSig {classes, ...}) = Sorts.certify_class (#2 classes);
wenzelm@16370
   140
fun cert_sort (TSig {classes, ...}) = Sorts.certify_sort (#2 classes);
wenzelm@14790
   141
wenzelm@14790
   142
fun witness_sorts (tsig as TSig {classes, arities, log_types, ...}) =
wenzelm@16370
   143
  Sorts.witness_sorts (#2 classes, arities) log_types;
wenzelm@14790
   144
wenzelm@14790
   145
wenzelm@14790
   146
(* certified types *)
wenzelm@14790
   147
wenzelm@14790
   148
fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
wenzelm@14830
   149
fun undecl_type c = "Undeclared type constructor: " ^ quote c;
wenzelm@14830
   150
wenzelm@14998
   151
local
wenzelm@14998
   152
wenzelm@14998
   153
fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
wenzelm@18957
   154
  | inst_typ env (T as TFree (x, _)) = the_default T (AList.lookup (op =) env x)
wenzelm@14998
   155
  | inst_typ _ T = T;
wenzelm@14998
   156
wenzelm@14790
   157
fun certify_typ normalize syntax tsig ty =
wenzelm@14790
   158
  let
wenzelm@16370
   159
    val TSig {classes = (_, classes), types = (_, types), ...} = tsig;
wenzelm@14790
   160
    fun err msg = raise TYPE (msg, [ty], []);
wenzelm@14790
   161
wenzelm@14989
   162
    val check_syntax =
wenzelm@14989
   163
      if syntax then K ()
wenzelm@14989
   164
      else fn c => err ("Illegal occurrence of syntactic type: " ^ quote c);
wenzelm@14989
   165
wenzelm@14989
   166
    fun cert (T as Type (c, Ts)) =
wenzelm@14989
   167
          let
wenzelm@14989
   168
            val Ts' = map cert Ts;
wenzelm@14989
   169
            fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
wenzelm@14989
   170
          in
wenzelm@17412
   171
            (case Symtab.lookup types c of
skalberg@15531
   172
              SOME (LogicalType n, _) => (nargs n; Type (c, Ts'))
skalberg@15531
   173
            | SOME (Abbreviation (vs, U, syn), _) => (nargs (length vs);
wenzelm@14989
   174
                if syn then check_syntax c else ();
wenzelm@14993
   175
                if normalize then inst_typ (vs ~~ Ts') U
wenzelm@14989
   176
                else Type (c, Ts'))
skalberg@15531
   177
            | SOME (Nonterminal, _) => (nargs 0; check_syntax c; T)
skalberg@15531
   178
            | NONE => err (undecl_type c))
wenzelm@14790
   179
          end
wenzelm@14989
   180
      | cert (TFree (x, S)) = TFree (x, Sorts.certify_sort classes S)
wenzelm@14989
   181
      | cert (TVar (xi as (_, i), S)) =
wenzelm@14993
   182
          if i < 0 then
wenzelm@14993
   183
            err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
wenzelm@14989
   184
          else TVar (xi, Sorts.certify_sort classes S);
wenzelm@14790
   185
wenzelm@14989
   186
    val ty' = cert ty;
wenzelm@14993
   187
  in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
wenzelm@14830
   188
wenzelm@14998
   189
in
wenzelm@14998
   190
wenzelm@16340
   191
val cert_typ        = certify_typ true false;
wenzelm@16340
   192
val cert_typ_syntax = certify_typ true true;
wenzelm@16340
   193
val cert_typ_abbrev = certify_typ false true;
wenzelm@14790
   194
wenzelm@14998
   195
end;
wenzelm@14998
   196
wenzelm@14790
   197
wenzelm@14790
   198
wenzelm@14790
   199
(** special treatment of type vars **)
wenzelm@14790
   200
wenzelm@14790
   201
(* strip_sorts *)
wenzelm@14790
   202
wenzelm@14790
   203
fun strip_sorts (Type (a, Ts)) = Type (a, map strip_sorts Ts)
wenzelm@14790
   204
  | strip_sorts (TFree (x, _)) = TFree (x, [])
wenzelm@14790
   205
  | strip_sorts (TVar (xi, _)) = TVar (xi, []);
wenzelm@14790
   206
wenzelm@14790
   207
wenzelm@14790
   208
(* no_tvars *)
wenzelm@621
   209
wenzelm@621
   210
fun no_tvars T =
wenzelm@12501
   211
  (case typ_tvars T of [] => T
wenzelm@12501
   212
  | vs => raise TYPE ("Illegal schematic type variable(s): " ^
wenzelm@14830
   213
      commas_quote (map (Term.string_of_vname o #1) vs), [T], []));
wenzelm@621
   214
wenzelm@7641
   215
wenzelm@2964
   216
(* varify, unvarify *)
wenzelm@621
   217
wenzelm@2964
   218
val varifyT = map_type_tfree (fn (a, S) => TVar ((a, 0), S));
wenzelm@16946
   219
val unvarifyT = map_type_tvar (fn ((a, 0), S) => TFree (a, S) | v => TVar v);
wenzelm@621
   220
wenzelm@621
   221
fun varify (t, fixed) =
wenzelm@621
   222
  let
wenzelm@19305
   223
    val fs = Term.fold_types (Term.fold_atyps
wenzelm@19305
   224
      (fn TFree v => if member (op =) fixed v then I else insert (op =) v | _ => I)) t [];
wenzelm@621
   225
    val ixns = add_term_tvar_ixns (t, []);
berghofe@15797
   226
    val fmap = fs ~~ map (rpair 0) (variantlist (map fst fs, map #1 ixns))
wenzelm@2964
   227
    fun thaw (f as (a, S)) =
wenzelm@17184
   228
      (case AList.lookup (op =) fmap f of
skalberg@15531
   229
        NONE => TFree f
wenzelm@16946
   230
      | SOME xi => TVar (xi, S));
wenzelm@12501
   231
  in (map_term_types (map_type_tfree thaw) t, fmap) end;
wenzelm@2964
   232
wenzelm@2964
   233
wenzelm@7641
   234
(* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
paulson@3411
   235
wenzelm@7641
   236
local
wenzelm@7641
   237
wenzelm@16289
   238
fun new_name (ix, (pairs, used)) =
wenzelm@16289
   239
  let val v = variant used (string_of_indexname ix)
wenzelm@16289
   240
  in ((ix, v) :: pairs, v :: used) end;
wenzelm@621
   241
wenzelm@16289
   242
fun freeze_one alist (ix, sort) =
wenzelm@17184
   243
  TFree (the (AList.lookup (op =) alist ix), sort)
skalberg@15531
   244
    handle Option =>
wenzelm@3790
   245
      raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
wenzelm@2964
   246
wenzelm@17184
   247
fun thaw_one alist (a, sort) = TVar (the (AList.lookup (op =) alist a), sort)
wenzelm@16289
   248
  handle Option => TFree (a, sort);
wenzelm@416
   249
wenzelm@10495
   250
in
wenzelm@10495
   251
wenzelm@10495
   252
(*this sort of code could replace unvarifyT*)
wenzelm@7641
   253
fun freeze_thaw_type T =
wenzelm@7641
   254
  let
wenzelm@7641
   255
    val used = add_typ_tfree_names (T, [])
wenzelm@7641
   256
    and tvars = map #1 (add_typ_tvars (T, []));
skalberg@15574
   257
    val (alist, _) = foldr new_name ([], used) tvars;
wenzelm@7641
   258
  in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
wenzelm@7641
   259
wenzelm@16289
   260
val freeze_type = #1 o freeze_thaw_type;
wenzelm@16289
   261
paulson@3411
   262
fun freeze_thaw t =
wenzelm@7641
   263
  let
wenzelm@7641
   264
    val used = it_term_types add_typ_tfree_names (t, [])
wenzelm@7641
   265
    and tvars = map #1 (it_term_types add_typ_tvars (t, []));
skalberg@15574
   266
    val (alist, _) = foldr new_name ([], used) tvars;
wenzelm@7641
   267
  in
wenzelm@7641
   268
    (case alist of
wenzelm@7641
   269
      [] => (t, fn x => x) (*nothing to do!*)
wenzelm@7641
   270
    | _ => (map_term_types (map_type_tvar (freeze_one alist)) t,
wenzelm@7641
   271
      map_term_types (map_type_tfree (thaw_one (map swap alist)))))
wenzelm@7641
   272
  end;
wenzelm@7641
   273
wenzelm@16289
   274
val freeze = #1 o freeze_thaw;
wenzelm@16289
   275
wenzelm@7641
   276
end;
wenzelm@7641
   277
wenzelm@256
   278
wenzelm@256
   279
wenzelm@14790
   280
(** matching and unification of types **)
wenzelm@8899
   281
berghofe@15797
   282
type tyenv = (sort * typ) Vartab.table;
wenzelm@256
   283
berghofe@15797
   284
fun tvar_clash ixn S S' = raise TYPE ("Type variable " ^
berghofe@15797
   285
  quote (Term.string_of_vname ixn) ^ " has two distinct sorts",
berghofe@15797
   286
  [TVar (ixn, S), TVar (ixn, S')], []);
clasohm@0
   287
wenzelm@16289
   288
fun lookup (tye, (ixn, S)) =
wenzelm@17412
   289
  (case Vartab.lookup tye ixn of
berghofe@15797
   290
    NONE => NONE
wenzelm@16289
   291
  | SOME (S', T) => if S = S' then SOME T else tvar_clash ixn S S');
wenzelm@16289
   292
clasohm@0
   293
wenzelm@14790
   294
(* matching *)
clasohm@0
   295
wenzelm@2964
   296
exception TYPE_MATCH;
clasohm@0
   297
wenzelm@16946
   298
fun typ_match tsig =
wenzelm@2964
   299
  let
wenzelm@16340
   300
    fun match (TVar (v, S), T) subs =
berghofe@15797
   301
          (case lookup (subs, (v, S)) of
skalberg@15531
   302
            NONE =>
wenzelm@17412
   303
              if of_sort tsig (T, S) then Vartab.update_new (v, (S, T)) subs
wenzelm@14993
   304
              else raise TYPE_MATCH
skalberg@15531
   305
          | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16340
   306
      | match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@2964
   307
          if a <> b then raise TYPE_MATCH
wenzelm@16885
   308
          else matches (Ts, Us) subs
wenzelm@16340
   309
      | match (TFree x, TFree y) subs =
wenzelm@2964
   310
          if x = y then subs else raise TYPE_MATCH
wenzelm@16885
   311
      | match _ _ = raise TYPE_MATCH
wenzelm@16885
   312
    and matches (T :: Ts, U :: Us) subs = matches (Ts, Us) (match (T, U) subs)
wenzelm@16885
   313
      | matches _ subs = subs;
wenzelm@16946
   314
  in match end;
clasohm@0
   315
wenzelm@14790
   316
fun typ_instance tsig (T, U) =
wenzelm@16946
   317
  (typ_match tsig (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@16946
   318
wenzelm@16946
   319
(*purely structural matching*)
wenzelm@16946
   320
fun raw_match (TVar (v, S), T) subs =
wenzelm@16946
   321
      (case lookup (subs, (v, S)) of
wenzelm@17412
   322
        NONE => Vartab.update_new (v, (S, T)) subs
wenzelm@16946
   323
      | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16946
   324
  | raw_match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@16946
   325
      if a <> b then raise TYPE_MATCH
wenzelm@16946
   326
      else raw_matches (Ts, Us) subs
wenzelm@16946
   327
  | raw_match (TFree x, TFree y) subs =
wenzelm@16946
   328
      if x = y then subs else raise TYPE_MATCH
wenzelm@16946
   329
  | raw_match _ _ = raise TYPE_MATCH
wenzelm@16946
   330
and raw_matches (T :: Ts, U :: Us) subs = raw_matches (Ts, Us) (raw_match (T, U) subs)
wenzelm@16946
   331
  | raw_matches _ subs = subs;
wenzelm@16946
   332
wenzelm@16946
   333
fun raw_instance (T, U) =
wenzelm@16946
   334
  (raw_match (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@2964
   335
clasohm@0
   336
wenzelm@14790
   337
(* unification *)
wenzelm@2964
   338
clasohm@0
   339
exception TUNIFY;
clasohm@0
   340
wenzelm@14790
   341
(*occurs_check*)
wenzelm@2964
   342
fun occurs v tye =
wenzelm@2964
   343
  let
wenzelm@2964
   344
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   345
      | occ (TFree _) = false
berghofe@15797
   346
      | occ (TVar (w, S)) =
wenzelm@2964
   347
          eq_ix (v, w) orelse
berghofe@15797
   348
            (case lookup (tye, (w, S)) of
skalberg@15531
   349
              NONE => false
skalberg@15531
   350
            | SOME U => occ U);
clasohm@0
   351
  in occ end;
clasohm@0
   352
wenzelm@14790
   353
(*chase variable assignments; if devar returns a type var then it must be unassigned*)
wenzelm@16885
   354
fun devar tye (T as TVar v) =
wenzelm@16885
   355
      (case lookup (tye, v) of
wenzelm@16885
   356
        SOME U => devar tye U
skalberg@15531
   357
      | NONE => T)
wenzelm@16885
   358
  | devar tye T = T;
clasohm@0
   359
wenzelm@17804
   360
(*order-sorted unification*)
wenzelm@16946
   361
fun unify (tsig as TSig {classes = (_, classes), arities, ...}) TU (tyenv, maxidx) =
wenzelm@2964
   362
  let
wenzelm@2964
   363
    val tyvar_count = ref maxidx;
wenzelm@2964
   364
    fun gen_tyvar S = TVar (("'a", inc tyvar_count), S);
wenzelm@2964
   365
wenzelm@2964
   366
    fun mg_domain a S =
wenzelm@14790
   367
      Sorts.mg_domain (classes, arities) a S handle Sorts.DOMAIN _ => raise TUNIFY;
wenzelm@2964
   368
wenzelm@16885
   369
    fun meet (_, []) tye = tye
wenzelm@16885
   370
      | meet (TVar (xi, S'), S) tye =
wenzelm@14790
   371
          if Sorts.sort_le classes (S', S) then tye
wenzelm@17412
   372
          else Vartab.update_new
wenzelm@17221
   373
            (xi, (S', gen_tyvar (Sorts.inter_sort classes (S', S)))) tye
wenzelm@16885
   374
      | meet (TFree (_, S'), S) tye =
wenzelm@14790
   375
          if Sorts.sort_le classes (S', S) then tye
wenzelm@2964
   376
          else raise TUNIFY
wenzelm@16885
   377
      | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
wenzelm@16885
   378
    and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
wenzelm@16885
   379
      | meets _ tye = tye;
wenzelm@2964
   380
wenzelm@16885
   381
    fun unif (ty1, ty2) tye =
wenzelm@16885
   382
      (case (devar tye ty1, devar tye ty2) of
wenzelm@2964
   383
        (T as TVar (v, S1), U as TVar (w, S2)) =>
berghofe@15797
   384
          if eq_ix (v, w) then
berghofe@15797
   385
            if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@14790
   386
          else if Sorts.sort_le classes (S1, S2) then
wenzelm@17412
   387
            Vartab.update_new (w, (S2, T)) tye
wenzelm@14790
   388
          else if Sorts.sort_le classes (S2, S1) then
wenzelm@17412
   389
            Vartab.update_new (v, (S1, U)) tye
wenzelm@2964
   390
          else
wenzelm@14790
   391
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
wenzelm@17412
   392
              Vartab.update_new (v, (S1, S)) (Vartab.update_new (w, (S2, S)) tye)
wenzelm@2964
   393
            end
wenzelm@2964
   394
      | (TVar (v, S), T) =>
wenzelm@2964
   395
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   396
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   397
      | (T, TVar (v, S)) =>
wenzelm@2964
   398
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   399
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   400
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   401
          if a <> b then raise TUNIFY
wenzelm@16885
   402
          else unifs (Ts, Us) tye
wenzelm@16885
   403
      | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16885
   404
    and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
wenzelm@16885
   405
      | unifs _ tye = tye;
wenzelm@16885
   406
  in (unif TU tyenv, ! tyvar_count) end;
clasohm@0
   407
wenzelm@16946
   408
(*purely structural unification*)
wenzelm@16946
   409
fun raw_unify (ty1, ty2) tye =
wenzelm@16946
   410
  (case (devar tye ty1, devar tye ty2) of
wenzelm@16946
   411
    (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@16946
   412
      if eq_ix (v, w) then
wenzelm@16946
   413
        if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@17412
   414
      else Vartab.update_new (w, (S2, T)) tye
wenzelm@16946
   415
  | (TVar (v, S), T) =>
wenzelm@16946
   416
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   417
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   418
  | (T, TVar (v, S)) =>
wenzelm@16946
   419
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   420
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   421
  | (Type (a, Ts), Type (b, Us)) =>
wenzelm@16946
   422
      if a <> b then raise TUNIFY
wenzelm@16946
   423
      else raw_unifys (Ts, Us) tye
wenzelm@16946
   424
  | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16946
   425
and raw_unifys (T :: Ts, U :: Us) tye = raw_unifys (Ts, Us) (raw_unify (T, U) tye)
wenzelm@16946
   426
  | raw_unifys _ tye = tye;
wenzelm@16946
   427
wenzelm@17804
   428
(*fast unification filter*)
wenzelm@17804
   429
fun could_unify (Type (a, Ts), Type (b, Us)) = a = b andalso could_unifys (Ts, Us)
wenzelm@17804
   430
  | could_unify (TFree (a, _), TFree (b, _)) = a = b
wenzelm@17804
   431
  | could_unify (TVar _, _) = true
wenzelm@17804
   432
  | could_unify (_, TVar _) = true
wenzelm@17804
   433
  | could_unify _ = false
wenzelm@17804
   434
and could_unifys (T :: Ts, U :: Us) = could_unify (T, U) andalso could_unifys (Ts, Us)
wenzelm@17804
   435
  | could_unifys _ = true;
wenzelm@450
   436
wenzelm@17804
   437
wenzelm@17804
   438
(*equality with respect to a type environment*)
berghofe@16650
   439
fun eq_type tye (T, T') =
wenzelm@16885
   440
  (case (devar tye T, devar tye T') of
berghofe@16650
   441
     (Type (s, Ts), Type (s', Ts')) =>
berghofe@16650
   442
       s = s' andalso ListPair.all (eq_type tye) (Ts, Ts')
berghofe@16650
   443
   | (U, U') => U = U');
berghofe@16650
   444
wenzelm@450
   445
clasohm@0
   446
wenzelm@14790
   447
(** extend and merge type signatures **)
wenzelm@14790
   448
wenzelm@14790
   449
(* arities *)
wenzelm@14790
   450
wenzelm@14790
   451
local
nipkow@1435
   452
wenzelm@14790
   453
fun err_decl t decl = error ("Illegal " ^ str_of_decl decl ^ ": " ^ quote t);
wenzelm@14830
   454
skalberg@15531
   455
fun for_classes _ NONE = ""
skalberg@15531
   456
  | for_classes pp (SOME (c1, c2)) =
wenzelm@14830
   457
      " for classes " ^ Pretty.string_of_classrel pp [c1, c2];
wenzelm@3790
   458
wenzelm@14830
   459
fun err_conflict pp t cc (c, Ss) (c', Ss') =
wenzelm@14830
   460
  error ("Conflict of type arities" ^ for_classes pp cc ^ ":\n  " ^
wenzelm@14830
   461
    Pretty.string_of_arity pp (t, Ss, [c]) ^ " and\n  " ^
wenzelm@14830
   462
    Pretty.string_of_arity pp (t, Ss', [c']));
wenzelm@14790
   463
wenzelm@14830
   464
fun coregular pp C t (c, Ss) ars =
wenzelm@3790
   465
  let
wenzelm@14790
   466
    fun conflict (c', Ss') =
wenzelm@14790
   467
      if Sorts.class_le C (c, c') andalso not (Sorts.sorts_le C (Ss, Ss')) then
skalberg@15531
   468
        SOME ((c, c'), (c', Ss'))
wenzelm@14790
   469
      else if Sorts.class_le C (c', c) andalso not (Sorts.sorts_le C (Ss', Ss)) then
skalberg@15531
   470
        SOME ((c', c), (c', Ss'))
skalberg@15531
   471
      else NONE;
wenzelm@14790
   472
  in
wenzelm@14790
   473
    (case Library.get_first conflict ars of
skalberg@15531
   474
      SOME ((c1, c2), (c', Ss')) => err_conflict pp t (SOME (c1, c2)) (c, Ss) (c', Ss')
skalberg@15531
   475
    | NONE => (c, Ss) :: ars)
wenzelm@14790
   476
  end;
wenzelm@3790
   477
wenzelm@16340
   478
fun insert pp C t (c, Ss) ars =
wenzelm@17184
   479
  (case AList.lookup (op =) ars c of
skalberg@15531
   480
    NONE => coregular pp C t (c, Ss) ars
skalberg@15531
   481
  | SOME Ss' =>
wenzelm@14790
   482
      if Sorts.sorts_le C (Ss, Ss') then ars
wenzelm@14790
   483
      else if Sorts.sorts_le C (Ss', Ss)
wenzelm@19250
   484
      then coregular pp C t (c, Ss) (remove (op =) (c, Ss') ars)
skalberg@15531
   485
      else err_conflict pp t NONE (c, Ss) (c, Ss'));
wenzelm@2587
   486
wenzelm@14790
   487
fun complete C (c, Ss) = map (rpair Ss) (Graph.all_succs C [c]);
wenzelm@3790
   488
wenzelm@16340
   489
fun insert_arities pp classes (t, ars) arities =
wenzelm@14790
   490
  let val ars' =
wenzelm@18957
   491
    Symtab.lookup_list arities t
wenzelm@16340
   492
    |> fold_rev (fold_rev (insert pp classes t)) (map (complete classes) ars)
wenzelm@17412
   493
  in Symtab.update (t, ars') arities end;
wenzelm@3790
   494
wenzelm@16444
   495
fun insert_table pp classes = Symtab.fold (fn (t, ars) =>
wenzelm@16444
   496
  insert_arities pp classes (t, map (apsnd (map (Sorts.norm_sort classes))) ars));
wenzelm@14790
   497
wenzelm@14790
   498
in
wenzelm@2587
   499
wenzelm@16370
   500
fun add_arities pp decls tsig = tsig |> map_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   501
  let
wenzelm@14790
   502
    fun prep (t, Ss, S) =
wenzelm@17756
   503
      (case Symtab.lookup (snd types) t of
skalberg@15531
   504
        SOME (LogicalType n, _) =>
wenzelm@14790
   505
          if length Ss = n then
wenzelm@14790
   506
            (t, map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@14790
   507
              handle TYPE (msg, _, _) => error msg
wenzelm@14790
   508
          else error (bad_nargs t)
skalberg@15531
   509
      | SOME (decl, _) => err_decl t decl
skalberg@15531
   510
      | NONE => error (undecl_type t));
wenzelm@4603
   511
wenzelm@14790
   512
    val ars = decls |> map ((fn (t, Ss, S) => (t, map (fn c => (c, Ss)) S)) o prep);
wenzelm@17756
   513
    val arities' = fold (insert_arities pp (snd classes)) ars arities;
wenzelm@14790
   514
  in (classes, default, types, arities') end);
wenzelm@12528
   515
wenzelm@14830
   516
fun rebuild_arities pp classes arities =
wenzelm@16444
   517
  Symtab.empty
wenzelm@16444
   518
  |> insert_table pp classes arities;
wenzelm@14790
   519
wenzelm@14830
   520
fun merge_arities pp classes (arities1, arities2) =
wenzelm@16444
   521
  Symtab.empty
wenzelm@16444
   522
  |> insert_table pp classes arities1
wenzelm@16444
   523
  |> insert_table pp classes arities2;
wenzelm@14790
   524
wenzelm@14790
   525
end;
wenzelm@4603
   526
wenzelm@4603
   527
wenzelm@14790
   528
(* classes *)
wenzelm@14790
   529
wenzelm@14790
   530
local
clasohm@0
   531
wenzelm@14790
   532
fun err_dup_classes cs =
wenzelm@14790
   533
  error ("Duplicate declaration of class(es): " ^ commas_quote cs);
wenzelm@14790
   534
wenzelm@14830
   535
fun err_cyclic_classes pp css =
wenzelm@14790
   536
  error (cat_lines (map (fn cs =>
wenzelm@14830
   537
    "Cycle in class relation: " ^ Pretty.string_of_classrel pp cs) css));
wenzelm@14790
   538
wenzelm@16370
   539
fun add_class pp naming (c, cs) tsig =
wenzelm@16370
   540
  tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   541
    let
wenzelm@16370
   542
      val c' = NameSpace.full naming c;
wenzelm@16370
   543
      val cs' = map (cert_class tsig) cs
wenzelm@16370
   544
        handle TYPE (msg, _, _) => error msg;
wenzelm@16370
   545
      val space' = space |> NameSpace.declare naming c';
wenzelm@16370
   546
      val classes' = classes |> Graph.new_node (c', stamp ())
wenzelm@16370
   547
        handle Graph.DUP dup => err_dup_classes [dup];
wenzelm@16370
   548
      val classes'' = classes' |> fold Graph.add_edge_trans_acyclic (map (pair c') cs')
wenzelm@16370
   549
        handle Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   550
    in ((space', classes''), default, types, arities) end);
wenzelm@2964
   551
wenzelm@14790
   552
in
clasohm@0
   553
wenzelm@16370
   554
val add_classes = fold oo add_class;
wenzelm@14790
   555
wenzelm@16370
   556
fun add_classrel pp ps tsig =
wenzelm@16370
   557
  tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   558
    let
wenzelm@16370
   559
      val ps' = map (pairself (cert_class tsig)) ps
wenzelm@16370
   560
        handle TYPE (msg, _, _) => error msg;
wenzelm@16370
   561
      val classes' = classes |> fold Graph.add_edge_trans_acyclic ps'
wenzelm@16370
   562
        handle Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   563
      val default' = default |> Sorts.norm_sort classes';
wenzelm@16370
   564
      val arities' = arities |> rebuild_arities pp classes';
wenzelm@16370
   565
    in ((space, classes'), default', types, arities') end);
wenzelm@16370
   566
wenzelm@16370
   567
fun merge_classes pp ((space1, classes1), (space2, classes2)) =
wenzelm@14790
   568
  let
wenzelm@16370
   569
    val space = NameSpace.merge (space1, space2);
wenzelm@16370
   570
    val classes =
wenzelm@16370
   571
      Graph.merge_trans_acyclic (op =) (classes1, classes2)
wenzelm@16370
   572
        handle Graph.DUPS cs => err_dup_classes cs
wenzelm@16370
   573
          | Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16946
   574
  in (space, classes) end;
wenzelm@14790
   575
wenzelm@14790
   576
end;
wenzelm@14790
   577
wenzelm@16370
   578
fun hide_classes fully cs = map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   579
  ((fold (NameSpace.hide fully) cs space, classes), default, types, arities));
wenzelm@16370
   580
wenzelm@14790
   581
wenzelm@14790
   582
(* default sort *)
wenzelm@14790
   583
wenzelm@16370
   584
fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types, arities) =>
wenzelm@14790
   585
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types, arities));
clasohm@0
   586
clasohm@0
   587
wenzelm@14790
   588
(* types *)
wenzelm@14790
   589
wenzelm@14790
   590
local
wenzelm@14790
   591
wenzelm@14790
   592
fun err_neg_args c =
wenzelm@14790
   593
  error ("Negative number of arguments in type constructor declaration: " ^ quote c);
nipkow@949
   594
wenzelm@14790
   595
fun err_in_decls c decl decl' =
wenzelm@14906
   596
  let val s = str_of_decl decl and s' = str_of_decl decl' in
wenzelm@14906
   597
    if s = s' then error ("Duplicate declaration of " ^ s ^ ": " ^ quote c)
wenzelm@14830
   598
    else error ("Conflict of " ^ s ^ " with " ^ s' ^ ": " ^ quote c)
wenzelm@14790
   599
  end;
wenzelm@14790
   600
wenzelm@16370
   601
fun new_decl naming (c, decl) (space, types) =
wenzelm@16370
   602
  let
wenzelm@16370
   603
    val c' = NameSpace.full naming c;
wenzelm@16370
   604
    val space' = NameSpace.declare naming c' space;
wenzelm@16370
   605
    val types' =
wenzelm@17412
   606
      (case Symtab.lookup types c' of
wenzelm@16370
   607
        SOME (decl', _) => err_in_decls c' decl decl'
wenzelm@17412
   608
      | NONE => Symtab.update (c', (decl, stamp ())) types);
wenzelm@16370
   609
  in (space', types') end;
wenzelm@14790
   610
wenzelm@17412
   611
fun the_decl (_, types) = fst o the o Symtab.lookup types;
wenzelm@14790
   612
wenzelm@16370
   613
fun change_types f = map_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   614
  (classes, default, f types, arities));
wenzelm@2964
   615
wenzelm@14989
   616
fun syntactic types (Type (c, Ts)) =
wenzelm@17412
   617
      (case Symtab.lookup types c of SOME (Nonterminal, _) => true | _ => false)
wenzelm@14989
   618
        orelse exists (syntactic types) Ts
wenzelm@14989
   619
  | syntactic _ _ = false;
wenzelm@14989
   620
wenzelm@16370
   621
fun add_abbrev naming (a, vs, rhs) tsig = tsig |> change_types (fn types =>
wenzelm@14790
   622
  let
wenzelm@19250
   623
    fun err msg = cat_error msg ("The error(s) above occurred in type abbreviation: " ^ quote a);
wenzelm@16946
   624
    val rhs' = strip_sorts (no_tvars (cert_typ_syntax tsig rhs))
wenzelm@14790
   625
      handle TYPE (msg, _, _) => err msg;
wenzelm@14790
   626
  in
wenzelm@18964
   627
    (case duplicates (op =) vs of
wenzelm@14790
   628
      [] => []
wenzelm@14790
   629
    | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
wenzelm@14790
   630
    (case gen_rems (op =) (map (#1 o #1) (typ_tvars rhs'), vs) of
wenzelm@14790
   631
      [] => []
wenzelm@14790
   632
    | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
wenzelm@16370
   633
    types |> new_decl naming (a, Abbreviation (vs, rhs', syntactic (#2 types) rhs'))
wenzelm@14790
   634
  end);
clasohm@0
   635
wenzelm@14790
   636
in
wenzelm@14790
   637
wenzelm@16370
   638
fun add_types naming ps = change_types (fold (new_decl naming) (ps |> map (fn (c, n) =>
wenzelm@14790
   639
  if n < 0 then err_neg_args c else (c, LogicalType n))));
wenzelm@14790
   640
wenzelm@16370
   641
val add_abbrevs = fold o add_abbrev;
wenzelm@16370
   642
wenzelm@16370
   643
fun add_nonterminals naming = change_types o fold (new_decl naming) o map (rpair Nonterminal);
wenzelm@14790
   644
wenzelm@14790
   645
fun merge_types (types1, types2) =
haftmann@17496
   646
  NameSpace.merge_tables (Library.eq_snd (op =)) (types1, types2) handle Symtab.DUPS (d :: _) =>
wenzelm@14790
   647
    err_in_decls d (the_decl types1 d) (the_decl types2 d);
wenzelm@14790
   648
wenzelm@14790
   649
end;
clasohm@0
   650
wenzelm@16370
   651
fun hide_types fully cs = map_tsig (fn (classes, default, (space, types), arities) =>
wenzelm@16370
   652
  (classes, default, (fold (NameSpace.hide fully) cs space, types), arities));
wenzelm@16370
   653
wenzelm@3790
   654
wenzelm@14790
   655
(* merge type signatures *)
wenzelm@14790
   656
wenzelm@14830
   657
fun merge_tsigs pp (tsig1, tsig2) =
wenzelm@14790
   658
  let
wenzelm@14790
   659
    val (TSig {classes = classes1, default = default1, types = types1, arities = arities1,
wenzelm@14790
   660
      log_types = _, witness = _}) = tsig1;
wenzelm@14790
   661
    val (TSig {classes = classes2, default = default2, types = types2, arities = arities2,
wenzelm@14790
   662
      log_types = _, witness = _}) = tsig2;
wenzelm@14790
   663
wenzelm@14830
   664
    val classes' = merge_classes pp (classes1, classes2);
wenzelm@16370
   665
    val default' = Sorts.inter_sort (#2 classes') (default1, default2);
wenzelm@14790
   666
    val types' = merge_types (types1, types2);
wenzelm@16370
   667
    val arities' = merge_arities pp (#2 classes') (arities1, arities2);
wenzelm@14790
   668
  in build_tsig (classes', default', types', arities') end;
wenzelm@14790
   669
clasohm@0
   670
end;