src/Pure/type.ML
author wenzelm
Fri May 21 21:26:19 2004 +0200 (2004-05-21)
changeset 14790 0d984ee030a1
parent 13666 a2730043029b
child 14830 faa4865ba1ce
permissions -rw-r--r--
major cleanup of tsig datastructures and extend/merge operations; fixes old bugs in classes/arities code; proper treatment of nonterminals and syntax-only types;
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@14790
    14
    Abbreviation of string list * typ |
wenzelm@14790
    15
    Nonterminal
wenzelm@14790
    16
  type tsig
wenzelm@14790
    17
  val rep_tsig: tsig ->
wenzelm@14790
    18
   {classes: Sorts.classes,
wenzelm@14790
    19
    default: sort,
wenzelm@14790
    20
    types: (decl * stamp) Symtab.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@14790
    35
  val norm_typ: tsig -> typ -> typ
wenzelm@14790
    36
  val cert_typ: tsig -> typ -> typ
wenzelm@14790
    37
  val cert_typ_syntax: tsig -> typ -> typ
wenzelm@14790
    38
  val cert_typ_raw: tsig -> typ -> typ
wenzelm@14790
    39
wenzelm@14790
    40
  (*special treatment of type vars*)
wenzelm@14790
    41
  val strip_sorts: typ -> typ
wenzelm@621
    42
  val no_tvars: typ -> typ
wenzelm@621
    43
  val varifyT: typ -> typ
wenzelm@621
    44
  val unvarifyT: typ -> typ
wenzelm@12501
    45
  val varify: term * string list -> term * (string * indexname) list
wenzelm@10495
    46
  val freeze_thaw_type : typ -> typ * (typ -> typ)
paulson@3411
    47
  val freeze_thaw : term -> term * (term -> term)
wenzelm@2964
    48
wenzelm@14790
    49
  (*matching and unification*)
wenzelm@14790
    50
  val inst_term_tvars: tsig -> (indexname * typ) list -> term -> term
wenzelm@14790
    51
  val inst_typ_tvars: tsig -> (indexname * typ) list -> typ -> typ
wenzelm@2964
    52
  exception TYPE_MATCH
wenzelm@14790
    53
  val typ_match: tsig -> typ Vartab.table * (typ * typ) -> typ Vartab.table
wenzelm@14790
    54
  val typ_instance: tsig -> typ * typ -> bool
wenzelm@2964
    55
  exception TUNIFY
wenzelm@14790
    56
  val unify: tsig -> typ Vartab.table * int -> typ * typ -> typ Vartab.table * int
wenzelm@450
    57
  val raw_unify: typ * typ -> bool
clasohm@0
    58
wenzelm@14790
    59
  (*extend and merge type signatures*)
wenzelm@14790
    60
  val add_classes: (class * class list) list -> tsig -> tsig
wenzelm@14790
    61
  val add_classrel: (class * class) list -> tsig -> tsig
wenzelm@14790
    62
  val set_defsort: sort -> tsig -> tsig
wenzelm@14790
    63
  val add_types: (string * int) list -> tsig -> tsig
wenzelm@14790
    64
  val add_abbrs: (string * string list * typ) list -> tsig -> tsig
wenzelm@14790
    65
  val add_nonterminals: string list -> tsig -> tsig
wenzelm@14790
    66
  val add_arities: (string * sort list * sort) list -> tsig -> tsig
wenzelm@14790
    67
  val merge_tsigs: tsig * tsig -> tsig
wenzelm@2964
    68
end;
wenzelm@2964
    69
wenzelm@2964
    70
structure Type: TYPE =
clasohm@0
    71
struct
clasohm@0
    72
wenzelm@14790
    73
(** type signatures and certified types **)
wenzelm@2964
    74
wenzelm@14790
    75
(* type declarations *)
wenzelm@14790
    76
wenzelm@14790
    77
datatype decl =
wenzelm@14790
    78
  LogicalType of int |
wenzelm@14790
    79
  Abbreviation of string list * typ |
wenzelm@14790
    80
  Nonterminal;
wenzelm@14790
    81
wenzelm@14790
    82
fun str_of_decl (LogicalType _) = "logical type constructor"
wenzelm@14790
    83
  | str_of_decl (Abbreviation _) = "type abbreviation"
wenzelm@14790
    84
  | str_of_decl Nonterminal = "syntactic type";
wenzelm@14790
    85
wenzelm@14790
    86
wenzelm@14790
    87
(* type tsig *)
wenzelm@14790
    88
wenzelm@14790
    89
datatype tsig =
wenzelm@14790
    90
  TSig of {
wenzelm@14790
    91
    classes: Sorts.classes,              (*declared classes with proper subclass relation*)
wenzelm@14790
    92
    default: sort,                       (*default sort on input*)
wenzelm@14790
    93
    types: (decl * stamp) Symtab.table,  (*declared types*)
wenzelm@14790
    94
    arities: Sorts.arities,              (*image specification of types wrt. sorts*)
wenzelm@14790
    95
    log_types: string list,              (*logical types sorted by number of arguments*)
wenzelm@14790
    96
    witness: (typ * sort) option};       (*witness for non-emptiness of strictest sort*)
wenzelm@14790
    97
wenzelm@14790
    98
fun rep_tsig (TSig comps) = comps;
wenzelm@14790
    99
wenzelm@14790
   100
fun make_tsig (classes, default, types, arities, log_types, witness) =
wenzelm@14790
   101
  TSig {classes = classes, default = default, types = types, arities = arities,
wenzelm@14790
   102
    log_types = log_types, witness = witness};
wenzelm@14790
   103
wenzelm@14790
   104
fun map_tsig f (TSig {classes, default, types, arities, log_types, witness}) =
wenzelm@14790
   105
  make_tsig (f (classes, default, types, arities, log_types, witness));
wenzelm@14790
   106
wenzelm@14790
   107
fun build_tsig (classes, default, types, arities) =
wenzelm@14790
   108
  let
wenzelm@14790
   109
    fun add_log_type (ts, (c, (LogicalType n, _))) = (c, n) :: ts
wenzelm@14790
   110
      | add_log_type (ts, _) = ts;
wenzelm@14790
   111
    val log_types =
wenzelm@14790
   112
      Symtab.foldl add_log_type ([], types)
wenzelm@14790
   113
      |> Library.sort (Library.int_ord o pairself #2) |> map #1;
wenzelm@14790
   114
    val witness =
wenzelm@14790
   115
      (case Sorts.witness_sorts (classes, arities) log_types [] [Graph.keys classes] of
wenzelm@14790
   116
        [w] => Some w | _ => None);
wenzelm@14790
   117
  in make_tsig (classes, default, types, arities, log_types, witness) end;
wenzelm@14790
   118
wenzelm@14790
   119
fun change_tsig f (TSig {classes, default, types, arities, log_types = _, witness = _}) =
wenzelm@14790
   120
  build_tsig (f (classes, default, types, arities));
wenzelm@14790
   121
wenzelm@14790
   122
val empty_tsig = build_tsig (Graph.empty, [], Symtab.empty, Symtab.empty);
wenzelm@14790
   123
wenzelm@14790
   124
wenzelm@14790
   125
(* classes and sorts *)
wenzelm@14790
   126
wenzelm@14790
   127
fun classes (TSig {classes = C, ...}) = Graph.keys C;
wenzelm@14790
   128
fun defaultS (TSig {default, ...}) = default;
wenzelm@14790
   129
fun logical_types (TSig {log_types, ...}) = log_types;
wenzelm@14790
   130
fun universal_witness (TSig {witness, ...}) = witness;
wenzelm@14790
   131
wenzelm@14790
   132
fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq classes;
wenzelm@14790
   133
fun subsort (TSig {classes, ...}) = Sorts.sort_le classes;
wenzelm@14790
   134
fun of_sort (TSig {classes, arities, ...}) = Sorts.of_sort (classes, arities);
wenzelm@14790
   135
fun norm_sort (TSig {classes, ...}) = Sorts.norm_sort classes;
wenzelm@14790
   136
wenzelm@14790
   137
fun cert_class (TSig {classes, ...}) c =
wenzelm@14790
   138
  if can (Graph.get_node classes) c then c
wenzelm@14790
   139
  else raise TYPE ("Undeclared class: " ^ quote c, [], []);
wenzelm@14790
   140
wenzelm@14790
   141
fun cert_sort tsig = norm_sort tsig o map (cert_class tsig);
wenzelm@14790
   142
wenzelm@14790
   143
fun witness_sorts (tsig as TSig {classes, arities, log_types, ...}) =
wenzelm@14790
   144
  Sorts.witness_sorts (classes, arities) log_types;
wenzelm@14790
   145
wenzelm@14790
   146
wenzelm@14790
   147
(* certified types *)
wenzelm@14790
   148
wenzelm@14790
   149
fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
wenzelm@14790
   150
wenzelm@14790
   151
fun inst_typ tye =
wenzelm@14790
   152
  let
wenzelm@14790
   153
    fun inst (var as (v, _)) =
wenzelm@14790
   154
      (case assoc_string_int (tye, v) of
wenzelm@14790
   155
        Some U => inst_typ tye U
wenzelm@14790
   156
      | None => TVar var);
wenzelm@14790
   157
  in map_type_tvar inst end;
wenzelm@14790
   158
wenzelm@14790
   159
(*expand type abbreviations and normalize sorts*)
wenzelm@14790
   160
fun norm_typ (tsig as TSig {types, ...}) ty =
wenzelm@14790
   161
  let
wenzelm@14790
   162
    val idx = Term.maxidx_of_typ ty + 1;
wenzelm@14790
   163
wenzelm@14790
   164
    fun norm (Type (a, Ts)) =
wenzelm@14790
   165
          (case Symtab.lookup (types, a) of
wenzelm@14790
   166
            Some (Abbreviation (vs, U), _) =>
wenzelm@14790
   167
              norm (inst_typ (map (rpair idx) vs ~~ Ts) (incr_tvar idx U))
wenzelm@14790
   168
          | _ => Type (a, map norm Ts))
wenzelm@14790
   169
      | norm (TFree (x, S)) = TFree (x, norm_sort tsig S)
wenzelm@14790
   170
      | norm (TVar (xi, S)) = TVar (xi, norm_sort tsig S);
wenzelm@14790
   171
wenzelm@14790
   172
    val ty' = norm ty;
wenzelm@14790
   173
  in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
wenzelm@14790
   174
wenzelm@14790
   175
(*check validity of (not necessarily normal) type*)   (*exception TYPE*)
wenzelm@14790
   176
fun certify_typ normalize syntax tsig ty =
wenzelm@14790
   177
  let
wenzelm@14790
   178
    val TSig {types, ...} = tsig;
wenzelm@14790
   179
    fun err msg = raise TYPE (msg, [ty], []);
wenzelm@14790
   180
wenzelm@14790
   181
    fun check_sort S = (map (cert_class tsig) S; ());
wenzelm@14790
   182
wenzelm@14790
   183
    fun check_typ (Type (c, Ts)) =
wenzelm@14790
   184
          let fun nargs n = if length Ts <> n then err (bad_nargs c) else () in
wenzelm@14790
   185
            (case Symtab.lookup (types, c) of
wenzelm@14790
   186
              Some (LogicalType n, _) => nargs n
wenzelm@14790
   187
            | Some (Abbreviation (vs, _), _) => nargs (length vs)
wenzelm@14790
   188
            | Some (Nonterminal, _) => nargs 0
wenzelm@14790
   189
            | None => err ("Undeclared type constructor: " ^ quote c));
wenzelm@14790
   190
            seq check_typ Ts
wenzelm@14790
   191
          end
wenzelm@14790
   192
    | check_typ (TFree (_, S)) = check_sort S
wenzelm@14790
   193
    | check_typ (TVar ((x, i), S)) =
wenzelm@14790
   194
        if i < 0 then err ("Malformed type variable: " ^ quote (Term.string_of_vname (x, i)))
wenzelm@14790
   195
        else check_sort S;
wenzelm@14790
   196
wenzelm@14790
   197
    fun no_syntax (Type (c, Ts)) =
wenzelm@14790
   198
          (case Symtab.lookup (types, c) of
wenzelm@14790
   199
            Some (Nonterminal, _) =>
wenzelm@14790
   200
              err ("Illegal occurrence of syntactic type: " ^ quote c)
wenzelm@14790
   201
          | _ => seq no_syntax Ts)
wenzelm@14790
   202
      | no_syntax _ = ();
wenzelm@14790
   203
wenzelm@14790
   204
    val _ = check_typ ty;
wenzelm@14790
   205
    val ty' = if normalize orelse not syntax then norm_typ tsig ty else ty;
wenzelm@14790
   206
    val _ = if not syntax then no_syntax ty' else ();
wenzelm@14790
   207
  in ty' end;
wenzelm@14790
   208
wenzelm@14790
   209
val cert_typ         = certify_typ true false;
wenzelm@14790
   210
val cert_typ_syntax  = certify_typ true true;
wenzelm@14790
   211
val cert_typ_raw     = certify_typ false true;
wenzelm@14790
   212
wenzelm@14790
   213
wenzelm@14790
   214
wenzelm@14790
   215
(** special treatment of type vars **)
wenzelm@14790
   216
wenzelm@14790
   217
(* strip_sorts *)
wenzelm@14790
   218
wenzelm@14790
   219
fun strip_sorts (Type (a, Ts)) = Type (a, map strip_sorts Ts)
wenzelm@14790
   220
  | strip_sorts (TFree (x, _)) = TFree (x, [])
wenzelm@14790
   221
  | strip_sorts (TVar (xi, _)) = TVar (xi, []);
wenzelm@14790
   222
wenzelm@14790
   223
wenzelm@14790
   224
(* no_tvars *)
wenzelm@621
   225
wenzelm@621
   226
fun no_tvars T =
wenzelm@12501
   227
  (case typ_tvars T of [] => T
wenzelm@12501
   228
  | vs => raise TYPE ("Illegal schematic type variable(s): " ^
wenzelm@14790
   229
      commas (map (Term.string_of_vname o #1) vs), [T], []));
wenzelm@621
   230
wenzelm@7641
   231
wenzelm@2964
   232
(* varify, unvarify *)
wenzelm@621
   233
wenzelm@2964
   234
val varifyT = map_type_tfree (fn (a, S) => TVar ((a, 0), S));
wenzelm@2964
   235
wenzelm@621
   236
fun unvarifyT (Type (a, Ts)) = Type (a, map unvarifyT Ts)
wenzelm@621
   237
  | unvarifyT (TVar ((a, 0), S)) = TFree (a, S)
wenzelm@621
   238
  | unvarifyT T = T;
wenzelm@621
   239
wenzelm@621
   240
fun varify (t, fixed) =
wenzelm@621
   241
  let
wenzelm@621
   242
    val fs = add_term_tfree_names (t, []) \\ fixed;
wenzelm@621
   243
    val ixns = add_term_tvar_ixns (t, []);
wenzelm@12501
   244
    val fmap = fs ~~ map (rpair 0) (variantlist (fs, map #1 ixns))
wenzelm@2964
   245
    fun thaw (f as (a, S)) =
wenzelm@2964
   246
      (case assoc (fmap, a) of
wenzelm@2964
   247
        None => TFree f
wenzelm@12501
   248
      | Some b => TVar (b, S));
wenzelm@12501
   249
  in (map_term_types (map_type_tfree thaw) t, fmap) end;
wenzelm@2964
   250
wenzelm@2964
   251
wenzelm@7641
   252
(* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
paulson@3411
   253
wenzelm@7641
   254
local
wenzelm@7641
   255
wenzelm@7641
   256
fun new_name (ix, (pairs,used)) =
paulson@3411
   257
      let val v = variant used (string_of_indexname ix)
paulson@3411
   258
      in  ((ix,v)::pairs, v::used)  end;
wenzelm@621
   259
wenzelm@7641
   260
fun freeze_one alist (ix,sort) =
wenzelm@3790
   261
  TFree (the (assoc (alist, ix)), sort)
wenzelm@4142
   262
    handle OPTION =>
wenzelm@3790
   263
      raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
wenzelm@2964
   264
wenzelm@7641
   265
fun thaw_one alist (a,sort) = TVar (the (assoc (alist,a)), sort)
wenzelm@4142
   266
      handle OPTION => TFree(a,sort);
wenzelm@416
   267
wenzelm@10495
   268
in
wenzelm@10495
   269
wenzelm@10495
   270
(*this sort of code could replace unvarifyT*)
wenzelm@7641
   271
fun freeze_thaw_type T =
wenzelm@7641
   272
  let
wenzelm@7641
   273
    val used = add_typ_tfree_names (T, [])
wenzelm@7641
   274
    and tvars = map #1 (add_typ_tvars (T, []));
wenzelm@7641
   275
    val (alist, _) = foldr new_name (tvars, ([], used));
wenzelm@7641
   276
  in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
wenzelm@7641
   277
paulson@3411
   278
fun freeze_thaw t =
wenzelm@7641
   279
  let
wenzelm@7641
   280
    val used = it_term_types add_typ_tfree_names (t, [])
wenzelm@7641
   281
    and tvars = map #1 (it_term_types add_typ_tvars (t, []));
wenzelm@7641
   282
    val (alist, _) = foldr new_name (tvars, ([], used));
wenzelm@7641
   283
  in
wenzelm@7641
   284
    (case alist of
wenzelm@7641
   285
      [] => (t, fn x => x) (*nothing to do!*)
wenzelm@7641
   286
    | _ => (map_term_types (map_type_tvar (freeze_one alist)) t,
wenzelm@7641
   287
      map_term_types (map_type_tfree (thaw_one (map swap alist)))))
wenzelm@7641
   288
  end;
wenzelm@7641
   289
wenzelm@7641
   290
end;
wenzelm@7641
   291
wenzelm@256
   292
wenzelm@256
   293
wenzelm@14790
   294
(** matching and unification of types **)
wenzelm@8899
   295
wenzelm@14790
   296
(* instantiation *)
wenzelm@256
   297
wenzelm@14790
   298
fun type_of_sort tsig (T, S) =
wenzelm@14790
   299
  if of_sort tsig (T, S) then T
wenzelm@3790
   300
  else raise TYPE ("Type not of sort " ^ Sorts.str_of_sort S, [T], []);
clasohm@0
   301
wenzelm@14790
   302
fun inst_typ_tvars tsig tye =
wenzelm@14790
   303
  let
wenzelm@14790
   304
    fun inst (var as (v, S)) =
wenzelm@14790
   305
      (case assoc_string_int (tye, v) of
wenzelm@14790
   306
        Some U => type_of_sort tsig (U, S)
wenzelm@14790
   307
      | None => TVar var);
nipkow@949
   308
  in map_type_tvar inst end;
clasohm@0
   309
wenzelm@14790
   310
fun inst_term_tvars _ [] t = t
wenzelm@14790
   311
  | inst_term_tvars tsig tye t = map_term_types (inst_typ_tvars tsig tye) t;
clasohm@0
   312
clasohm@0
   313
wenzelm@14790
   314
(* matching *)
clasohm@0
   315
wenzelm@2964
   316
exception TYPE_MATCH;
clasohm@0
   317
wenzelm@2964
   318
fun typ_match tsig =
wenzelm@2964
   319
  let
wenzelm@2964
   320
    fun match (subs, (TVar (v, S), T)) =
berghofe@8406
   321
          (case Vartab.lookup (subs, v) of
wenzelm@14790
   322
            None => (Vartab.update_new ((v, type_of_sort tsig (T, S)), subs)
wenzelm@2964
   323
              handle TYPE _ => raise TYPE_MATCH)
wenzelm@2964
   324
          | Some U => if U = T then subs else raise TYPE_MATCH)
wenzelm@2964
   325
      | match (subs, (Type (a, Ts), Type (b, Us))) =
wenzelm@2964
   326
          if a <> b then raise TYPE_MATCH
wenzelm@2964
   327
          else foldl match (subs, Ts ~~ Us)
wenzelm@2964
   328
      | match (subs, (TFree x, TFree y)) =
wenzelm@2964
   329
          if x = y then subs else raise TYPE_MATCH
wenzelm@2964
   330
      | match _ = raise TYPE_MATCH;
wenzelm@2964
   331
  in match end;
clasohm@0
   332
wenzelm@14790
   333
fun typ_instance tsig (T, U) =
berghofe@8406
   334
  (typ_match tsig (Vartab.empty, (U, T)); 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
wenzelm@2964
   346
      | occ (TVar (w, _)) =
wenzelm@2964
   347
          eq_ix (v, w) orelse
berghofe@8406
   348
            (case Vartab.lookup (tye, w) of
wenzelm@2964
   349
              None => false
wenzelm@2964
   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@2964
   354
fun devar (T as TVar (v, _), tye) =
berghofe@8406
   355
      (case  Vartab.lookup (tye, v) of
wenzelm@2964
   356
        Some U => devar (U, tye)
wenzelm@2964
   357
      | None => T)
wenzelm@256
   358
  | devar (T, tye) = T;
clasohm@0
   359
wenzelm@14790
   360
fun unify (tsig as TSig {classes, arities, ...}) (tyenv, maxidx) TU =
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@2964
   368
    fun meet ((_, []), tye) = tye
wenzelm@2964
   369
      | meet ((TVar (xi, S'), S), tye) =
wenzelm@14790
   370
          if Sorts.sort_le classes (S', S) then tye
berghofe@13666
   371
          else Vartab.update_new ((xi,
wenzelm@14790
   372
            gen_tyvar (Sorts.inter_sort classes (S', S))), tye)
wenzelm@2964
   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@2964
   376
      | meet ((Type (a, Ts), S), tye) = meets ((Ts, mg_domain a S), tye)
wenzelm@2964
   377
    and meets (([], []), tye) = tye
wenzelm@2964
   378
      | meets ((T :: Ts, S :: Ss), tye) =
wenzelm@2964
   379
          meets ((Ts, Ss), meet ((devar (T, tye), S), tye))
wenzelm@2964
   380
      | meets _ = sys_error "meets";
wenzelm@2964
   381
wenzelm@2964
   382
    fun unif ((ty1, ty2), tye) =
wenzelm@2964
   383
      (case (devar (ty1, tye), devar (ty2, tye)) of
wenzelm@2964
   384
        (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@2964
   385
          if eq_ix (v, w) then tye
wenzelm@14790
   386
          else if Sorts.sort_le classes (S1, S2) then
berghofe@13666
   387
            Vartab.update_new ((w, T), tye)
wenzelm@14790
   388
          else if Sorts.sort_le classes (S2, S1) then
berghofe@13666
   389
            Vartab.update_new ((v, U), tye)
wenzelm@2964
   390
          else
wenzelm@14790
   391
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
berghofe@13666
   392
              Vartab.update_new ((v, S), Vartab.update_new ((w, S), tye))
wenzelm@2964
   393
            end
wenzelm@2964
   394
      | (TVar (v, S), T) =>
wenzelm@2964
   395
          if occurs v tye T then raise TUNIFY
berghofe@13666
   396
          else meet ((T, S), Vartab.update_new ((v, T), tye))
wenzelm@2964
   397
      | (T, TVar (v, S)) =>
wenzelm@2964
   398
          if occurs v tye T then raise TUNIFY
berghofe@13666
   399
          else meet ((T, S), Vartab.update_new ((v, T), tye))
wenzelm@2964
   400
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   401
          if a <> b then raise TUNIFY
wenzelm@2964
   402
          else foldr unif (Ts ~~ Us, tye)
wenzelm@2964
   403
      | (T, U) => if T = U then tye else raise TUNIFY);
wenzelm@12528
   404
  in (unif (TU, tyenv), ! tyvar_count) end;
clasohm@0
   405
wenzelm@14790
   406
(*purely structural unification *)
wenzelm@450
   407
fun raw_unify (ty1, ty2) =
wenzelm@14790
   408
  (unify empty_tsig (Vartab.empty, 0) (strip_sorts ty1, strip_sorts ty2); true)
wenzelm@450
   409
    handle TUNIFY => false;
wenzelm@450
   410
wenzelm@450
   411
clasohm@0
   412
wenzelm@14790
   413
(** extend and merge type signatures **)
wenzelm@14790
   414
wenzelm@14790
   415
(* arities *)
wenzelm@14790
   416
wenzelm@14790
   417
local
nipkow@1435
   418
wenzelm@14790
   419
fun err_decl t decl = error ("Illegal " ^ str_of_decl decl ^ ": " ^ quote t);
wenzelm@14790
   420
fun err_undecl t = error ("Undeclared type constructor: " ^ quote t);
wenzelm@3790
   421
wenzelm@14790
   422
fun err_conflict t (c1, c2) (c, Ss) (c', Ss') =
wenzelm@14790
   423
  error ("Conflict of type arities for classes " ^ quote c1 ^ " < " ^ quote c2 ^ ":\n  " ^
wenzelm@14790
   424
    Sorts.str_of_arity (t, Ss, [c]) ^ " and\n  " ^
wenzelm@14790
   425
    Sorts.str_of_arity (t, Ss', [c']));
wenzelm@14790
   426
wenzelm@14790
   427
fun coregular C t (c, Ss) ars =
wenzelm@3790
   428
  let
wenzelm@14790
   429
    fun conflict (c', Ss') =
wenzelm@14790
   430
      if Sorts.class_le C (c, c') andalso not (Sorts.sorts_le C (Ss, Ss')) then
wenzelm@14790
   431
        Some ((c, c'), (c', Ss'))
wenzelm@14790
   432
      else if Sorts.class_le C (c', c) andalso not (Sorts.sorts_le C (Ss', Ss)) then
wenzelm@14790
   433
        Some ((c', c), (c', Ss'))
wenzelm@14790
   434
      else None;
wenzelm@14790
   435
  in
wenzelm@14790
   436
    (case Library.get_first conflict ars of
wenzelm@14790
   437
      Some ((c1, c2), (c', Ss')) => err_conflict t (c1, c2) (c, Ss) (c', Ss')
wenzelm@14790
   438
    | None => (c, Ss) :: ars)
wenzelm@14790
   439
  end;
wenzelm@3790
   440
wenzelm@14790
   441
fun insert C t ((c, Ss), ars) =
wenzelm@14790
   442
  (case assoc_string (ars, c) of
wenzelm@14790
   443
    None => coregular C t (c, Ss) ars
wenzelm@14790
   444
  | Some Ss' =>
wenzelm@14790
   445
      if Sorts.sorts_le C (Ss, Ss') then ars
wenzelm@14790
   446
      else if Sorts.sorts_le C (Ss', Ss)
wenzelm@14790
   447
      then coregular C t (c, Ss) (ars \ (c, Ss'))
wenzelm@14790
   448
      else coregular C t (c, Ss) ars);
wenzelm@2587
   449
wenzelm@14790
   450
fun complete C (c, Ss) = map (rpair Ss) (Graph.all_succs C [c]);
wenzelm@3790
   451
wenzelm@14790
   452
fun insert_arities classes (arities, (t, ars)) =
wenzelm@14790
   453
  let val ars' =
wenzelm@14790
   454
    Symtab.lookup_multi (arities, t)
wenzelm@14790
   455
    |> curry (foldr (insert classes t)) (flat (map (complete classes) ars))
wenzelm@14790
   456
  in Symtab.update ((t, ars'), arities) end;
wenzelm@3790
   457
wenzelm@14790
   458
fun insert_table classes = Symtab.foldl (fn (arities, (t, ars)) =>
wenzelm@14790
   459
  insert_arities classes (arities, (t, map (apsnd (map (Sorts.norm_sort classes))) ars)));
wenzelm@14790
   460
wenzelm@14790
   461
in
wenzelm@2587
   462
wenzelm@14790
   463
fun add_arities decls tsig = tsig |> change_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   464
  let
wenzelm@14790
   465
    fun prep (t, Ss, S) =
wenzelm@14790
   466
      (case Symtab.lookup (types, t) of
wenzelm@14790
   467
        Some (LogicalType n, _) =>
wenzelm@14790
   468
          if length Ss = n then
wenzelm@14790
   469
            (t, map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@14790
   470
              handle TYPE (msg, _, _) => error msg
wenzelm@14790
   471
          else error (bad_nargs t)
wenzelm@14790
   472
      | Some (decl, _) => err_decl t decl
wenzelm@14790
   473
      | None => err_undecl t);
wenzelm@4603
   474
wenzelm@14790
   475
    val ars = decls |> map ((fn (t, Ss, S) => (t, map (fn c => (c, Ss)) S)) o prep);
wenzelm@14790
   476
    val arities' = foldl (insert_arities classes) (arities, ars);
wenzelm@14790
   477
  in (classes, default, types, arities') end);
wenzelm@12528
   478
wenzelm@14790
   479
fun rebuild_arities classes arities =
wenzelm@14790
   480
  insert_table classes (Symtab.empty, arities);
wenzelm@14790
   481
wenzelm@14790
   482
fun merge_arities classes (arities1, arities2) =
wenzelm@14790
   483
  insert_table classes (insert_table classes (Symtab.empty, arities1), arities2);
wenzelm@14790
   484
wenzelm@14790
   485
end;
wenzelm@4603
   486
wenzelm@4603
   487
wenzelm@14790
   488
(* classes *)
wenzelm@14790
   489
wenzelm@14790
   490
local
clasohm@0
   491
wenzelm@14790
   492
fun err_dup_classes cs =
wenzelm@14790
   493
  error ("Duplicate declaration of class(es): " ^ commas_quote cs);
wenzelm@14790
   494
wenzelm@14790
   495
fun err_cyclic_classes css =
wenzelm@14790
   496
  error (cat_lines (map (fn cs =>
wenzelm@14790
   497
    "Cycle in class relation: " ^ space_implode " < " (map quote cs)) css));
wenzelm@14790
   498
wenzelm@14790
   499
fun add_class (c, cs) tsig = tsig |> change_tsig (fn (classes, default, types, arities) =>
wenzelm@2964
   500
  let
wenzelm@14790
   501
    val cs' = map (cert_class tsig) cs
wenzelm@14790
   502
      handle TYPE (msg, _, _) => error msg;
wenzelm@14790
   503
    val classes' = classes |> Graph.new_node (c, stamp ())
wenzelm@14790
   504
      handle Graph.DUP d => err_dup_classes [d];
wenzelm@14790
   505
    val classes'' = classes' |> fold Graph.add_edge_trans_acyclic (map (pair c) cs')
wenzelm@14790
   506
      handle Graph.CYCLES css => err_cyclic_classes css;
wenzelm@14790
   507
  in (classes'', default, types, arities) end);
wenzelm@2964
   508
wenzelm@14790
   509
in
clasohm@0
   510
wenzelm@14790
   511
val add_classes = fold add_class;
wenzelm@14790
   512
wenzelm@14790
   513
fun add_classrel ps tsig = tsig |> change_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   514
  let
wenzelm@14790
   515
    val ps' = map (pairself (cert_class tsig)) ps
wenzelm@14790
   516
      handle TYPE (msg, _, _) => error msg;
wenzelm@14790
   517
    val classes' = classes |> fold Graph.add_edge_trans_acyclic ps'
wenzelm@14790
   518
      handle Graph.CYCLES css => err_cyclic_classes css;
wenzelm@14790
   519
    val default' = default |> Sorts.norm_sort classes';
wenzelm@14790
   520
    val arities' = arities |> rebuild_arities classes';
wenzelm@14790
   521
  in (classes', default', types, arities') end);
wenzelm@14790
   522
wenzelm@14790
   523
fun merge_classes CC = Graph.merge_trans_acyclic (op =) CC
wenzelm@14790
   524
  handle Graph.DUPS cs => err_dup_classes cs
wenzelm@14790
   525
    | Graph.CYCLES css => err_cyclic_classes css;
wenzelm@14790
   526
wenzelm@14790
   527
end;
wenzelm@14790
   528
wenzelm@14790
   529
wenzelm@14790
   530
(* default sort *)
wenzelm@14790
   531
wenzelm@14790
   532
fun set_defsort S tsig = tsig |> change_tsig (fn (classes, _, types, arities) =>
wenzelm@14790
   533
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types, arities));
clasohm@0
   534
clasohm@0
   535
wenzelm@14790
   536
(* types *)
wenzelm@14790
   537
wenzelm@14790
   538
local
wenzelm@14790
   539
wenzelm@14790
   540
fun err_neg_args c =
wenzelm@14790
   541
  error ("Negative number of arguments in type constructor declaration: " ^ quote c);
nipkow@949
   542
wenzelm@14790
   543
fun err_in_decls c decl decl' =
wenzelm@14790
   544
  let
wenzelm@14790
   545
    val s = str_of_decl decl;
wenzelm@14790
   546
    val s' = str_of_decl decl';
wenzelm@14790
   547
  in
wenzelm@14790
   548
    if s = s' then error ("Duplicate declaration of " ^ s ^ ": " ^ quote c)
wenzelm@14790
   549
    else error ("Conflicting declarations of " ^ s ^ " with " ^ s' ^ ": " ^ quote c)
wenzelm@14790
   550
  end;
wenzelm@14790
   551
wenzelm@14790
   552
fun new_decl (c, decl) types =
wenzelm@14790
   553
  (case Symtab.lookup (types, c) of
wenzelm@14790
   554
    Some (decl', _) => err_in_decls c decl decl'
wenzelm@14790
   555
  | None => Symtab.update ((c, (decl, stamp ())), types));
wenzelm@14790
   556
wenzelm@14790
   557
fun the_decl types c = fst (the (Symtab.lookup (types, c)));
wenzelm@14790
   558
wenzelm@14790
   559
fun change_types f = change_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   560
  (classes, default, f types, arities));
wenzelm@2964
   561
wenzelm@14790
   562
fun add_abbr (a, vs, rhs) tsig = tsig |> change_types (fn types =>
wenzelm@14790
   563
  let
wenzelm@14790
   564
    fun err msg =
wenzelm@14790
   565
      error (msg ^ "\nThe error(s) above occurred in type abbreviation " ^ quote a);
wenzelm@14790
   566
    val rhs' = strip_sorts (varifyT (no_tvars (cert_typ_syntax tsig rhs)))
wenzelm@14790
   567
      handle TYPE (msg, _, _) => err msg;
wenzelm@14790
   568
  in
wenzelm@14790
   569
    (case duplicates vs of
wenzelm@14790
   570
      [] => []
wenzelm@14790
   571
    | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
wenzelm@14790
   572
    (case gen_rems (op =) (map (#1 o #1) (typ_tvars rhs'), vs) of
wenzelm@14790
   573
      [] => []
wenzelm@14790
   574
    | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
wenzelm@14790
   575
    types |> new_decl (a, Abbreviation (vs, rhs'))
wenzelm@14790
   576
  end);
clasohm@0
   577
wenzelm@14790
   578
in
wenzelm@14790
   579
wenzelm@14790
   580
fun add_types ps = change_types (fold new_decl (ps |> map (fn (c, n) =>
wenzelm@14790
   581
  if n < 0 then err_neg_args c else (c, LogicalType n))));
wenzelm@14790
   582
wenzelm@14790
   583
val add_abbrs = fold add_abbr;
wenzelm@14790
   584
val add_nonterminals = change_types o fold new_decl o map (rpair Nonterminal);
wenzelm@14790
   585
wenzelm@14790
   586
fun merge_types (types1, types2) =
wenzelm@14790
   587
  Symtab.merge Library.eq_snd (types1, types2) handle Symtab.DUPS (d :: _) =>
wenzelm@14790
   588
    err_in_decls d (the_decl types1 d) (the_decl types2 d);
wenzelm@14790
   589
wenzelm@14790
   590
end;
clasohm@0
   591
wenzelm@3790
   592
wenzelm@14790
   593
(* merge type signatures *)
wenzelm@14790
   594
wenzelm@14790
   595
fun merge_tsigs (tsig1, tsig2) =
wenzelm@14790
   596
  let
wenzelm@14790
   597
    val (TSig {classes = classes1, default = default1, types = types1, arities = arities1,
wenzelm@14790
   598
      log_types = _, witness = _}) = tsig1;
wenzelm@14790
   599
    val (TSig {classes = classes2, default = default2, types = types2, arities = arities2,
wenzelm@14790
   600
      log_types = _, witness = _}) = tsig2;
wenzelm@14790
   601
wenzelm@14790
   602
    val classes' = merge_classes (classes1, classes2);
wenzelm@14790
   603
    val default' = Sorts.inter_sort classes' (default1, default2);
wenzelm@14790
   604
    val types' = merge_types (types1, types2);
wenzelm@14790
   605
    val arities' = merge_arities classes' (arities1, arities2);
wenzelm@14790
   606
  in build_tsig (classes', default', types', arities') end;
wenzelm@14790
   607
clasohm@0
   608
end;