src/Pure/type.ML
author wenzelm
Mon Feb 23 14:50:30 2015 +0100 (2015-02-23)
changeset 59564 fdc03c8daacc
parent 59058 a78612c67ec0
child 59841 2551ac44150e
permissions -rw-r--r--
Goal.prove_multi is superseded by the fully general Goal.prove_common;
wenzelm@256
     1
(*  Title:      Pure/type.ML
wenzelm@14790
     2
    Author:     Tobias Nipkow, Lawrence C Paulson, and Markus Wenzel
clasohm@0
     3
wenzelm@14790
     4
Type signatures and certified types, special treatment of type vars,
wenzelm@14790
     5
matching and unification of types, extend and merge type signatures.
clasohm@0
     6
*)
clasohm@0
     7
clasohm@0
     8
signature TYPE =
wenzelm@2964
     9
sig
wenzelm@39288
    10
  (*constraints*)
wenzelm@39290
    11
  val mark_polymorphic: typ -> typ
wenzelm@39288
    12
  val constraint: typ -> term -> term
wenzelm@45445
    13
  val constraint_type: Proof.context -> typ -> typ
wenzelm@39292
    14
  val strip_constraints: term -> term
wenzelm@42383
    15
  val appl_error: Proof.context -> term -> typ -> term -> typ -> string
wenzelm@14790
    16
  (*type signatures and certified types*)
wenzelm@14790
    17
  datatype decl =
wenzelm@14790
    18
    LogicalType of int |
wenzelm@14989
    19
    Abbreviation of string list * typ * bool |
wenzelm@14790
    20
    Nonterminal
wenzelm@14790
    21
  type tsig
wenzelm@35669
    22
  val eq_tsig: tsig * tsig -> bool
wenzelm@14790
    23
  val rep_tsig: tsig ->
wenzelm@33095
    24
   {classes: Name_Space.T * Sorts.algebra,
wenzelm@14790
    25
    default: sort,
wenzelm@33173
    26
    types: decl Name_Space.table,
wenzelm@26641
    27
    log_types: string list}
wenzelm@56056
    28
  val change_base: bool -> tsig -> tsig
wenzelm@56139
    29
  val change_ignore: tsig -> tsig
wenzelm@14790
    30
  val empty_tsig: tsig
wenzelm@35669
    31
  val class_space: tsig -> Name_Space.T
wenzelm@35680
    32
  val class_alias: Name_Space.naming -> binding -> string -> tsig -> tsig
wenzelm@14790
    33
  val defaultS: tsig -> sort
wenzelm@14790
    34
  val logical_types: tsig -> string list
wenzelm@14790
    35
  val eq_sort: tsig -> sort * sort -> bool
wenzelm@14790
    36
  val subsort: tsig -> sort * sort -> bool
wenzelm@14790
    37
  val of_sort: tsig -> typ * sort -> bool
wenzelm@19464
    38
  val inter_sort: tsig -> sort * sort -> sort
wenzelm@14790
    39
  val cert_class: tsig -> class -> class
wenzelm@14790
    40
  val cert_sort: tsig -> sort -> sort
wenzelm@36447
    41
  val minimize_sort: tsig -> sort -> sort
wenzelm@31946
    42
  val witness_sorts: tsig -> (typ * sort) list -> sort list -> (typ * sort) list
wenzelm@24274
    43
  type mode
wenzelm@24274
    44
  val mode_default: mode
wenzelm@24274
    45
  val mode_syntax: mode
wenzelm@24274
    46
  val mode_abbrev: mode
wenzelm@24484
    47
  val get_mode: Proof.context -> mode
wenzelm@24484
    48
  val set_mode: mode -> Proof.context -> Proof.context
wenzelm@24484
    49
  val restore_mode: Proof.context -> Proof.context -> Proof.context
wenzelm@35669
    50
  val type_space: tsig -> Name_Space.T
wenzelm@35680
    51
  val type_alias: Name_Space.naming -> binding -> string -> tsig -> tsig
wenzelm@35669
    52
  val is_logtype: tsig -> string -> bool
wenzelm@55922
    53
  val check_decl: Context.generic -> tsig ->
wenzelm@55922
    54
    xstring * Position.T -> (string * Position.report list) * decl
wenzelm@42468
    55
  val the_decl: tsig -> string * Position.T -> decl
wenzelm@24274
    56
  val cert_typ_mode: mode -> tsig -> typ -> typ
wenzelm@14993
    57
  val cert_typ: tsig -> typ -> typ
wenzelm@19464
    58
  val arity_number: tsig -> string -> int
wenzelm@42383
    59
  val arity_sorts: Context.pretty -> tsig -> string -> sort -> sort list
wenzelm@14790
    60
wenzelm@14790
    61
  (*special treatment of type vars*)
wenzelm@36621
    62
  val sort_of_atyp: typ -> sort
wenzelm@14790
    63
  val strip_sorts: typ -> typ
wenzelm@49687
    64
  val strip_sorts_dummy: typ -> typ
wenzelm@621
    65
  val no_tvars: typ -> typ
wenzelm@35845
    66
  val varify_global: (string * sort) list -> term -> ((string * sort) * indexname) list * term
wenzelm@33832
    67
  val legacy_freeze_thaw_type: typ -> typ * (typ -> typ)
wenzelm@33832
    68
  val legacy_freeze_type: typ -> typ
wenzelm@33832
    69
  val legacy_freeze_thaw: term -> term * (term -> term)
wenzelm@33832
    70
  val legacy_freeze: term -> term
wenzelm@2964
    71
wenzelm@14790
    72
  (*matching and unification*)
wenzelm@2964
    73
  exception TYPE_MATCH
wenzelm@25324
    74
  type tyenv = (sort * typ) Vartab.table
haftmann@26327
    75
  val lookup: tyenv -> indexname * sort -> typ option
paulson@32648
    76
  val devar: tyenv -> typ -> typ
