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