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