src/Pure/type.ML
author wenzelm
Tue Jul 19 17:21:57 2005 +0200 (2005-07-19 ago)
changeset 16885 cabcd33cde18
parent 16650 bd4f7149ba1e
child 16946 7f9a7fe413f3
permissions -rw-r--r--
tuned match, 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
berghofe@15797
    54
  val typ_match: tsig -> tyenv * (typ * typ) -> tyenv
wenzelm@14790
    55
  val typ_instance: tsig -> typ * typ -> bool
wenzelm@2964
    56
  exception TUNIFY
berghofe@15797
    57
  val unify: tsig -> tyenv * int -> typ * typ -> tyenv * int
wenzelm@450
    58
  val raw_unify: typ * typ -> bool
berghofe@16650
    59
  val eq_type: tyenv -> typ * typ -> bool
clasohm@0
    60
wenzelm@14790
    61
  (*extend and merge type signatures*)
wenzelm@16370
    62
  val add_classes: Pretty.pp -> NameSpace.naming -> (bstring * class list) list -> tsig -> tsig
wenzelm@16370
    63
  val hide_classes: bool -> string list -> tsig -> tsig
wenzelm@14830
    64
  val add_classrel: Pretty.pp -> (class * class) list -> tsig -> tsig
wenzelm@14790
    65
  val set_defsort: sort -> tsig -> tsig
wenzelm@16370
    66
  val add_types: NameSpace.naming -> (bstring * int) list -> tsig -> tsig
wenzelm@16370
    67
  val add_abbrevs: NameSpace.naming -> (string * string list * typ) list -> tsig -> tsig
wenzelm@16370
    68
  val add_nonterminals: NameSpace.naming -> string list -> tsig -> tsig
wenzelm@16370
    69
  val hide_types: bool -> string list -> tsig -> tsig
wenzelm@14830
    70
  val add_arities: Pretty.pp -> arity list -> tsig -> tsig
wenzelm@14830
    71
  val merge_tsigs: Pretty.pp -> tsig * tsig -> tsig
wenzelm@2964
    72
end;
wenzelm@2964
    73
wenzelm@2964
    74
structure Type: TYPE =
clasohm@0
    75
struct
clasohm@0
    76
wenzelm@14790
    77
(** type signatures and certified types **)
wenzelm@2964
    78
wenzelm@14790
    79
(* type declarations *)
wenzelm@14790
    80
wenzelm@14790
    81
datatype decl =
wenzelm@14790
    82
  LogicalType of int |
wenzelm@14989
    83
  Abbreviation of string list * typ * bool |
wenzelm@14790
    84
  Nonterminal;
wenzelm@14790
    85
wenzelm@14790
    86
fun str_of_decl (LogicalType _) = "logical type constructor"
wenzelm@14790
    87
  | str_of_decl (Abbreviation _) = "type abbreviation"
wenzelm@14790
    88
  | str_of_decl Nonterminal = "syntactic type";
wenzelm@14790
    89
wenzelm@14790
    90
wenzelm@14790
    91
(* type tsig *)
wenzelm@14790
    92
wenzelm@14790
    93
datatype tsig =
wenzelm@14790
    94
  TSig of {
wenzelm@16370
    95
    classes: NameSpace.T * Sorts.classes,   (*declared classes with proper subclass relation*)
wenzelm@16370
    96
    default: sort,                          (*default sort on input*)
wenzelm@16370
    97
    types: (decl * stamp) NameSpace.table,  (*declared types*)
wenzelm@16370
    98
    arities: Sorts.arities,                 (*image specification of types wrt. sorts*)
wenzelm@16370
    99
    log_types: string list,                 (*logical types sorted by number of arguments*)
wenzelm@16370
   100
    witness: (typ * sort) option};          (*witness for non-emptiness of strictest sort*)
wenzelm@14790
   101
wenzelm@14790
   102
fun rep_tsig (TSig comps) = comps;
wenzelm@14790
   103
wenzelm@14790
   104