wenzelm@16946
    77
  val typ_match: tsig -> typ * typ -> tyenv -> tyenv
wenzelm@14790
    78
  val typ_instance: tsig -> typ * typ -> bool
wenzelm@16946
    79
  val raw_match: typ * typ -> tyenv -> tyenv
wenzelm@19694
    80
  val raw_matches: typ list * typ list -> tyenv -> tyenv
wenzelm@56050
    81
  val could_match: typ * typ -> bool
wenzelm@56050
    82
  val could_matches: typ list * typ list -> bool
wenzelm@16946
    83
  val raw_instance: typ * typ -> bool
wenzelm@2964
    84
  exception TUNIFY
wenzelm@16946
    85
  val unify: tsig -> typ * typ -> tyenv * int -> tyenv * int
wenzelm@16946
    86
  val raw_unify: typ * typ -> tyenv -> tyenv
wenzelm@19696
    87
  val raw_unifys: typ list * typ list -> tyenv -> tyenv
wenzelm@17804
    88
  val could_unify: typ * typ -> bool
wenzelm@19696
    89
  val could_unifys: typ list * typ list -> bool
wenzelm@58949
    90
  val unified: tyenv -> typ * typ -> bool
clasohm@0
    91
wenzelm@14790
    92
  (*extend and merge type signatures*)
wenzelm@47005
    93
  val add_class: Context.generic -> binding * class list -> tsig -> tsig
wenzelm@26669
    94
  val hide_class: bool -> string -> tsig -> tsig
wenzelm@14790
    95
  val set_defsort: sort -> tsig -> tsig
wenzelm@47005
    96
  val add_type: Context.generic -> binding * int -> tsig -> tsig
wenzelm@47005
    97
  val add_abbrev: Context.generic -> binding * string list * typ -> tsig -> tsig
wenzelm@47005
    98
  val add_nonterminal: Context.generic -> binding -> tsig -> tsig
wenzelm@26669
    99
  val hide_type: bool -> string -> tsig -> tsig
wenzelm@47005
   100
  val add_arity: Context.pretty -> arity -> tsig -> tsig
wenzelm@47005
   101
  val add_classrel: Context.pretty -> class * class -> tsig -> tsig
wenzelm@47005
   102
  val merge_tsig: Context.pretty -> tsig * tsig -> tsig
wenzelm@2964
   103
end;
wenzelm@2964
   104
wenzelm@2964
   105
structure Type: TYPE =
clasohm@0
   106
struct
clasohm@0
   107
wenzelm@39288
   108
(** constraints **)
wenzelm@39288
   109
wenzelm@39290
   110
(*indicate polymorphic Vars*)
wenzelm@39290
   111
fun mark_polymorphic T = Type ("_polymorphic_", [T]);
wenzelm@39290
   112
wenzelm@39288
   113
fun constraint T t =
wenzelm@39288
   114
  if T = dummyT then t
wenzelm@39288
   115
  else Const ("_type_constraint_", T --> T) $ t;
wenzelm@39288
   116
wenzelm@45445
   117
fun constraint_type ctxt T =
wenzelm@45445
   118
  let fun err () = error ("Malformed internal type constraint: " ^ Syntax.string_of_typ ctxt T);
wenzelm@45445
   119
  in (case T of Type ("fun", [A, B]) => if A = B then A else err () | _ => err ()) end;
wenzelm@45445
   120
wenzelm@39292
   121
fun strip_constraints (Const ("_type_constraint_", _) $ t) = strip_constraints t
wenzelm@39292
   122
  | strip_constraints (t $ u) = strip_constraints t $ strip_constraints u
wenzelm@39292
   123
  | strip_constraints (Abs (x, T, t)) = Abs (x, T, strip_constraints t)
wenzelm@39292
   124
  | strip_constraints a = a;
wenzelm@39292
   125
wenzelm@42383
   126
fun appl_error ctxt (Const ("_type_constraint_", Type ("fun", [T, _]))) _ u U =
wenzelm@39289
   127
      cat_lines
wenzelm@39289
   128
       ["Failed to meet type constraint:", "",
wenzelm@39289
   129
        Pretty.string_of (Pretty.block
wenzelm@42383
   130
         [Pretty.str "Term:", Pretty.brk 2, Syntax.pretty_term ctxt u,
wenzelm@42383
   131
          Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ ctxt U]),
wenzelm@39289
   132
        Pretty.string_of (Pretty.block
wenzelm@42383
   133
         [Pretty.str "Type:", Pretty.brk 2, Syntax.pretty_typ ctxt T])]
wenzelm@42383
   134
  | appl_error ctxt t T u U =
wenzelm@39289
   135
      cat_lines
wenzelm@39289
   136
       ["Type error in application: " ^
wenzelm@39289
   137
          (case T of
wenzelm@39289
   138
            Type ("fun", _) => "incompatible operand type"
wenzelm@39289
   139
          | _ => "operator not of function type"),
wenzelm@39289
   140
        "",
wenzelm@39289
   141
        Pretty.string_of (Pretty.block
wenzelm@42383
   142
          [Pretty.str "Operator:", Pretty.brk 2, Syntax.pretty_term ctxt t,
wenzelm@42383
   143
            Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ ctxt T]),
wenzelm@39289
   144
        Pretty.string_of (Pretty.block
wenzelm@42383
   145
          [Pretty.str "Operand:", Pretty.brk 3, Syntax.pretty_term ctxt u,
wenzelm@42383
   146
            Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ ctxt U])];
wenzelm@39289
   147
wenzelm@39288
   148
wenzelm@39288
   149
wenzelm@14790
   150
(** type signatures and certified types **)
wenzelm@2964
   151
wenzelm@14790
   152
(* type declarations *)
wenzelm@14790
   153
wenzelm@14790
   154
datatype decl =
wenzelm@14790
   155
  LogicalType of int |
wenzelm@14989
   156
  Abbreviation of string list * typ * bool |
