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