src/Pure/type.ML
author wenzelm
Sat Oct 08 22:39:42 2005 +0200 (2005-10-08 ago)
changeset 17804 4deae4b33d97
parent 17756 d4a35f82fbb4
child 18928 042608ffa2ec
permissions -rw-r--r--
added could_unify;
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@17184
   154
  | inst_typ env (T as TFree (x, _)) = if_none (AList.lookup (op =) env x) T
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
berghofe@15797
   223
    val fs = add_term_tfrees (t, []) \\ fixed;
wenzelm@621
   224
    val ixns = add_term_tvar_ixns (t, []);
berghofe@15797
   225
    val fmap = fs ~~ map (rpair 0) (variantlist (map fst fs, map #1 ixns))
wenzelm@2964
   226
    fun thaw (f as (a, S)) =
wenzelm@17184
   227
      (case AList.lookup (op =) fmap f of
skalberg@15531
   228
        NONE => TFree f
wenzelm@16946
   229
      | SOME xi => TVar (xi, S));
wenzelm@12501
   230
  in (map_term_types (map_type_tfree thaw) t, fmap) end;
wenzelm@2964
   231
wenzelm@2964
   232
wenzelm@7641
   233
(* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
paulson@3411
   234
wenzelm@7641
   235
local
wenzelm@7641
   236
wenzelm@16289
   237
fun new_name (ix, (pairs, used)) =
wenzelm@16289
   238
  let val v = variant used (string_of_indexname ix)
wenzelm@16289
   239
  in ((ix, v) :: pairs, v :: used) end;
wenzelm@621
   240
wenzelm@16289
   241
fun freeze_one alist (ix, sort) =
wenzelm@17184
   242
  TFree (the (AList.lookup (op =) alist ix), sort)
skalberg@15531
   243
    handle Option =>
wenzelm@3790
   244
      raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
wenzelm@2964
   245
wenzelm@17184
   246
fun thaw_one alist (a, sort) = TVar (the (AList.lookup (op =) alist a), sort)
wenzelm@16289
   247
  handle Option => TFree (a, sort);
wenzelm@416
   248
wenzelm@10495
   249
in
wenzelm@10495
   250
wenzelm@10495
   251
(*this sort of code could replace unvarifyT*)
wenzelm@7641
   252
fun freeze_thaw_type T =
wenzelm@7641
   253
  let
wenzelm@7641
   254
    val used = add_typ_tfree_names (T, [])
wenzelm@7641
   255
    and tvars = map #1 (add_typ_tvars (T, []));
skalberg@15574
   256
    val (alist, _) = foldr new_name ([], used) tvars;
wenzelm@7641
   257
  in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
wenzelm@7641
   258
wenzelm@16289
   259
val freeze_type = #1 o freeze_thaw_type;
wenzelm@16289
   260
paulson@3411
   261
fun freeze_thaw t =
wenzelm@7641
   262
  let
wenzelm@7641
   263
    val used = it_term_types add_typ_tfree_names (t, [])
wenzelm@7641
   264
    and tvars = map #1 (it_term_types add_typ_tvars (t, []));
skalberg@15574
   265
    val (alist, _) = foldr new_name ([], used) tvars;
wenzelm@7641
   266
  in
wenzelm@7641
   267
    (case alist of
wenzelm@7641
   268
      [] => (t, fn x => x) (*nothing to do!*)
wenzelm@7641
   269
    | _ => (map_term_types (map_type_tvar (freeze_one alist)) t,
wenzelm@7641
   270
      map_term_types (map_type_tfree (thaw_one (map swap alist)))))
wenzelm@7641
   271
  end;
wenzelm@7641
   272
wenzelm@16289
   273
val freeze = #1 o freeze_thaw;
wenzelm@16289
   274
wenzelm@7641
   275
end;
wenzelm@7641
   276
wenzelm@256
   277
wenzelm@256
   278
wenzelm@14790
   279
(** matching and unification of types **)
wenzelm@8899
   280
berghofe@15797
   281
type tyenv = (sort * typ) Vartab.table;
wenzelm@256
   282
berghofe@15797
   283
fun tvar_clash ixn S S' = raise TYPE ("Type variable " ^
berghofe@15797
   284
  quote (Term.string_of_vname ixn) ^ " has two distinct sorts",
berghofe@15797
   285
  [TVar (ixn, S), TVar (ixn, S')], []);
clasohm@0
   286
wenzelm@16289
   287
fun lookup (tye, (ixn, S)) =
wenzelm@17412
   288
  (case Vartab.lookup tye ixn of
berghofe@15797
   289
    NONE => NONE
wenzelm@16289
   290
  | SOME (S', T) => if S = S' then SOME T else tvar_clash ixn S S');
wenzelm@16289
   291
clasohm@0
   292
wenzelm@14790
   293
(* matching *)
clasohm@0
   294
wenzelm@2964
   295
exception TYPE_MATCH;
clasohm@0
   296
wenzelm@16946
   297
fun typ_match tsig =
wenzelm@2964
   298
  let
wenzelm@16340
   299
    fun match (TVar (v, S), T) subs =
berghofe@15797
   300
          (case lookup (subs, (v, S)) of
skalberg@15531
   301
            NONE =>
wenzelm@17412
   302
              if of_sort tsig (T, S) then Vartab.update_new (v, (S, T)) subs
wenzelm@14993
   303
              else raise TYPE_MATCH
skalberg@15531
   304
          | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16340
   305
      | match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@2964
   306
          if a <> b then raise TYPE_MATCH
wenzelm@16885
   307
          else matches (Ts, Us) subs
wenzelm@16340
   308
      | match (TFree x, TFree y) subs =
wenzelm@2964
   309
          if x = y then subs else raise TYPE_MATCH
wenzelm@16885
   310
      | match _ _ = raise TYPE_MATCH
wenzelm@16885
   311
    and matches (T :: Ts, U :: Us) subs = matches (Ts, Us) (match (T, U) subs)
wenzelm@16885
   312
      | matches _ subs = subs;
wenzelm@16946
   313
  in match end;
clasohm@0
   314
wenzelm@14790
   315
fun typ_instance tsig (T, U) =
wenzelm@16946
   316
  (typ_match tsig (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@16946
   317
wenzelm@16946
   318
(*purely structural matching*)
wenzelm@16946
   319
fun raw_match (TVar (v, S), T) subs =
wenzelm@16946
   320
      (case lookup (subs, (v, S)) of
wenzelm@17412
   321
        NONE => Vartab.update_new (v, (S, T)) subs
wenzelm@16946
   322
      | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16946
   323
  | raw_match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@16946
   324
      if a <> b then raise TYPE_MATCH
wenzelm@16946
   325
      else raw_matches (Ts, Us) subs
wenzelm@16946
   326
  | raw_match (TFree x, TFree y) subs =
wenzelm@16946
   327
      if x = y then subs else raise TYPE_MATCH
wenzelm@16946
   328
  | raw_match _ _ = raise TYPE_MATCH
wenzelm@16946
   329
and raw_matches (T :: Ts, U :: Us) subs = raw_matches (Ts, Us) (raw_match (T, U) subs)
wenzelm@16946
   330
  | raw_matches _ subs = subs;
wenzelm@16946
   331
wenzelm@16946
   332
fun raw_instance (T, U) =
wenzelm@16946
   333
  (raw_match (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@2964
   334
clasohm@0
   335
wenzelm@14790
   336
(* unification *)
wenzelm@2964
   337
clasohm@0
   338
exception TUNIFY;
clasohm@0
   339
wenzelm@14790
   340
(*occurs_check*)
wenzelm@2964
   341
fun occurs v tye =
wenzelm@2964
   342
  let
wenzelm@2964
   343
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   344
      | occ (TFree _) = false
berghofe@15797
   345
      | occ (TVar (w, S)) =
wenzelm@2964
   346
          eq_ix (v, w) orelse
berghofe@15797
   347
            (case lookup (tye, (w, S)) of
skalberg@15531
   348
              NONE => false
skalberg@15531
   349
            | SOME U => occ U);
clasohm@0
   350
  in occ end;
clasohm@0
   351
wenzelm@14790
   352
(*chase variable assignments; if devar returns a type var then it must be unassigned*)
wenzelm@16885
   353
fun devar tye (T as TVar v) =
wenzelm@16885
   354
      (case lookup (tye, v) of
wenzelm@16885
   355
        SOME U => devar tye U
skalberg@15531
   356
      | NONE => T)
wenzelm@16885
   357
  | devar tye T = T;
clasohm@0
   358
wenzelm@17804
   359
(*order-sorted unification*)
wenzelm@16946
   360
fun unify (tsig as TSig {classes = (_, classes), arities, ...}) TU (tyenv, maxidx) =
wenzelm@2964
   361
  let
wenzelm@2964
   362
    val tyvar_count = ref maxidx;
wenzelm@2964
   363
    fun gen_tyvar S = TVar (("'a", inc tyvar_count), S);
wenzelm@2964
   364
wenzelm@2964
   365
    fun mg_domain a S =
wenzelm@14790
   366
      Sorts.mg_domain (classes, arities) a S handle Sorts.DOMAIN _ => raise TUNIFY;
wenzelm@2964
   367
wenzelm@16885
   368
    fun meet (_, []) tye = tye
wenzelm@16885
   369
      | meet (TVar (xi, S'), S) tye =
wenzelm@14790
   370
          if Sorts.sort_le classes (S', S) then tye
wenzelm@17412
   371
          else Vartab.update_new
wenzelm@17221
   372
            (xi, (S', gen_tyvar (Sorts.inter_sort classes (S', S)))) tye
wenzelm@16885
   373
      | meet (TFree (_, S'), S) tye =
wenzelm@14790
   374
          if Sorts.sort_le classes (S', S) then tye
wenzelm@2964
   375
          else raise TUNIFY
wenzelm@16885
   376
      | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
wenzelm@16885
   377
    and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
wenzelm@16885
   378
      | meets _ tye = tye;
wenzelm@2964
   379
wenzelm@16885
   380
    fun unif (ty1, ty2) tye =
wenzelm@16885
   381
      (case (devar tye ty1, devar tye ty2) of
wenzelm@2964
   382
        (T as TVar (v, S1), U as TVar (w, S2)) =>
berghofe@15797
   383
          if eq_ix (v, w) then
berghofe@15797
   384
            if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@14790
   385
          else if Sorts.sort_le classes (S1, S2) then
wenzelm@17412
   386
            Vartab.update_new (w, (S2, T)) tye
wenzelm@14790
   387
          else if Sorts.sort_le classes (S2, S1) then
wenzelm@17412
   388
            Vartab.update_new (v, (S1, U)) tye
wenzelm@2964
   389
          else
wenzelm@14790
   390
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
wenzelm@17412
   391
              Vartab.update_new (v, (S1, S)) (Vartab.update_new (w, (S2, S)) tye)
wenzelm@2964
   392
            end
wenzelm@2964
   393
      | (TVar (v, S), T) =>
wenzelm@2964
   394
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   395
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   396
      | (T, TVar (v, S)) =>
wenzelm@2964
   397
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   398
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   399
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   400
          if a <> b then raise TUNIFY
wenzelm@16885
   401
          else unifs (Ts, Us) tye
wenzelm@16885
   402
      | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16885
   403
    and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
wenzelm@16885
   404
      | unifs _ tye = tye;
wenzelm@16885
   405
  in (unif TU tyenv, ! tyvar_count) end;
clasohm@0
   406
wenzelm@16946
   407
(*purely structural unification*)
wenzelm@16946
   408
fun raw_unify (ty1, ty2) tye =
wenzelm@16946
   409
  (case (devar tye ty1, devar tye ty2) of
wenzelm@16946
   410
    (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@16946
   411
      if eq_ix (v, w) then
wenzelm@16946
   412
        if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@17412
   413
      else Vartab.update_new (w, (S2, T)) tye
wenzelm@16946
   414
  | (TVar (v, S), T) =>
wenzelm@16946
   415
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   416
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   417
  | (T, TVar (v, S)) =>
wenzelm@16946
   418
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   419
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   420
  | (Type (a, Ts), Type (b, Us)) =>
wenzelm@16946
   421
      if a <> b then raise TUNIFY
wenzelm@16946
   422
      else raw_unifys (Ts, Us) tye
wenzelm@16946
   423
  | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16946
   424
and raw_unifys (T :: Ts, U :: Us) tye = raw_unifys (Ts, Us) (raw_unify (T, U) tye)
wenzelm@16946
   425
  | raw_unifys _ tye = tye;
wenzelm@16946
   426
wenzelm@17804
   427
(*fast unification filter*)
wenzelm@17804
   428
fun could_unify (Type (a, Ts), Type (b, Us)) = a = b andalso could_unifys (Ts, Us)
wenzelm@17804
   429
  | could_unify (TFree (a, _), TFree (b, _)) = a = b
wenzelm@17804
   430
  | could_unify (TVar _, _) = true
wenzelm@17804
   431
  | could_unify (_, TVar _) = true
wenzelm@17804
   432
  | could_unify _ = false
wenzelm@17804
   433
and could_unifys (T :: Ts, U :: Us) = could_unify (T, U) andalso could_unifys (Ts, Us)
wenzelm@17804
   434
  | could_unifys _ = true;
wenzelm@450
   435
wenzelm@17804
   436
wenzelm@17804
   437
(*equality with respect to a type environment*)
berghofe@16650
   438
fun eq_type tye (T, T') =
wenzelm@16885
   439
  (case (devar tye T, devar tye T') of
berghofe@16650
   440
     (Type (s, Ts), Type (s', Ts')) =>
berghofe@16650
   441
       s = s' andalso ListPair.all (eq_type tye) (Ts, Ts')
berghofe@16650
   442
   | (U, U') => U = U');
berghofe@16650
   443
wenzelm@450
   444
clasohm@0
   445
wenzelm@14790
   446
(** extend and merge type signatures **)
wenzelm@14790
   447
wenzelm@14790
   448
(* arities *)
wenzelm@14790
   449
wenzelm@14790
   450
local
nipkow@1435
   451
wenzelm@14790
   452
fun err_decl t decl = error ("Illegal " ^ str_of_decl decl ^ ": " ^ quote t);
wenzelm@14830
   453
skalberg@15531
   454
fun for_classes _ NONE = ""
skalberg@15531
   455
  | for_classes pp (SOME (c1, c2)) =
wenzelm@14830
   456
      " for classes " ^ Pretty.string_of_classrel pp [c1, c2];
wenzelm@3790
   457
wenzelm@14830
   458
fun err_conflict pp t cc (c, Ss) (c', Ss') =
wenzelm@14830
   459
  error ("Conflict of type arities" ^ for_classes pp cc ^ ":\n  " ^
wenzelm@14830
   460
    Pretty.string_of_arity pp (t, Ss, [c]) ^ " and\n  " ^
wenzelm@14830
   461
    Pretty.string_of_arity pp (t, Ss', [c']));
wenzelm@14790
   462
wenzelm@14830
   463
fun coregular pp C t (c, Ss) ars =
wenzelm@3790
   464
  let
wenzelm@14790
   465
    fun conflict (c', Ss') =
wenzelm@14790
   466
      if Sorts.class_le C (c, c') andalso not (Sorts.sorts_le C (Ss, Ss')) then
skalberg@15531
   467
        SOME ((c, c'), (c', Ss'))
wenzelm@14790
   468
      else if Sorts.class_le C (c', c) andalso not (Sorts.sorts_le C (Ss', Ss)) then
skalberg@15531
   469
        SOME ((c', c), (c', Ss'))
skalberg@15531
   470
      else NONE;
wenzelm@14790
   471
  in
wenzelm@14790
   472
    (case Library.get_first conflict ars of
skalberg@15531
   473
      SOME ((c1, c2), (c', Ss')) => err_conflict pp t (SOME (c1, c2)) (c, Ss) (c', Ss')
skalberg@15531
   474
    | NONE => (c, Ss) :: ars)
wenzelm@14790
   475
  end;
wenzelm@3790
   476
wenzelm@16340
   477
fun insert pp C t (c, Ss) ars =
wenzelm@17184
   478
  (case AList.lookup (op =) ars c of
skalberg@15531
   479
    NONE => coregular pp C t (c, Ss) ars
skalberg@15531
   480
  | SOME Ss' =>
wenzelm@14790
   481
      if Sorts.sorts_le C (Ss, Ss') then ars
wenzelm@14790
   482
      else if Sorts.sorts_le C (Ss', Ss)
wenzelm@14830
   483
      then coregular pp C t (c, Ss) (ars \ (c, Ss'))
skalberg@15531
   484
      else err_conflict pp t NONE (c, Ss) (c, Ss'));
wenzelm@2587
   485
wenzelm@14790
   486
fun complete C (c, Ss) = map (rpair Ss) (Graph.all_succs C [c]);
wenzelm@3790
   487
wenzelm@16340
   488
fun insert_arities pp classes (t, ars) arities =
wenzelm@14790
   489
  let val ars' =
wenzelm@17412
   490
    Symtab.lookup_multi arities t
wenzelm@16340
   491
    |> fold_rev (fold_rev (insert pp classes t)) (map (complete classes) ars)
wenzelm@17412
   492
  in Symtab.update (t, ars') arities end;
wenzelm@3790
   493
wenzelm@16444
   494
fun insert_table pp classes = Symtab.fold (fn (t, ars) =>
wenzelm@16444
   495
  insert_arities pp classes (t, map (apsnd (map (Sorts.norm_sort classes))) ars));
wenzelm@14790
   496
wenzelm@14790
   497
in
wenzelm@2587
   498
wenzelm@16370
   499
fun add_arities pp decls tsig = tsig |> map_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   500
  let
wenzelm@14790
   501
    fun prep (t, Ss, S) =
wenzelm@17756
   502
      (case Symtab.lookup (snd types) t of
skalberg@15531
   503
        SOME (LogicalType n, _) =>
wenzelm@14790
   504
          if length Ss = n then
wenzelm@14790
   505
            (t, map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@14790
   506
              handle TYPE (msg, _, _) => error msg
wenzelm@14790
   507
          else error (bad_nargs t)
skalberg@15531
   508
      | SOME (decl, _) => err_decl t decl
skalberg@15531
   509
      | NONE => error (undecl_type t));
wenzelm@4603
   510
wenzelm@14790
   511
    val ars = decls |> map ((fn (t, Ss, S) => (t, map (fn c => (c, Ss)) S)) o prep);
wenzelm@17756
   512
    val arities' = fold (insert_arities pp (snd classes)) ars arities;
wenzelm@14790
   513
  in (classes, default, types, arities') end);
wenzelm@12528
   514
wenzelm@14830
   515
fun rebuild_arities pp classes arities =
wenzelm@16444
   516
  Symtab.empty
wenzelm@16444
   517
  |> insert_table pp classes arities;
wenzelm@14790
   518
wenzelm@14830
   519
fun merge_arities pp classes (arities1, arities2) =
wenzelm@16444
   520
  Symtab.empty
wenzelm@16444
   521
  |> insert_table pp classes arities1
wenzelm@16444
   522
  |> insert_table pp classes arities2;
wenzelm@14790
   523
wenzelm@14790
   524
end;
wenzelm@4603
   525
wenzelm@4603
   526
wenzelm@14790
   527
(* classes *)
wenzelm@14790
   528
wenzelm@14790
   529
local
clasohm@0
   530
wenzelm@14790
   531
fun err_dup_classes cs =
wenzelm@14790
   532
  error ("Duplicate declaration of class(es): " ^ commas_quote cs);
wenzelm@14790
   533
wenzelm@14830
   534
fun err_cyclic_classes pp css =
wenzelm@14790
   535
  error (cat_lines (map (fn cs =>
wenzelm@14830
   536
    "Cycle in class relation: " ^ Pretty.string_of_classrel pp cs) css));
wenzelm@14790
   537
wenzelm@16370
   538
fun add_class pp naming (c, cs) tsig =
wenzelm@16370
   539
  tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   540
    let
wenzelm@16370
   541
      val c' = NameSpace.full naming c;
wenzelm@16370
   542
      val cs' = map (cert_class tsig) cs
wenzelm@16370
   543
        handle TYPE (msg, _, _) => error msg;
wenzelm@16370
   544
      val space' = space |> NameSpace.declare naming c';
wenzelm@16370
   545
      val classes' = classes |> Graph.new_node (c', stamp ())
wenzelm@16370
   546
        handle Graph.DUP dup => err_dup_classes [dup];
wenzelm@16370
   547
      val classes'' = classes' |> fold Graph.add_edge_trans_acyclic (map (pair c') cs')
wenzelm@16370
   548
        handle Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   549
    in ((space', classes''), default, types, arities) end);
wenzelm@2964
   550
wenzelm@14790
   551
in
clasohm@0
   552
wenzelm@16370
   553
val add_classes = fold oo add_class;
wenzelm@14790
   554
wenzelm@16370
   555
fun add_classrel pp ps tsig =
wenzelm@16370
   556
  tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   557
    let
wenzelm@16370
   558
      val ps' = map (pairself (cert_class tsig)) ps
wenzelm@16370
   559
        handle TYPE (msg, _, _) => error msg;
wenzelm@16370
   560
      val classes' = classes |> fold Graph.add_edge_trans_acyclic ps'
wenzelm@16370
   561
        handle Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   562
      val default' = default |> Sorts.norm_sort classes';
wenzelm@16370
   563
      val arities' = arities |> rebuild_arities pp classes';
wenzelm@16370
   564
    in ((space, classes'), default', types, arities') end);
wenzelm@16370
   565
wenzelm@16370
   566
fun merge_classes pp ((space1, classes1), (space2, classes2)) =
wenzelm@14790
   567
  let
wenzelm@16370
   568
    val space = NameSpace.merge (space1, space2);
wenzelm@16370
   569
    val classes =
wenzelm@16370
   570
      Graph.merge_trans_acyclic (op =) (classes1, classes2)
wenzelm@16370
   571
        handle Graph.DUPS cs => err_dup_classes cs
wenzelm@16370
   572
          | Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16946
   573
  in (space, classes) end;
wenzelm@14790
   574
wenzelm@14790
   575
end;
wenzelm@14790
   576
wenzelm@16370
   577
fun hide_classes fully cs = map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   578
  ((fold (NameSpace.hide fully) cs space, classes), default, types, arities));
wenzelm@16370
   579
wenzelm@14790
   580
wenzelm@14790
   581
(* default sort *)
wenzelm@14790
   582
wenzelm@16370
   583
fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types, arities) =>
wenzelm@14790
   584
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types, arities));
clasohm@0
   585
clasohm@0
   586
wenzelm@14790
   587
(* types *)
wenzelm@14790
   588
wenzelm@14790
   589
local
wenzelm@14790
   590
wenzelm@14790
   591
fun err_neg_args c =
wenzelm@14790
   592
  error ("Negative number of arguments in type constructor declaration: " ^ quote c);
nipkow@949
   593
wenzelm@14790
   594
fun err_in_decls c decl decl' =
wenzelm@14906
   595
  let val s = str_of_decl decl and s' = str_of_decl decl' in
wenzelm@14906
   596
    if s = s' then error ("Duplicate declaration of " ^ s ^ ": " ^ quote c)
wenzelm@14830
   597
    else error ("Conflict of " ^ s ^ " with " ^ s' ^ ": " ^ quote c)
wenzelm@14790
   598
  end;
wenzelm@14790
   599
wenzelm@16370
   600
fun new_decl naming (c, decl) (space, types) =
wenzelm@16370
   601
  let
wenzelm@16370
   602
    val c' = NameSpace.full naming c;
wenzelm@16370
   603
    val space' = NameSpace.declare naming c' space;
wenzelm@16370
   604
    val types' =
wenzelm@17412
   605
      (case Symtab.lookup types c' of
wenzelm@16370
   606
        SOME (decl', _) => err_in_decls c' decl decl'
wenzelm@17412
   607
      | NONE => Symtab.update (c', (decl, stamp ())) types);
wenzelm@16370
   608
  in (space', types') end;
wenzelm@14790
   609
wenzelm@17412
   610
fun the_decl (_, types) = fst o the o Symtab.lookup types;
wenzelm@14790
   611
wenzelm@16370
   612
fun change_types f = map_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   613
  (classes, default, f types, arities));
wenzelm@2964
   614
wenzelm@14989
   615
fun syntactic types (Type (c, Ts)) =
wenzelm@17412
   616
      (case Symtab.lookup types c of SOME (Nonterminal, _) => true | _ => false)
wenzelm@14989
   617
        orelse exists (syntactic types) Ts
wenzelm@14989
   618
  | syntactic _ _ = false;
wenzelm@14989
   619
wenzelm@16370
   620
fun add_abbrev naming (a, vs, rhs) tsig = tsig |> change_types (fn types =>
wenzelm@14790
   621
  let
wenzelm@14790
   622
    fun err msg =
wenzelm@14906
   623
      error (msg ^ "\nThe 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@14790
   627
    (case duplicates 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;