wenzelm@14790
   157
  Nonterminal;
wenzelm@14790
   158
wenzelm@14790
   159
wenzelm@14790
   160
(* type tsig *)
wenzelm@14790
   161
wenzelm@14790
   162
datatype tsig =
wenzelm@14790
   163
  TSig of {
wenzelm@33095
   164
    classes: Name_Space.T * Sorts.algebra,  (*order-sorted algebra of type classes*)
wenzelm@16370
   165
    default: sort,                          (*default sort on input*)
wenzelm@33173
   166
    types: decl Name_Space.table,           (*declared types*)
wenzelm@26641
   167
    log_types: string list};                (*logical types sorted by number of arguments*)
wenzelm@14790
   168
wenzelm@35669
   169
fun eq_tsig
wenzelm@35669
   170
   (TSig {classes = classes1, default = default1, types = types1, log_types = _},
wenzelm@35669
   171
    TSig {classes = classes2, default = default2, types = types2, log_types = _}) =
wenzelm@35669
   172
  pointer_eq (classes1, classes2) andalso
wenzelm@35669
   173
  default1 = default2 andalso
wenzelm@35669
   174
  pointer_eq (types1, types2);
wenzelm@35669
   175
wenzelm@14790
   176
fun rep_tsig (TSig comps) = comps;
wenzelm@14790
   177
wenzelm@26641
   178
fun make_tsig (classes, default, types, log_types) =
wenzelm@26641
   179
  TSig {classes = classes, default = default, types = types, log_types = log_types};
wenzelm@14790
   180
wenzelm@56056
   181
fun change_base begin (TSig {classes, default, types, log_types}) =
wenzelm@56056
   182
  make_tsig (classes, default, Name_Space.change_base begin types, log_types);
wenzelm@56056
   183
wenzelm@56139
   184
fun change_ignore (TSig {classes, default, types, log_types}) =
wenzelm@56139
   185
  make_tsig (classes, default, Name_Space.change_ignore types, log_types);
wenzelm@56139
   186
wenzelm@33094
   187
fun build_tsig (classes, default, types) =
wenzelm@14790
   188
  let
wenzelm@14790
   189
    val log_types =
wenzelm@56025
   190
      Name_Space.fold_table (fn (c, LogicalType n) => cons (c, n) | _ => I) types []
wenzelm@59058
   191
      |> Library.sort (int_ord o apply2 snd) |> map fst;
wenzelm@33094
   192
  in make_tsig (classes, default, types, log_types) end;
wenzelm@14790
   193
wenzelm@26641
   194
fun map_tsig f (TSig {classes, default, types, log_types = _}) =
wenzelm@19642
   195
  build_tsig (f (classes, default, types));
wenzelm@14790
   196
wenzelm@16370
   197
val empty_tsig =
wenzelm@50201
   198
  build_tsig ((Name_Space.empty Markup.classN, Sorts.empty_algebra), [],
wenzelm@50201
   199
    Name_Space.empty_table Markup.type_nameN);
wenzelm@14790
   200
wenzelm@14790
   201
wenzelm@14790
   202
(* classes and sorts *)
wenzelm@14790
   203
wenzelm@35669
   204
val class_space = #1 o #classes o rep_tsig;
wenzelm@35669
   205
wenzelm@35680
   206
fun class_alias naming binding name = map_tsig (fn ((space, classes), default, types) =>
wenzelm@35680
   207
  ((Name_Space.alias naming binding name space, classes), default, types));
wenzelm@35680
   208
wenzelm@14790
   209
fun defaultS (TSig {default, ...}) = default;
wenzelm@14790
   210
fun logical_types (TSig {log_types, ...}) = log_types;
wenzelm@14790
   211
wenzelm@16370
   212
fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq (#2 classes);
wenzelm@16370
   213
fun subsort (TSig {classes, ...}) = Sorts.sort_le (#2 classes);
wenzelm@19642
   214
fun of_sort (TSig {classes, ...}) = Sorts.of_sort (#2 classes);
wenzelm@19464
   215
fun inter_sort (TSig {classes, ...}) = Sorts.inter_sort (#2 classes);
wenzelm@14790
   216
wenzelm@45595
   217
fun cert_class (TSig {classes = (_, algebra), ...}) c =
wenzelm@45595
   218
  if can (Graph.get_entry (Sorts.classes_of algebra)) c then c
wenzelm@45595
   219
  else raise TYPE ("Undeclared class: " ^ quote c, [], []);
wenzelm@45595
   220
wenzelm@45595
   221
val cert_sort = map o cert_class;
wenzelm@45595
   222
wenzelm@36447
   223
fun minimize_sort (TSig {classes, ...}) = Sorts.minimize_sort (#2 classes);
wenzelm@19515
   224
wenzelm@32784
   225
fun witness_sorts (TSig {classes, log_types, ...}) =
wenzelm@19642
   226
  Sorts.witness_sorts (#2 classes) log_types;
wenzelm@14790
   227
wenzelm@14790
   228
wenzelm@24274
   229
(* certification mode *)
wenzelm@24274
   230
wenzelm@24274
   231
datatype mode = Mode of {normalize: bool, logical: bool};
wenzelm@24274
   232
wenzelm@24274
   233
val mode_default = Mode {normalize = true, logical = true};
wenzelm@24274
   234
val mode_syntax = Mode {normalize = true, logical = false};
wenzelm@24274
   235
val mode_abbrev = Mode {normalize = false, logical = false};
wenzelm@24274
   236
wenzelm@33519
   237
structure Mode = Proof_Data
wenzelm@24484
   238
(
wenzelm@24484
   239
  type T = mode;
wenzelm@24484
   240
  fun init _ = mode_default;
wenzelm@24484
   241
);
wenzelm@24484
   242
wenzelm@24484
   243
val get_mode = Mode.get;
wenzelm@24484
   244
fun set_mode mode = Mode.map (K mode);
wenzelm@24484
   245
fun restore_mode ctxt = set_mode (get_mode ctxt);
wenzelm@24484
   246
wenzelm@24274
   247
wenzelm@35669
   248
(* types *)
wenzelm@35669
   249
wenzelm@56025
   250
val type_space = Name_Space.space_of_table o #types o rep_tsig;
wenzelm@35669
   251
wenzelm@56025
   252
fun type_alias naming binding name = map_tsig (fn (classes, default, types) =>
wenzelm@56025
   253
  (classes, default, (Name_Space.alias_table naming binding name types)));
wenzelm@35680
   254
wenzelm@35669
   255
val is_logtype = member (op =) o logical_types;
wenzelm@35669
   256
wenzelm@27313
   257
wenzelm@27313
   258
fun undecl_type c = "Undeclared type constructor: " ^ quote c;
wenzelm@27313
   259
wenzelm@56025
   260
fun lookup_type (TSig {types, ...}) = Option.map #2 o Name_Space.lookup_key types;
wenzelm@27313
   261
wenzelm@55956
   262
fun check_decl context (TSig {types, ...}) (c, pos) =
wenzelm@55956
   263
  Name_Space.check_reports context types (c, [pos]);
wenzelm@55841
   264
wenzelm@42468
   265
fun the_decl tsig (c, pos) =
wenzelm@35359
   266
  (case lookup_type tsig c of
wenzelm@48992
   267
    NONE => error (undecl_type c ^ Position.here pos)
wenzelm@35359
   268
  | SOME decl => decl);
wenzelm@35359
   269
wenzelm@27313
   270
wenzelm@14790
   271
(* certified types *)
wenzelm@14790
   272
wenzelm@14790
   273
fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
wenzelm@14830
   274
wenzelm@14998
   275
local
wenzelm@14998
   276
wenzelm@14998
   277
fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
wenzelm@18957
   278
  | inst_typ env (T as TFree (x, _)) = the_default T (AList.lookup (op =) env x)
wenzelm@14998
   279
  | inst_typ _ T = T;
wenzelm@14998
   280
wenzelm@24274
   281
in
wenzelm@24274
   282
wenzelm@24274
   283
fun cert_typ_mode (Mode {normalize, logical}) tsig ty =
wenzelm@14790
   284
  let
wenzelm@14790
   285
    fun err msg = raise TYPE (msg, [ty], []);
wenzelm@14790
   286
wenzelm@24274
   287
    val check_logical =
wenzelm@24274
   288
      if logical then fn c => err ("Illegal occurrence of syntactic type: " ^ quote c)
wenzelm@24274
   289
      else fn _ => ();
wenzelm@14989
   290
wenzelm@14989
   291
    fun cert (T as Type (c, Ts)) =
wenzelm@14989
   292
          let
wenzelm@14989
   293
            val Ts' = map cert Ts;
wenzelm@14989
   294
            fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
wenzelm@14989
   295
          in
wenzelm@42468
   296
            (case the_decl tsig (c, Position.none) of
wenzelm@35359
   297
              LogicalType n => (nargs n; Type (c, Ts'))
wenzelm@35359
   298
            | Abbreviation (vs, U, syn) =>
wenzelm@24274
   299
               (nargs (length vs);
wenzelm@24274
   300
                if syn then check_logical c else ();
wenzelm@14993
   301
                if normalize then inst_typ (vs ~~ Ts') U
wenzelm@14989
   302
                else Type (c, Ts'))
wenzelm@35359
   303
            | Nonterminal => (nargs 0; check_logical c; T))
wenzelm@14790
   304
          end
wenzelm@19515
   305
      | cert (TFree (x, S)) = TFree (x, cert_sort tsig S)
wenzelm@14989
   306
      | cert (TVar (xi as (_, i), S)) =
wenzelm@14993
   307
          if i < 0 then
wenzelm@14993
   308
            err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
wenzelm@19515
   309
          else TVar (xi, cert_sort tsig S);
wenzelm@14790
   310
wenzelm@14989
   311
    val ty' = cert ty;
wenzelm@14993
   312
  in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
wenzelm@14830
   313
wenzelm@24274
   314
val cert_typ = cert_typ_mode mode_default;
wenzelm@14790
   315
wenzelm@14998
   316
end;
wenzelm@14998
   317
wenzelm@14790
   318
wenzelm@19464
   319
(* type arities *)
wenzelm@19464
   320
haftmann@27302
   321
fun arity_number tsig a =
haftmann@27302
   322
  (case lookup_type tsig a of
wenzelm@33173
   323
    SOME (LogicalType n) => n
wenzelm@19464
   324
  | _ => error (undecl_type a));
wenzelm@19464
   325
wenzelm@19464
   326
fun arity_sorts _ tsig a [] = replicate (arity_number tsig a) []
wenzelm@47005
   327
  | arity_sorts pp (TSig {classes, ...}) a S =
wenzelm@47005
   328
      Sorts.mg_domain (#2 classes) a S
wenzelm@47005
   329
        handle Sorts.CLASS_ERROR err => error (Sorts.class_error pp err);
wenzelm@19464
   330
wenzelm@19464
   331
wenzelm@14790
   332
wenzelm@14790
   333
(** special treatment of type vars **)
wenzelm@14790
   334
wenzelm@36621
   335
(* sort_of_atyp *)
wenzelm@36621
   336
wenzelm@36621
   337
fun sort_of_atyp (TFree (_, S)) = S
wenzelm@36621
   338
  | sort_of_atyp (TVar (_, S)) = S
wenzelm@36621
   339
  | sort_of_atyp T = raise TYPE ("sort_of_atyp", [T], []);
wenzelm@36621
   340
wenzelm@36621
   341
wenzelm@14790
   342
(* strip_sorts *)
wenzelm@14790
   343
wenzelm@49687
   344
val strip_sorts = map_atyps
wenzelm@49687
   345
  (fn TFree (x, _) => TFree (x, [])
wenzelm@49687
   346
    | TVar (xi, _) => TVar (xi, []));
wenzelm@49687
   347
wenzelm@49687
   348
val strip_sorts_dummy = map_atyps
wenzelm@49687
   349
  (fn TFree (x, _) => TFree (x, dummyS)
wenzelm@49687
   350
    | TVar (xi, _) => TVar (xi, dummyS));
wenzelm@14790
   351
wenzelm@14790
   352
wenzelm@14790
   353
(* no_tvars *)
wenzelm@621
   354
wenzelm@621
   355
fun no_tvars T =
wenzelm@29275
   356
  (case Term.add_tvarsT T [] of [] => T
wenzelm@12501
   357
  | vs => raise TYPE ("Illegal schematic type variable(s): " ^
wenzelm@29275
   358
      commas_quote (map (Term.string_of_vname o #1) (rev vs)), [T], []));
wenzelm@621
   359
wenzelm@7641
   360
wenzelm@35845
   361
(* varify_global *)
wenzelm@621
   362
wenzelm@35845
   363
fun varify_global fixed t =
wenzelm@621
   364
  let
wenzelm@19305
   365
    val fs = Term.fold_types (Term.fold_atyps
wenzelm@19305
   366
      (fn TFree v => if member (op =) fixed v then I else insert (op =) v | _ => I)) t [];
wenzelm@29260
   367
    val used = Name.context
wenzelm@29260
   368
      |> fold_types (fold_atyps (fn TVar ((a, _), _) => Name.declare a | _ => I)) t;
wenzelm@43326
   369
    val fmap = fs ~~ map (rpair 0) (#1 (fold_map Name.variant (map fst fs) used));
wenzelm@32784
   370
    fun thaw (f as (_, S)) =
wenzelm@17184
   371
      (case AList.lookup (op =) fmap f of
skalberg@15531
   372
        NONE => TFree f
wenzelm@16946
   373
      | SOME xi => TVar (xi, S));
haftmann@21116
   374
  in (fmap, map_types (map_type_tfree thaw) t) end;
wenzelm@2964
   375
wenzelm@2964
   376
wenzelm@7641
   377
(* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
paulson@3411
   378
wenzelm@7641
   379
local
wenzelm@7641
   380
wenzelm@44116
   381
fun new_name ix (pairs, used) =
wenzelm@43324
   382
  let val v = singleton (Name.variant_list used) (string_of_indexname ix)
wenzelm@16289
   383
  in ((ix, v) :: pairs, v :: used) end;
wenzelm@621
   384
wenzelm@16289
   385
fun freeze_one alist (ix, sort) =
wenzelm@17184
   386
  TFree (the (AList.lookup (op =) alist ix), sort)
wenzelm@51930
   387
    handle Option.Option =>
wenzelm@3790
   388
      raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
wenzelm@2964
   389
wenzelm@17184
   390
fun thaw_one alist (a, sort) = TVar (the (AList.lookup (op =) alist a), sort)
wenzelm@51930
   391
  handle Option.Option => TFree (a, sort);
wenzelm@416
   392
wenzelm@10495
   393
in
wenzelm@10495
   394
wenzelm@33832
   395
fun legacy_freeze_thaw_type T =
wenzelm@7641
   396
  let
wenzelm@44116
   397
    val used = Term.add_tfree_namesT T [];
wenzelm@44116
   398
    val (alist, _) = fold_rev new_name (map #1 (Term.add_tvarsT T [])) ([], used);
wenzelm@7641
   399
  in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
wenzelm@7641
   400
wenzelm@33832
   401
val legacy_freeze_type = #1 o legacy_freeze_thaw_type;
wenzelm@16289
   402
wenzelm@33832
   403
fun legacy_freeze_thaw t =
wenzelm@7641
   404
  let
wenzelm@44116
   405
    val used = Term.add_tfree_names t [];
wenzelm@44116
   406
    val (alist, _) = fold_rev new_name (map #1 (Term.add_tvars t [])) ([], used);
wenzelm@7641
   407
  in
wenzelm@7641
   408
    (case alist of
wenzelm@7641
   409
      [] => (t, fn x => x) (*nothing to do!*)
wenzelm@20548
   410
    | _ => (map_types (map_type_tvar (freeze_one alist)) t,
wenzelm@20548
   411
      map_types (map_type_tfree (thaw_one (map swap alist)))))
wenzelm@7641
   412
  end;
wenzelm@7641
   413
wenzelm@33832
   414
val legacy_freeze = #1 o legacy_freeze_thaw;
wenzelm@16289
   415
wenzelm@7641
   416
end;
wenzelm@7641
   417
wenzelm@256
   418
wenzelm@256
   419
wenzelm@14790
   420
(** matching and unification of types **)
wenzelm@8899
   421
berghofe@15797
   422
type tyenv = (sort * typ) Vartab.table;
wenzelm@256
   423
wenzelm@51701
   424
fun tvar_clash ixn S S' =
wenzelm@51701
   425
  raise TYPE ("Type variable has two distinct sorts", [TVar (ixn, S), TVar (ixn, S')], []);
clasohm@0
   426
haftmann@26327
   427
fun lookup tye (ixn, S) =
wenzelm@17412
   428
  (case Vartab.lookup tye ixn of
berghofe@15797
   429
    NONE => NONE
wenzelm@16289
   430
  | SOME (S', T) => if S = S' then SOME T else tvar_clash ixn S S');
wenzelm@16289
   431
clasohm@0
   432
wenzelm@14790
   433
(* matching *)
clasohm@0
   434
wenzelm@2964
   435
exception TYPE_MATCH;
clasohm@0
   436
wenzelm@16946
   437
fun typ_match tsig =
wenzelm@2964
   438
  let
wenzelm@58942
   439
    fun match (TVar (v, S), T) subs =
haftmann@26327
   440
          (case lookup subs (v, S) of
skalberg@15531
   441
            NONE =>
wenzelm@58942
   442
              if of_sort tsig (T, S) then Vartab.update_new (v, (S, T)) subs
wenzelm@14993
   443
              else raise TYPE_MATCH
skalberg@15531
   444
          | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16340
   445
      | match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@2964
   446
          if a <> b then raise TYPE_MATCH
wenzelm@16885
   447
          else matches (Ts, Us) subs
wenzelm@16340
   448
      | match (TFree x, TFree y) subs =
wenzelm@2964
   449
          if x = y then subs else raise TYPE_MATCH
wenzelm@16885
   450
      | match _ _ = raise TYPE_MATCH
wenzelm@16885
   451
    and matches (T :: Ts, U :: Us) subs = matches (Ts, Us) (match (T, U) subs)
wenzelm@16885
   452
      | matches _ subs = subs;
wenzelm@16946
   453
  in match end;
clasohm@0
   454
wenzelm@14790
   455
fun typ_instance tsig (T, U) =
wenzelm@16946
   456
  (typ_match tsig (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@16946
   457
wenzelm@16946
   458
(*purely structural matching*)
wenzelm@58942
   459
fun raw_match (TVar (v, S), T) subs =
haftmann@26327
   460
      (case lookup subs (v, S) of
wenzelm@58942
   461
        NONE => Vartab.update_new (v, (S, T)) subs
wenzelm@16946
   462
      | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16946
   463
  | raw_match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@16946
   464
      if a <> b then raise TYPE_MATCH
wenzelm@16946
   465
      else raw_matches (Ts, Us) subs
wenzelm@16946
   466
  | raw_match (TFree x, TFree y) subs =
wenzelm@16946
   467
      if x = y then subs else raise TYPE_MATCH
wenzelm@16946
   468
  | raw_match _ _ = raise TYPE_MATCH
wenzelm@16946
   469
and raw_matches (T :: Ts, U :: Us) subs = raw_matches (Ts, Us) (raw_match (T, U) subs)
wenzelm@19694
   470
  | raw_matches ([], []) subs = subs
wenzelm@19694
   471
  | raw_matches _ _ = raise TYPE_MATCH;
wenzelm@16946
   472
wenzelm@56050
   473
(*fast matching filter*)
wenzelm@56050
   474
fun could_match (Type (a, Ts), Type (b, Us)) = a = b andalso could_matches (Ts, Us)
wenzelm@56050
   475
  | could_match (TFree (a, _), TFree (b, _)) = a = b
wenzelm@56050
   476
  | could_match (TVar _, _) = true
wenzelm@56050
   477
  | could_match _ = false
wenzelm@56050
   478
and could_matches (T :: Ts, U :: Us) = could_match (T, U) andalso could_matches (Ts, Us)
wenzelm@56050
   479
  | could_matches ([], []) = true
wenzelm@56050
   480
  | could_matches _ = false;
wenzelm@56050
   481
wenzelm@16946
   482
fun raw_instance (T, U) =
wenzelm@56050
   483
  if could_match (U, T) then
wenzelm@56050
   484
    (raw_match (U, T) Vartab.empty; true) handle TYPE_MATCH => false
wenzelm@56050
   485
  else false;
wenzelm@2964
   486
clasohm@0
   487
wenzelm@14790
   488
(* unification *)
wenzelm@2964
   489
clasohm@0
   490
exception TUNIFY;
clasohm@0
   491
wenzelm@26641
   492
(*occurs check*)
wenzelm@2964
   493
fun occurs v tye =
wenzelm@2964
   494
  let
wenzelm@2964
   495
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   496
      | occ (TFree _) = false
berghofe@15797
   497
      | occ (TVar (w, S)) =
wenzelm@29269
   498
          Term.eq_ix (v, w) orelse
haftmann@26327
   499
            (case lookup tye (w, S) of
skalberg@15531
   500
              NONE => false
skalberg@15531
   501
            | SOME U => occ U);
clasohm@0
   502
  in occ end;
clasohm@0
   503
wenzelm@14790
   504
(*chase variable assignments; if devar returns a type var then it must be unassigned*)
wenzelm@16885
   505
fun devar tye (T as TVar v) =
haftmann@26327
   506
      (case lookup tye v of
wenzelm@16885
   507
        SOME U => devar tye U
skalberg@15531
   508
      | NONE => T)
wenzelm@32784
   509
  | devar _ T = T;
clasohm@0
   510
wenzelm@17804
   511
(*order-sorted unification*)
wenzelm@32784
   512
fun unify (TSig {classes = (_, classes), ...}) TU (tyenv, maxidx) =
wenzelm@2964
   513
  let
wenzelm@32738
   514
    val tyvar_count = Unsynchronized.ref maxidx;
wenzelm@32738
   515
    fun gen_tyvar S = TVar ((Name.aT, Unsynchronized.inc tyvar_count), S);
wenzelm@2964
   516
wenzelm@19642
   517
    fun mg_domain a S = Sorts.mg_domain classes a S
wenzelm@19642
   518
      handle Sorts.CLASS_ERROR _ => raise TUNIFY;
wenzelm@2964
   519
wenzelm@16885
   520
    fun meet (_, []) tye = tye
wenzelm@16885
   521
      | meet (TVar (xi, S'), S) tye =
wenzelm@14790
   522
          if Sorts.sort_le classes (S', S) then tye
wenzelm@17412
   523
          else Vartab.update_new
wenzelm@17221
   524
            (xi, (S', gen_tyvar (Sorts.inter_sort classes (S', S)))) tye
wenzelm@16885
   525
      | meet (TFree (_, S'), S) tye =
wenzelm@14790
   526
          if Sorts.sort_le classes (S', S) then tye
wenzelm@2964
   527
          else raise TUNIFY
wenzelm@16885
   528
      | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
wenzelm@16885
   529
    and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
wenzelm@16885
   530
      | meets _ tye = tye;
wenzelm@2964
   531
wenzelm@16885
   532
    fun unif (ty1, ty2) tye =
wenzelm@16885
   533
      (case (devar tye ty1, devar tye ty2) of
wenzelm@2964
   534
        (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@29269
   535
          if Term.eq_ix (v, w) then
berghofe@15797
   536
            if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@14790
   537
          else if Sorts.sort_le classes (S1, S2) then
wenzelm@17412
   538
            Vartab.update_new (w, (S2, T)) tye
wenzelm@14790
   539
          else if Sorts.sort_le classes (S2, S1) then
wenzelm@17412
   540
            Vartab.update_new (v, (S1, U)) tye
wenzelm@2964
   541
          else
wenzelm@14790
   542
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
wenzelm@17412
   543
              Vartab.update_new (v, (S1, S)) (Vartab.update_new (w, (S2, S)) tye)
wenzelm@2964
   544
            end
wenzelm@2964
   545
      | (TVar (v, S), T) =>
wenzelm@2964
   546
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   547
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   548
      | (T, TVar (v, S)) =>
wenzelm@2964
   549
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   550
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   551
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   552
          if a <> b then raise TUNIFY
wenzelm@16885
   553
          else unifs (Ts, Us) tye
wenzelm@16885
   554
      | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16885
   555
    and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
wenzelm@16885
   556
      | unifs _ tye = tye;
wenzelm@16885
   557
  in (unif TU tyenv, ! tyvar_count) end;
clasohm@0
   558
wenzelm@16946
   559
(*purely structural unification*)
wenzelm@16946
   560
fun raw_unify (ty1, ty2) tye =
wenzelm@16946
   561
  (case (devar tye ty1, devar tye ty2) of
wenzelm@32784
   562
    (T as TVar (v, S1), TVar (w, S2)) =>
wenzelm@29269
   563
      if Term.eq_ix (v, w) then
wenzelm@16946
   564
        if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@17412
   565
      else Vartab.update_new (w, (S2, T)) tye
wenzelm@16946
   566
  | (TVar (v, S), T) =>
wenzelm@16946
   567
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   568
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   569
  | (T, TVar (v, S)) =>
wenzelm@16946
   570
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   571
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   572
  | (Type (a, Ts), Type (b, Us)) =>
wenzelm@16946
   573
      if a <> b then raise TUNIFY
wenzelm@16946
   574
      else raw_unifys (Ts, Us) tye
wenzelm@16946
   575
  | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16946
   576
and raw_unifys (T :: Ts, U :: Us) tye = raw_unifys (Ts, Us) (raw_unify (T, U) tye)
wenzelm@19696
   577
  | raw_unifys ([], []) tye = tye
wenzelm@19696
   578
  | raw_unifys _ _ = raise TUNIFY;
wenzelm@16946
   579
wenzelm@17804
   580
(*fast unification filter*)
wenzelm@17804
   581
fun could_unify (Type (a, Ts), Type (b, Us)) = a = b andalso could_unifys (Ts, Us)
wenzelm@17804
   582
  | could_unify (TFree (a, _), TFree (b, _)) = a = b
wenzelm@17804
   583
  | could_unify (TVar _, _) = true
wenzelm@17804
   584
  | could_unify (_, TVar _) = true
wenzelm@17804
   585
  | could_unify _ = false
wenzelm@17804
   586
and could_unifys (T :: Ts, U :: Us) = could_unify (T, U) andalso could_unifys (Ts, Us)
wenzelm@19696
   587
  | could_unifys ([], []) = true
wenzelm@19696
   588
  | could_unifys _ = false;
wenzelm@450
   589
wenzelm@17804
   590
(*equality with respect to a type environment*)
wenzelm@58949
   591
fun unified tye =
wenzelm@58949
   592
  let
wenzelm@58949
   593
    fun unif (T, T') =
wenzelm@58949
   594
      (case (devar tye T, devar tye T') of
wenzelm@58949
   595
         (Type (s, Ts), Type (s', Ts')) => s = s' andalso unifs (Ts, Ts')
wenzelm@58949
   596
       | (U, U') => U = U')
wenzelm@58949
   597
    and unifs ([], []) = true
wenzelm@58949
   598
      | unifs (T :: Ts, T' :: Ts') = unif (T', T') andalso unifs (Ts, Ts')
wenzelm@58949
   599
      | unifs _ = false;
wenzelm@58949
   600
  in if Vartab.is_empty tye then op = else unif end;
wenzelm@32030
   601
wenzelm@450
   602
clasohm@0
   603
wenzelm@14790
   604
(** extend and merge type signatures **)
wenzelm@14790
   605
wenzelm@14790
   606
(* classes *)
wenzelm@14790
   607
wenzelm@47005
   608
fun add_class context (c, cs) tsig =
wenzelm@19642
   609
  tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@16370
   610
    let
wenzelm@16370
   611
      val cs' = map (cert_class tsig) cs
wenzelm@16370
   612
        handle TYPE (msg, _, _) => error msg;
wenzelm@41254
   613
      val _ = Binding.check c;
wenzelm@47005
   614
      val (c', space') = space |> Name_Space.declare context true c;
wenzelm@47005
   615
      val classes' = classes |> Sorts.add_class (Context.pretty_generic context) (c', cs');
wenzelm@19642
   616
    in ((space', classes'), default, types) end);
wenzelm@14790
   617
wenzelm@26669
   618
fun hide_class fully c = map_tsig (fn ((space, classes), default, types) =>
wenzelm@33095
   619
  ((Name_Space.hide fully c space, classes), default, types));
wenzelm@16370
   620
wenzelm@14790
   621
wenzelm@19515
   622
(* arities *)
wenzelm@19515
   623
wenzelm@47005
   624
fun add_arity pp (t, Ss, S) tsig = tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@19515
   625
  let
wenzelm@19515
   626
    val _ =
haftmann@27302
   627
      (case lookup_type tsig t of
wenzelm@33173
   628
        SOME (LogicalType n) => if length Ss <> n then error (bad_nargs t) else ()
wenzelm@33094
   629
      | SOME _ => error ("Logical type constructor expected: " ^ quote t)
wenzelm@19515
   630
      | NONE => error (undecl_type t));
wenzelm@19515
   631
    val (Ss', S') = (map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@19515
   632
      handle TYPE (msg, _, _) => error msg;
wenzelm@47005
   633
    val classes' = classes |> Sorts.add_arities pp ((t, map (fn c' => (c', Ss')) S'));
wenzelm@19642
   634
  in ((space, classes'), default, types) end);
wenzelm@19515
   635
wenzelm@19515
   636
wenzelm@19515
   637
(* classrel *)
wenzelm@19515
   638
wenzelm@47005
   639
fun add_classrel pp rel tsig =
wenzelm@19642
   640
  tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@19515
   641
    let
wenzelm@59058
   642
      val rel' = apply2 (cert_class tsig) rel
wenzelm@19515
   643
        handle TYPE (msg, _, _) => error msg;
wenzelm@47005
   644
      val classes' = classes |> Sorts.add_classrel pp rel';
wenzelm@19642
   645
    in ((space, classes'), default, types) end);
wenzelm@19515
   646
wenzelm@19515
   647
wenzelm@14790
   648
(* default sort *)
wenzelm@14790
   649
wenzelm@19642
   650
fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types) =>
wenzelm@19642
   651
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types));
clasohm@0
   652
clasohm@0
   653
wenzelm@14790
   654
(* types *)
wenzelm@14790
   655
wenzelm@14790
   656
local
wenzelm@14790
   657
wenzelm@47005
   658
fun new_decl context (c, decl) types =
wenzelm@47005
   659
  (Binding.check c; #2 (Name_Space.define context true (c, decl) types));
wenzelm@14790
   660
wenzelm@19642
   661
fun map_types f = map_tsig (fn (classes, default, types) =>
wenzelm@19579
   662
  let
wenzelm@56025
   663
    val types' = f types;
wenzelm@56025
   664
    val _ =
wenzelm@56025
   665
      Name_Space.intern (Name_Space.space_of_table types') "dummy" = "dummy" orelse
wenzelm@56025
   666
        error "Illegal declaration of dummy type";
wenzelm@56025
   667
  in (classes, default, types') end);
wenzelm@2964
   668
wenzelm@56025
   669
fun syntactic tsig (Type (c, Ts)) =
wenzelm@56025
   670
      (case lookup_type tsig c of SOME Nonterminal => true | _ => false)
wenzelm@56025
   671
        orelse exists (syntactic tsig) Ts
wenzelm@14989
   672
  | syntactic _ _ = false;
wenzelm@14989
   673
haftmann@27302
   674
in
haftmann@27302
   675
wenzelm@47005
   676
fun add_type context (c, n) =
wenzelm@42381
   677
  if n < 0 then error ("Bad type constructor declaration " ^ Binding.print c)
wenzelm@47005
   678
  else map_types (new_decl context (c, LogicalType n));
haftmann@27302
   679
wenzelm@47005
   680
fun add_abbrev context (a, vs, rhs) tsig = tsig |> map_types (fn types =>
wenzelm@14790
   681
  let
wenzelm@30343
   682
    fun err msg =
wenzelm@42381
   683
      cat_error msg ("The error(s) above occurred in type abbreviation " ^ Binding.print a);
wenzelm@24274
   684
    val rhs' = strip_sorts (no_tvars (cert_typ_mode mode_syntax tsig rhs))
wenzelm@14790
   685
      handle TYPE (msg, _, _) => err msg;
wenzelm@33094
   686
    val _ =
wenzelm@33094
   687
      (case duplicates (op =) vs of
wenzelm@33094
   688
        [] => []
wenzelm@33094
   689
      | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
wenzelm@33094
   690
    val _ =
wenzelm@33094
   691
      (case subtract (op =) vs (map #1 (Term.add_tfreesT rhs' [])) of
wenzelm@33094
   692
        [] => []
wenzelm@33094
   693
      | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
wenzelm@56025
   694
  in types |> new_decl context (a, Abbreviation (vs, rhs', syntactic tsig rhs')) end);
clasohm@0
   695
wenzelm@47005
   696
fun add_nonterminal context = map_types o new_decl context o rpair Nonterminal;
wenzelm@14790
   697
wenzelm@14790
   698
end;
clasohm@0
   699
wenzelm@56025
   700
fun hide_type fully c = map_tsig (fn (classes, default, types) =>
wenzelm@56025
   701
  (classes, default, Name_Space.hide_table fully c types));
wenzelm@16370
   702
wenzelm@3790
   703
wenzelm@14790
   704
(* merge type signatures *)
wenzelm@14790
   705
wenzelm@47005
   706
fun merge_tsig pp (tsig1, tsig2) =
wenzelm@14790
   707
  let
wenzelm@19515
   708
    val (TSig {classes = (space1, classes1), default = default1, types = types1,
wenzelm@26641
   709
      log_types = _}) = tsig1;
wenzelm@19515
   710
    val (TSig {classes = (space2, classes2), default = default2, types = types2,
wenzelm@26641
   711
      log_types = _}) = tsig2;
wenzelm@14790
   712
wenzelm@33095
   713
    val space' = Name_Space.merge (space1, space2);
wenzelm@47005
   714
    val classes' = Sorts.merge_algebra pp (classes1, classes2);
wenzelm@19515
   715
    val default' = Sorts.inter_sort classes' (default1, default2);
wenzelm@33095
   716
    val types' = Name_Space.merge_tables (types1, types2);
wenzelm@19642
   717
  in build_tsig ((space', classes'), default', types') end;
wenzelm@14790
   718
clasohm@0
   719
end;