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