fun make_tsig (classes, default, types, arities, log_types, witness) =
wenzelm@14790
   105
  TSig {classes = classes, default = default, types = types, arities = arities,
wenzelm@14790
   106
    log_types = log_types, witness = witness};
wenzelm@14790
   107
wenzelm@14790
   108
fun build_tsig (classes, default, types, arities) =
wenzelm@14790
   109
  let
wenzelm@14790
   110
    val log_types =
wenzelm@16444
   111
      Symtab.fold (fn (c, (LogicalType n, _)) => cons (c, n) | _ => I) (#2 types) []
wenzelm@14790
   112
      |> Library.sort (Library.int_ord o pairself #2) |> map #1;
wenzelm@14790
   113
    val witness =
wenzelm@16370
   114
      (case Sorts.witness_sorts (#2 classes, arities) log_types [] [Graph.keys (#2 classes)] of
skalberg@15531
   115
        [w] => SOME w | _ => NONE);
wenzelm@14790
   116
  in make_tsig (classes, default, types, arities, log_types, witness) end;
wenzelm@14790
   117
wenzelm@16370
   118
fun map_tsig f (TSig {classes, default, types, arities, log_types = _, witness = _}) =
wenzelm@14790
   119
  build_tsig (f (classes, default, types, arities));
wenzelm@14790
   120
wenzelm@16370
   121
val empty_tsig =
wenzelm@16370
   122
  build_tsig ((NameSpace.empty, Graph.empty), [], NameSpace.empty_table, Symtab.empty);
wenzelm@14790
   123
wenzelm@14790
   124
wenzelm@14790
   125
(* classes and sorts *)
wenzelm@14790
   126
wenzelm@16370
   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@16370
   132
fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq (#2 classes);
wenzelm@16370
   133
fun subsort (TSig {classes, ...}) = Sorts.sort_le (#2 classes);
wenzelm@16370
   134
fun of_sort (TSig {classes, arities, ...}) = Sorts.of_sort (#2 classes, arities);
wenzelm@14790
   135
wenzelm@16370
   136
fun cert_class (TSig {classes, ...}) = Sorts.certify_class (#2 classes);
wenzelm@16370
   137
fun cert_sort (TSig {classes, ...}) = Sorts.certify_sort (#2 classes);
wenzelm@14790
   138
wenzelm@14790
   139
fun witness_sorts (tsig as TSig {classes, arities, log_types, ...}) =
wenzelm@16370
   140
  Sorts.witness_sorts (#2 classes, arities) log_types;
wenzelm@14790
   141
wenzelm@14790
   142
wenzelm@14790
   143
(* certified types *)
wenzelm@14790
   144
wenzelm@14790
   145
fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
wenzelm@14830
   146
fun undecl_type c = "Undeclared type constructor: " ^ quote c;
wenzelm@14830
   147
wenzelm@14998
   148
local
wenzelm@14998
   149
wenzelm@14998
   150
fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
wenzelm@16289
   151
  | inst_typ env (T as TFree (x, _)) = if_none (Library.assoc_string (env, x)) T
wenzelm@14998
   152
  | inst_typ _ T = T;
wenzelm@14998
   153
wenzelm@14790
   154
fun certify_typ normalize syntax tsig ty =
wenzelm@14790
   155
  let
wenzelm@16370
   156
    val TSig {classes = (_, classes), types = (_, types), ...} = tsig;
wenzelm@14790
   157
    fun err msg = raise TYPE (msg, [ty], []);
wenzelm@14790
   158
wenzelm@14989
   159
    val check_syntax =
wenzelm@14989
   160
      if syntax then K ()
wenzelm@14989
   161
      else fn c => err ("Illegal occurrence of syntactic type: " ^ quote c);
wenzelm@14989
   162
wenzelm@14989
   163
    fun cert (T as Type (c, Ts)) =
wenzelm@14989
   164
          let
wenzelm@14989
   165
            val Ts' = map cert Ts;
wenzelm@14989
   166
            fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
wenzelm@14989
   167
          in
wenzelm@14790
   168
            (case Symtab.lookup (types, c) of
skalberg@15531
   169
              SOME (LogicalType n, _) => (nargs n; Type (c, Ts'))
skalberg@15531
   170
            | SOME (Abbreviation (vs, U, syn), _) => (nargs (length vs);
wenzelm@14989
   171
                if syn then check_syntax c else ();
wenzelm@14993
   172
                if normalize then inst_typ (vs ~~ Ts') U
wenzelm@14989
   173
                else Type (c, Ts'))
skalberg@15531
   174
            | SOME (Nonterminal, _) => (nargs 0; check_syntax c; T)
skalberg@15531
   175
            | NONE => err (undecl_type c))
wenzelm@14790
   176
          end
wenzelm@14989
   177
      | cert (TFree (x, S)) = TFree (x, Sorts.certify_sort classes S)
wenzelm@14989
   178
      | cert (TVar (xi as (_, i), S)) =
wenzelm@14993
   179
          if i < 0 then
wenzelm@14993
   180
            err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
wenzelm@14989
   181
          else TVar (xi, Sorts.certify_sort classes S);
wenzelm@14790
   182
wenzelm@14989
   183
    val ty' = cert ty;
wenzelm@14993
   184
  in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
wenzelm@14830
   185
wenzelm@14998
   186
in
wenzelm@14998
   187
wenzelm@16340
   188
val cert_typ        = certify_typ true false;
wenzelm@16340
   189
val cert_typ_syntax = certify_typ true true;
wenzelm@16340
   190
val cert_typ_abbrev = certify_typ false true;
wenzelm@14790
   191
wenzelm@14998
   192
end;
wenzelm@14998
   193
wenzelm@14790
   194
wenzelm@14790
   195
wenzelm@14790
   196
(** special treatment of type vars **)
wenzelm@14790
   197
wenzelm@14790
   198
(* strip_sorts *)
wenzelm@14790
   199
wenzelm@14790
   200
fun strip_sorts (Type (a, Ts)) = Type (a, map strip_sorts Ts)
wenzelm@14790
   201
  | strip_sorts (TFree (x, _)) = TFree (x, [])
wenzelm@14790
   202
  | strip_sorts (TVar (xi, _)) = TVar (xi, []);
wenzelm@14790
   203
wenzelm@14790
   204
wenzelm@14790
   205
(* no_tvars *)
wenzelm@621
   206
wenzelm@621
   207
fun no_tvars T =
wenzelm@12501
   208
  (case typ_tvars T of [] => T
wenzelm@12501
   209
  | vs => raise TYPE ("Illegal schematic type variable(s): " ^
wenzelm@14830
   210
      commas_quote (map (Term.string_of_vname o #1) vs), [T], []));
wenzelm@621
   211
wenzelm@7641
   212
wenzelm@2964
   213
(* varify, unvarify *)
wenzelm@621
   214
wenzelm@2964
   215
val varifyT = map_type_tfree (fn (a, S) => TVar ((a, 0), S));
wenzelm@2964
   216
wenzelm@621
   217
fun unvarifyT (Type (a, Ts)) = Type (a, map unvarifyT Ts)
wenzelm@621
   218
  | unvarifyT (TVar ((a, 0), S)) = TFree (a, S)
wenzelm@621
   219
  | unvarifyT T = T;
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)) =
berghofe@15797
   227
      (case assoc (fmap, f) of
skalberg@15531
   228
        NONE => TFree f
skalberg@15531
   229
      | SOME b => TVar (b, 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@16289
   242
  TFree (the (assoc_string_int (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@16289
   246
fun thaw_one alist (a, sort) = TVar (the (assoc_string (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@16289
   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@16340
   297
fun typ_match tsig (tyenv, TU) =
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 =>
berghofe@15797
   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@16340
   313
  in match TU tyenv end;
clasohm@0
   314
wenzelm@14790
   315
fun typ_instance tsig (T, U) =
berghofe@8406
   316
  (typ_match tsig (Vartab.empty, (U, T)); true) handle TYPE_MATCH => false;
wenzelm@2964
   317
clasohm@0
   318
wenzelm@14790
   319
(* unification *)
wenzelm@2964
   320
clasohm@0
   321
exception TUNIFY;
clasohm@0
   322
wenzelm@14790
   323
(*occurs_check*)
wenzelm@2964
   324
fun occurs v tye =
wenzelm@2964
   325
  let
wenzelm@2964
   326
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   327
      | occ (TFree _) = false
berghofe@15797
   328
      | occ (TVar (w, S)) =
wenzelm@2964
   329
          eq_ix (v, w) orelse
berghofe@15797
   330
            (case lookup (tye, (w, S)) of
skalberg@15531
   331
              NONE => false
skalberg@15531
   332
            | SOME U => occ U);
clasohm@0
   333
  in occ end;
clasohm@0
   334
wenzelm@14790
   335
(*chase variable assignments; if devar returns a type var then it must be unassigned*)
wenzelm@16885
   336
fun devar tye (T as TVar v) =
wenzelm@16885
   337
      (case lookup (tye, v) of
wenzelm@16885
   338
        SOME U => devar tye U
skalberg@15531
   339
      | NONE => T)
wenzelm@16885
   340
  | devar tye T = T;
clasohm@0
   341
wenzelm@16370
   342
fun unify (tsig as TSig {classes = (_, classes), arities, ...}) (tyenv, maxidx) TU =
wenzelm@2964
   343
  let
wenzelm@2964
   344
    val tyvar_count = ref maxidx;
wenzelm@2964
   345
    fun gen_tyvar S = TVar (("'a", inc tyvar_count), S);
wenzelm@2964
   346
wenzelm@2964
   347
    fun mg_domain a S =
wenzelm@14790
   348
      Sorts.mg_domain (classes, arities) a S handle Sorts.DOMAIN _ => raise TUNIFY;
wenzelm@2964
   349
wenzelm@16885
   350
    fun meet (_, []) tye = tye
wenzelm@16885
   351
      | meet (TVar (xi, S'), S) tye =
wenzelm@14790
   352
          if Sorts.sort_le classes (S', S) then tye
berghofe@15797
   353
          else Vartab.update_new ((xi, (S',
berghofe@15797
   354
            gen_tyvar (Sorts.inter_sort classes (S', S)))), tye)
wenzelm@16885
   355
      | meet (TFree (_, S'), S) tye =
wenzelm@14790
   356
          if Sorts.sort_le classes (S', S) then tye
wenzelm@2964
   357
          else raise TUNIFY
wenzelm@16885
   358
      | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
wenzelm@16885
   359
    and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
wenzelm@16885
   360
      | meets _ tye = tye;
wenzelm@2964
   361
wenzelm@16885
   362
    fun unif (ty1, ty2) tye =
wenzelm@16885
   363
      (case (devar tye ty1, devar tye ty2) of
wenzelm@2964
   364
        (T as TVar (v, S1), U as TVar (w, S2)) =>
berghofe@15797
   365
          if eq_ix (v, w) then
berghofe@15797
   366
            if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@14790
   367
          else if Sorts.sort_le classes (S1, S2) then
berghofe@15797
   368
            Vartab.update_new ((w, (S2, T)), tye)
wenzelm@14790
   369
          else if Sorts.sort_le classes (S2, S1) then
berghofe@15797
   370
            Vartab.update_new ((v, (S1, U)), tye)
wenzelm@2964
   371
          else
wenzelm@14790
   372
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
berghofe@15797
   373
              Vartab.update_new ((v, (S1, S)), Vartab.update_new ((w, (S2, S)), tye))
wenzelm@2964
   374
            end
wenzelm@2964
   375
      | (TVar (v, S), T) =>
wenzelm@2964
   376
          if occurs v tye T then raise TUNIFY
wenzelm@16885
   377
          else meet (T, S) (Vartab.update_new ((v, (S, T)), tye))
wenzelm@2964
   378
      | (T, TVar (v, S)) =>
wenzelm@2964
   379
          if occurs v tye T then raise TUNIFY
wenzelm@16885
   380
          else meet (T, S) (Vartab.update_new ((v, (S, T)), tye))
wenzelm@2964
   381
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   382
          if a <> b then raise TUNIFY
wenzelm@16885
   383
          else unifs (Ts, Us) tye
wenzelm@16885
   384
      | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16885
   385
    and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
wenzelm@16885
   386
      | unifs _ tye = tye;
wenzelm@16885
   387
  in (unif TU tyenv, ! tyvar_count) end;
clasohm@0
   388
wenzelm@14790
   389
(*purely structural unification *)
wenzelm@450
   390
fun raw_unify (ty1, ty2) =
wenzelm@14790
   391
  (unify empty_tsig (Vartab.empty, 0) (strip_sorts ty1, strip_sorts ty2); true)
wenzelm@450
   392
    handle TUNIFY => false;
wenzelm@450
   393
berghofe@16650
   394
(*check whether two types are equal with respect to a type environment*)
berghofe@16650
   395
fun eq_type tye (T, T') =
wenzelm@16885
   396
  (case (devar tye T, devar tye T') of
berghofe@16650
   397
     (Type (s, Ts), Type (s', Ts')) =>
berghofe@16650
   398
       s = s' andalso ListPair.all (eq_type tye) (Ts, Ts')
berghofe@16650
   399
   | (U, U') => U = U');
berghofe@16650
   400
wenzelm@450
   401
clasohm@0
   402
wenzelm@14790
   403
(** extend and merge type signatures **)
wenzelm@14790
   404
wenzelm@14790
   405
(* arities *)
wenzelm@14790
   406
wenzelm@14790
   407
local
nipkow@1435
   408
wenzelm@14790
   409
fun err_decl t decl = error ("Illegal " ^ str_of_decl decl ^ ": " ^ quote t);
wenzelm@14830
   410
skalberg@15531
   411
fun for_classes _ NONE = ""
skalberg@15531
   412
  | for_classes pp (SOME (c1, c2)) =
wenzelm@14830
   413
      " for classes " ^ Pretty.string_of_classrel pp [c1, c2];
wenzelm@3790
   414
wenzelm@14830
   415
fun err_conflict pp t cc (c, Ss) (c', Ss') =
wenzelm@14830
   416
  error ("Conflict of type arities" ^ for_classes pp cc ^ ":\n  " ^
wenzelm@14830
   417
    Pretty.string_of_arity pp (t, Ss, [c]) ^ " and\n  " ^
wenzelm@14830
   418
    Pretty.string_of_arity pp (t, Ss', [c']));
wenzelm@14790
   419
wenzelm@14830
   420
fun coregular pp C t (c, Ss) ars =
wenzelm@3790
   421
  let
wenzelm@14790
   422
    fun conflict (c', Ss') =
wenzelm@14790
   423
      if Sorts.class_le C (c, c') andalso not (Sorts.sorts_le C (Ss, Ss')) then
skalberg@15531
   424
        SOME ((c, c'), (c', Ss'))
wenzelm@14790
   425
      else if Sorts.class_le C (c', c) andalso not (Sorts.sorts_le C (Ss', Ss)) then
skalberg@15531
   426
        SOME ((c', c), (c', Ss'))
skalberg@15531
   427
      else NONE;
wenzelm@14790
   428
  in
wenzelm@14790
   429
    (case Library.get_first conflict ars of
skalberg@15531
   430
      SOME ((c1, c2), (c', Ss')) => err_conflict pp t (SOME (c1, c2)) (c, Ss) (c', Ss')
skalberg@15531
   431
    | NONE => (c, Ss) :: ars)
wenzelm@14790
   432
  end;
wenzelm@3790
   433
wenzelm@16340
   434
fun insert pp C t (c, Ss) ars =
wenzelm@14790
   435
  (case assoc_string (ars, c) of
skalberg@15531
   436
    NONE => coregular pp C t (c, Ss) ars
skalberg@15531
   437
  | SOME Ss' =>
wenzelm@14790
   438
      if Sorts.sorts_le C (Ss, Ss') then ars
wenzelm@14790
   439
      else if Sorts.sorts_le C (Ss', Ss)
wenzelm@14830
   440
      then coregular pp C t (c, Ss) (ars \ (c, Ss'))
skalberg@15531
   441
      else err_conflict pp t NONE (c, Ss) (c, Ss'));
wenzelm@2587
   442
wenzelm@14790
   443
fun complete C (c, Ss) = map (rpair Ss) (Graph.all_succs C [c]);
wenzelm@3790
   444
wenzelm@16340
   445
fun insert_arities pp classes (t, ars) arities =
wenzelm@14790
   446
  let val ars' =
wenzelm@14790
   447
    Symtab.lookup_multi (arities, t)
wenzelm@16340
   448
    |> fold_rev (fold_rev (insert pp classes t)) (map (complete classes) ars)
wenzelm@14790
   449
  in Symtab.update ((t, ars'), arities) end;
wenzelm@3790
   450
wenzelm@16444
   451
fun insert_table pp classes = Symtab.fold (fn (t, ars) =>
wenzelm@16444
   452
  insert_arities pp classes (t, map (apsnd (map (Sorts.norm_sort classes))) ars));
wenzelm@14790
   453
wenzelm@14790
   454
in
wenzelm@2587
   455
wenzelm@16370
   456
fun add_arities pp decls tsig = tsig |> map_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   457
  let
wenzelm@14790
   458
    fun prep (t, Ss, S) =
wenzelm@16370
   459
      (case Symtab.lookup (#2 types, t) of
skalberg@15531
   460
        SOME (LogicalType n, _) =>
wenzelm@14790
   461
          if length Ss = n then
wenzelm@14790
   462
            (t, map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@14790
   463
              handle TYPE (msg, _, _) => error msg
wenzelm@14790
   464
          else error (bad_nargs t)
skalberg@15531
   465
      | SOME (decl, _) => err_decl t decl
skalberg@15531
   466
      | NONE => error (undecl_type t));
wenzelm@4603
   467
wenzelm@14790
   468
    val ars = decls |> map ((fn (t, Ss, S) => (t, map (fn c => (c, Ss)) S)) o prep);
wenzelm@16370
   469
    val arities' = fold (insert_arities pp (#2 classes)) ars arities;
wenzelm@14790
   470
  in (classes, default, types, arities') end);
wenzelm@12528
   471
wenzelm@14830
   472
fun rebuild_arities pp classes arities =
wenzelm@16444
   473
  Symtab.empty
wenzelm@16444
   474
  |> insert_table pp classes arities;
wenzelm@14790
   475
wenzelm@14830
   476
fun merge_arities pp classes (arities1, arities2) =
wenzelm@16444
   477
  Symtab.empty
wenzelm@16444
   478
  |> insert_table pp classes arities1
wenzelm@16444
   479
  |> insert_table pp classes arities2;
wenzelm@14790
   480
wenzelm@14790
   481
end;
wenzelm@4603
   482
wenzelm@4603
   483
wenzelm@14790
   484
(* classes *)
wenzelm@14790
   485
wenzelm@14790
   486
local
clasohm@0
   487
wenzelm@14790
   488
fun err_dup_classes cs =
wenzelm@14790
   489
  error ("Duplicate declaration of class(es): " ^ commas_quote cs);
wenzelm@14790
   490
wenzelm@14830
   491
fun err_cyclic_classes pp css =
wenzelm@14790
   492
  error (cat_lines (map (fn cs =>
wenzelm@14830
   493
    "Cycle in class relation: " ^ Pretty.string_of_classrel pp cs) css));
wenzelm@14790
   494
wenzelm@16370
   495
fun add_class pp naming (c, cs) tsig =
wenzelm@16370
   496
  tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   497
    let
wenzelm@16370
   498
      val c' = NameSpace.full naming c;
wenzelm@16370
   499
      val cs' = map (cert_class tsig) cs
wenzelm@16370
   500
        handle TYPE (msg, _, _) => error msg;
wenzelm@16370
   501
      val space' = space |> NameSpace.declare naming c';
wenzelm@16370
   502
      val classes' = classes |> Graph.new_node (c', stamp ())
wenzelm@16370
   503
        handle Graph.DUP dup => err_dup_classes [dup];
wenzelm@16370
   504
      val classes'' = classes' |> fold Graph.add_edge_trans_acyclic (map (pair c') cs')
wenzelm@16370
   505
        handle Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   506
    in ((space', classes''), default, types, arities) end);
wenzelm@2964
   507
wenzelm@14790
   508
in
clasohm@0
   509
wenzelm@16370
   510
val add_classes = fold oo add_class;
wenzelm@14790
   511
wenzelm@16370
   512
fun add_classrel pp ps tsig =
wenzelm@16370
   513
  tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   514
    let
wenzelm@16370
   515
      val ps' = map (pairself (cert_class tsig)) ps
wenzelm@16370
   516
        handle TYPE (msg, _, _) => error msg;
wenzelm@16370
   517
      val classes' = classes |> fold Graph.add_edge_trans_acyclic ps'
wenzelm@16370
   518
        handle Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   519
      val default' = default |> Sorts.norm_sort classes';
wenzelm@16370
   520
      val arities' = arities |> rebuild_arities pp classes';
wenzelm@16370
   521
    in ((space, classes'), default', types, arities') end);
wenzelm@16370
   522
wenzelm@16370
   523
fun merge_classes pp ((space1, classes1), (space2, classes2)) =
wenzelm@14790
   524
  let
wenzelm@16370
   525
    val space = NameSpace.merge (space1, space2);
wenzelm@16370
   526
    val classes =
wenzelm@16370
   527
      Graph.merge_trans_acyclic (op =) (classes1, classes2)
wenzelm@16370
   528
        handle Graph.DUPS cs => err_dup_classes cs
wenzelm@16370
   529
          | Graph.CYCLES css => err_cyclic_classes pp css;
wenzelm@16370
   530
  in (space, classes) end;    
wenzelm@14790
   531
wenzelm@14790
   532
end;
wenzelm@14790
   533
wenzelm@16370
   534
fun hide_classes fully cs = map_tsig (fn ((space, classes), default, types, arities) =>
wenzelm@16370
   535
  ((fold (NameSpace.hide fully) cs space, classes), default, types, arities));
wenzelm@16370
   536
wenzelm@14790
   537
wenzelm@14790
   538
(* default sort *)
wenzelm@14790
   539
wenzelm@16370
   540
fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types, arities) =>
wenzelm@14790
   541
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types, arities));
clasohm@0
   542
clasohm@0
   543
wenzelm@14790
   544
(* types *)
wenzelm@14790
   545
wenzelm@14790
   546
local
wenzelm@14790
   547
wenzelm@14790
   548
fun err_neg_args c =
wenzelm@14790
   549
  error ("Negative number of arguments in type constructor declaration: " ^ quote c);
nipkow@949
   550
wenzelm@14790
   551
fun err_in_decls c decl decl' =
wenzelm@14906
   552
  let val s = str_of_decl decl and s' = str_of_decl decl' in
wenzelm@14906
   553
    if s = s' then error ("Duplicate declaration of " ^ s ^ ": " ^ quote c)
wenzelm@14830
   554
    else error ("Conflict of " ^ s ^ " with " ^ s' ^ ": " ^ quote c)
wenzelm@14790
   555
  end;
wenzelm@14790
   556
wenzelm@16370
   557
fun new_decl naming (c, decl) (space, types) =
wenzelm@16370
   558
  let
wenzelm@16370
   559
    val c' = NameSpace.full naming c;
wenzelm@16370
   560
    val space' = NameSpace.declare naming c' space;
wenzelm@16370
   561
    val types' =
wenzelm@16370
   562
      (case Symtab.lookup (types, c') of
wenzelm@16370
   563
        SOME (decl', _) => err_in_decls c' decl decl'
wenzelm@16370
   564
      | NONE => Symtab.update ((c', (decl, stamp ())), types));
wenzelm@16370
   565
  in (space', types') end;
wenzelm@14790
   566
wenzelm@16370
   567
fun the_decl (_, types) c = fst (the (Symtab.lookup (types, c)));
wenzelm@14790
   568
wenzelm@16370
   569
fun change_types f = map_tsig (fn (classes, default, types, arities) =>
wenzelm@14790
   570
  (classes, default, f types, arities));
wenzelm@2964
   571
wenzelm@14989
   572
fun syntactic types (Type (c, Ts)) =
skalberg@15531
   573
      (case Symtab.lookup (types, c) of SOME (Nonterminal, _) => true | _ => false)
wenzelm@14989
   574
        orelse exists (syntactic types) Ts
wenzelm@14989
   575
  | syntactic _ _ = false;
wenzelm@14989
   576
wenzelm@16370
   577
fun add_abbrev naming (a, vs, rhs) tsig = tsig |> change_types (fn types =>
wenzelm@14790
   578
  let
wenzelm@14790
   579
    fun err msg =
wenzelm@14906
   580
      error (msg ^ "\nThe error(s) above occurred in type abbreviation: " ^ quote a);
wenzelm@16340
   581
    val rhs' = compress_type (strip_sorts (no_tvars (cert_typ_syntax tsig rhs)))
wenzelm@14790
   582
      handle TYPE (msg, _, _) => err msg;
wenzelm@14790
   583
  in
wenzelm@14790
   584
    (case duplicates vs of
wenzelm@14790
   585
      [] => []
wenzelm@14790
   586
    | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
wenzelm@14790
   587
    (case gen_rems (op =) (map (#1 o #1) (typ_tvars rhs'), vs) of
wenzelm@14790
   588
      [] => []
wenzelm@14790
   589
    | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
wenzelm@16370
   590
    types |> new_decl naming (a, Abbreviation (vs, rhs', syntactic (#2 types) rhs'))
wenzelm@14790
   591
  end);
clasohm@0
   592
wenzelm@14790
   593
in
wenzelm@14790
   594
wenzelm@16370
   595
fun add_types naming ps = change_types (fold (new_decl naming) (ps |> map (fn (c, n) =>
wenzelm@14790
   596
  if n < 0 then err_neg_args c else (c, LogicalType n))));
wenzelm@14790
   597
wenzelm@16370
   598
val add_abbrevs = fold o add_abbrev;
wenzelm@16370
   599
wenzelm@16370
   600
fun add_nonterminals naming = change_types o fold (new_decl naming) o map (rpair Nonterminal);
wenzelm@14790
   601
wenzelm@14790
   602
fun merge_types (types1, types2) =
wenzelm@16370
   603
  NameSpace.merge_tables Library.eq_snd (types1, types2) handle Symtab.DUPS (d :: _) =>
wenzelm@14790
   604
    err_in_decls d (the_decl types1 d) (the_decl types2 d);
wenzelm@14790
   605
wenzelm@14790
   606
end;
clasohm@0
   607
wenzelm@16370
   608
fun hide_types fully cs = map_tsig (fn (classes, default, (space, types), arities) =>
wenzelm@16370
   609
  (classes, default, (fold (NameSpace.hide fully) cs space, types), arities));
wenzelm@16370
   610
wenzelm@3790
   611
wenzelm@14790
   612
(* merge type signatures *)
wenzelm@14790
   613
wenzelm@14830
   614
fun merge_tsigs pp (tsig1, tsig2) =
wenzelm@14790
   615
  let
wenzelm@14790
   616
    val (TSig {classes = classes1, default = default1, types = types1, arities = arities1,
wenzelm@14790
   617
      log_types = _, witness = _}) = tsig1;
wenzelm@14790
   618
    val (TSig {classes = classes2, default = default2, types = types2, arities = arities2,
wenzelm@14790
   619
      log_types = _, witness = _}) = tsig2;
wenzelm@14790
   620
wenzelm@14830
   621
    val classes' = merge_classes pp (classes1, classes2);
wenzelm@16370
   622
    val default' = Sorts.inter_sort (#2 classes') (default1, default2);
wenzelm@14790
   623
    val types' = merge_types (types1, types2);
wenzelm@16370
   624
    val arities' = merge_arities pp (#2 classes') (arities1, arities2);
wenzelm@14790
   625
  in build_tsig (classes', default', types', arities') end;
wenzelm@14790
   626
clasohm@0
   627
end;