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