src/Pure/type.ML
author wenzelm
Wed Dec 12 23:36:07 2012 +0100 (2012-12-12 ago)
changeset 50499 f496b2b7bafb
parent 50201 c26369c9eda6
child 51701 1e29891759c4
permissions -rw-r--r--
rendering of selected dialog_result as active_result_color, depending on dynamic command status in output panel, but not static popups etc.;
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@14790
    28
  val empty_tsig: tsig
wenzelm@35669
    29
  val class_space: tsig -> Name_Space.T
wenzelm@35680
    30
  val class_alias: Name_Space.naming -> binding -> string -> tsig -> tsig
wenzelm@35669
    31
  val intern_class: tsig -> xstring -> string
wenzelm@42358
    32
  val extern_class: Proof.context -> tsig -> string -> xstring
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 intern_type: tsig -> xstring -> string
wenzelm@42358
    53
  val extern_type: Proof.context -> tsig -> string -> xstring
wenzelm@35669
    54
  val is_logtype: tsig -> string -> bool
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@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
berghofe@16650
    88
  val eq_type: 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@47005
    98
  val add_arity: Context.pretty -> arity -> tsig -> tsig
wenzelm@47005
    99
  val add_classrel: Context.pretty -> class * class -> tsig -> tsig
wenzelm@47005
   100
  val merge_tsig: Context.pretty -> 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@33094
   179
fun build_tsig (classes, default, types) =
wenzelm@14790
   180
  let
wenzelm@14790
   181
    val log_types =
wenzelm@33173
   182
      Symtab.fold (fn (c, LogicalType n) => cons (c, n) | _ => I) (snd types) []
wenzelm@33094
   183
      |> Library.sort (int_ord o pairself snd) |> map fst;
wenzelm@33094
   184
  in make_tsig (classes, default, types, log_types) end;
wenzelm@14790
   185
wenzelm@26641
   186
fun map_tsig f (TSig {classes, default, types, log_types = _}) =
wenzelm@19642
   187
  build_tsig (f (classes, default, types));
wenzelm@14790
   188
wenzelm@16370
   189
val empty_tsig =
wenzelm@50201
   190
  build_tsig ((Name_Space.empty Markup.classN, Sorts.empty_algebra), [],
wenzelm@50201
   191
    Name_Space.empty_table Markup.type_nameN);
wenzelm@14790
   192
wenzelm@14790
   193
wenzelm@14790
   194
(* classes and sorts *)
wenzelm@14790
   195
wenzelm@35669
   196
val class_space = #1 o #classes o rep_tsig;
wenzelm@35669
   197
wenzelm@35680
   198
fun class_alias naming binding name = map_tsig (fn ((space, classes), default, types) =>
wenzelm@35680
   199
  ((Name_Space.alias naming binding name space, classes), default, types));
wenzelm@35680
   200
wenzelm@35669
   201
val intern_class = Name_Space.intern o class_space;
wenzelm@42358
   202
fun extern_class ctxt = Name_Space.extern ctxt o class_space;
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@35669
   245
val type_space = #1 o #types o rep_tsig;
wenzelm@35669
   246
wenzelm@35680
   247
fun type_alias naming binding name = map_tsig (fn (classes, default, (space, types)) =>
wenzelm@35680
   248
  (classes, default, (Name_Space.alias naming binding name space, types)));
wenzelm@35680
   249
wenzelm@35669
   250
val intern_type = Name_Space.intern o type_space;
wenzelm@42358
   251
fun extern_type ctxt = Name_Space.extern ctxt o type_space;
wenzelm@35669
   252
wenzelm@35669
   253
val is_logtype = member (op =) o logical_types;
wenzelm@35669
   254
wenzelm@27313
   255
wenzelm@27313
   256
fun undecl_type c = "Undeclared type constructor: " ^ quote c;
wenzelm@27313
   257
wenzelm@33094
   258
fun lookup_type (TSig {types = (_, types), ...}) = Symtab.lookup types;
wenzelm@27313
   259
wenzelm@42468
   260
fun the_decl tsig (c, pos) =
wenzelm@35359
   261
  (case lookup_type tsig c of
wenzelm@48992
   262
    NONE => error (undecl_type c ^ Position.here pos)
wenzelm@35359
   263
  | SOME decl => decl);
wenzelm@35359
   264
wenzelm@27313
   265
wenzelm@14790
   266
(* certified types *)
wenzelm@14790
   267
wenzelm@14790
   268
fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
wenzelm@14830
   269
wenzelm@14998
   270
local
wenzelm@14998
   271
wenzelm@14998
   272
fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
wenzelm@18957
   273
  | inst_typ env (T as TFree (x, _)) = the_default T (AList.lookup (op =) env x)
wenzelm@14998
   274
  | inst_typ _ T = T;
wenzelm@14998
   275
wenzelm@24274
   276
in
wenzelm@24274
   277
wenzelm@24274
   278
fun cert_typ_mode (Mode {normalize, logical}) tsig ty =
wenzelm@14790
   279
  let
wenzelm@14790
   280
    fun err msg = raise TYPE (msg, [ty], []);
wenzelm@14790
   281
wenzelm@24274
   282
    val check_logical =
wenzelm@24274
   283
      if logical then fn c => err ("Illegal occurrence of syntactic type: " ^ quote c)
wenzelm@24274
   284
      else fn _ => ();
wenzelm@14989
   285
wenzelm@14989
   286
    fun cert (T as Type (c, Ts)) =
wenzelm@14989
   287
          let
wenzelm@14989
   288
            val Ts' = map cert Ts;
wenzelm@14989
   289
            fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
wenzelm@14989
   290
          in
wenzelm@42468
   291
            (case the_decl tsig (c, Position.none) of
wenzelm@35359
   292
              LogicalType n => (nargs n; Type (c, Ts'))
wenzelm@35359
   293
            | Abbreviation (vs, U, syn) =>
wenzelm@24274
   294
               (nargs (length vs);
wenzelm@24274
   295
                if syn then check_logical c else ();
wenzelm@14993
   296
                if normalize then inst_typ (vs ~~ Ts') U
wenzelm@14989
   297
                else Type (c, Ts'))
wenzelm@35359
   298
            | Nonterminal => (nargs 0; check_logical c; T))
wenzelm@14790
   299
          end
wenzelm@19515
   300
      | cert (TFree (x, S)) = TFree (x, cert_sort tsig S)
wenzelm@14989
   301
      | cert (TVar (xi as (_, i), S)) =
wenzelm@14993
   302
          if i < 0 then
wenzelm@14993
   303
            err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
wenzelm@19515
   304
          else TVar (xi, cert_sort tsig S);
wenzelm@14790
   305
wenzelm@14989
   306
    val ty' = cert ty;
wenzelm@14993
   307
  in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
wenzelm@14830
   308
wenzelm@24274
   309
val cert_typ = cert_typ_mode mode_default;
wenzelm@14790
   310
wenzelm@14998
   311
end;
wenzelm@14998
   312
wenzelm@14790
   313
wenzelm@19464
   314
(* type arities *)
wenzelm@19464
   315
haftmann@27302
   316
fun arity_number tsig a =
haftmann@27302
   317
  (case lookup_type tsig a of
wenzelm@33173
   318
    SOME (LogicalType n) => n
wenzelm@19464
   319
  | _ => error (undecl_type a));
wenzelm@19464
   320
wenzelm@19464
   321
fun arity_sorts _ tsig a [] = replicate (arity_number tsig a) []
wenzelm@47005
   322
  | arity_sorts pp (TSig {classes, ...}) a S =
wenzelm@47005
   323
      Sorts.mg_domain (#2 classes) a S
wenzelm@47005
   324
        handle Sorts.CLASS_ERROR err => error (Sorts.class_error pp err);
wenzelm@19464
   325
wenzelm@19464
   326
wenzelm@14790
   327
wenzelm@14790
   328
(** special treatment of type vars **)
wenzelm@14790
   329
wenzelm@36621
   330
(* sort_of_atyp *)
wenzelm@36621
   331
wenzelm@36621
   332
fun sort_of_atyp (TFree (_, S)) = S
wenzelm@36621
   333
  | sort_of_atyp (TVar (_, S)) = S
wenzelm@36621
   334
  | sort_of_atyp T = raise TYPE ("sort_of_atyp", [T], []);
wenzelm@36621
   335
wenzelm@36621
   336
wenzelm@14790
   337
(* strip_sorts *)
wenzelm@14790
   338
wenzelm@49687
   339
val strip_sorts = map_atyps
wenzelm@49687
   340
  (fn TFree (x, _) => TFree (x, [])
wenzelm@49687
   341
    | TVar (xi, _) => TVar (xi, []));
wenzelm@49687
   342
wenzelm@49687
   343
val strip_sorts_dummy = map_atyps
wenzelm@49687
   344
  (fn TFree (x, _) => TFree (x, dummyS)
wenzelm@49687
   345
    | TVar (xi, _) => TVar (xi, dummyS));
wenzelm@14790
   346
wenzelm@14790
   347
wenzelm@14790
   348
(* no_tvars *)
wenzelm@621
   349
wenzelm@621
   350
fun no_tvars T =
wenzelm@29275
   351
  (case Term.add_tvarsT T [] of [] => T
wenzelm@12501
   352
  | vs => raise TYPE ("Illegal schematic type variable(s): " ^
wenzelm@29275
   353
      commas_quote (map (Term.string_of_vname o #1) (rev vs)), [T], []));
wenzelm@621
   354
wenzelm@7641
   355
wenzelm@35845
   356
(* varify_global *)
wenzelm@621
   357
wenzelm@35845
   358
fun varify_global fixed t =
wenzelm@621
   359
  let
wenzelm@19305
   360
    val fs = Term.fold_types (Term.fold_atyps
wenzelm@19305
   361
      (fn TFree v => if member (op =) fixed v then I else insert (op =) v | _ => I)) t [];
wenzelm@29260
   362
    val used = Name.context
wenzelm@29260
   363
      |> fold_types (fold_atyps (fn TVar ((a, _), _) => Name.declare a | _ => I)) t;
wenzelm@43326
   364
    val fmap = fs ~~ map (rpair 0) (#1 (fold_map Name.variant (map fst fs) used));
wenzelm@32784
   365
    fun thaw (f as (_, S)) =
wenzelm@17184
   366
      (case AList.lookup (op =) fmap f of
skalberg@15531
   367
        NONE => TFree f
wenzelm@16946
   368
      | SOME xi => TVar (xi, S));
haftmann@21116
   369
  in (fmap, map_types (map_type_tfree thaw) t) end;
wenzelm@2964
   370
wenzelm@2964
   371
wenzelm@7641
   372
(* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
paulson@3411
   373
wenzelm@7641
   374
local
wenzelm@7641
   375
wenzelm@44116
   376
fun new_name ix (pairs, used) =
wenzelm@43324
   377
  let val v = singleton (Name.variant_list used) (string_of_indexname ix)
wenzelm@16289
   378
  in ((ix, v) :: pairs, v :: used) end;
wenzelm@621
   379
wenzelm@16289
   380
fun freeze_one alist (ix, sort) =
wenzelm@17184
   381
  TFree (the (AList.lookup (op =) alist ix), sort)
skalberg@15531
   382
    handle Option =>
wenzelm@3790
   383
      raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
wenzelm@2964
   384
wenzelm@17184
   385
fun thaw_one alist (a, sort) = TVar (the (AList.lookup (op =) alist a), sort)
wenzelm@16289
   386
  handle Option => TFree (a, sort);
wenzelm@416
   387
wenzelm@10495
   388
in
wenzelm@10495
   389
wenzelm@33832
   390
fun legacy_freeze_thaw_type T =
wenzelm@7641
   391
  let
wenzelm@44116
   392
    val used = Term.add_tfree_namesT T [];
wenzelm@44116
   393
    val (alist, _) = fold_rev new_name (map #1 (Term.add_tvarsT T [])) ([], used);
wenzelm@7641
   394
  in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
wenzelm@7641
   395
wenzelm@33832
   396
val legacy_freeze_type = #1 o legacy_freeze_thaw_type;
wenzelm@16289
   397
wenzelm@33832
   398
fun legacy_freeze_thaw t =
wenzelm@7641
   399
  let
wenzelm@44116
   400
    val used = Term.add_tfree_names t [];
wenzelm@44116
   401
    val (alist, _) = fold_rev new_name (map #1 (Term.add_tvars t [])) ([], used);
wenzelm@7641
   402
  in
wenzelm@7641
   403
    (case alist of
wenzelm@7641
   404
      [] => (t, fn x => x) (*nothing to do!*)
wenzelm@20548
   405
    | _ => (map_types (map_type_tvar (freeze_one alist)) t,
wenzelm@20548
   406
      map_types (map_type_tfree (thaw_one (map swap alist)))))
wenzelm@7641
   407
  end;
wenzelm@7641
   408
wenzelm@33832
   409
val legacy_freeze = #1 o legacy_freeze_thaw;
wenzelm@16289
   410
wenzelm@7641
   411
end;
wenzelm@7641
   412
wenzelm@256
   413
wenzelm@256
   414
wenzelm@14790
   415
(** matching and unification of types **)
wenzelm@8899
   416
berghofe@15797
   417
type tyenv = (sort * typ) Vartab.table;
wenzelm@256
   418
berghofe@15797
   419
fun tvar_clash ixn S S' = raise TYPE ("Type variable " ^
berghofe@15797
   420
  quote (Term.string_of_vname ixn) ^ " has two distinct sorts",
berghofe@15797
   421
  [TVar (ixn, S), TVar (ixn, S')], []);
clasohm@0
   422
haftmann@26327
   423
fun lookup tye (ixn, S) =
wenzelm@17412
   424
  (case Vartab.lookup tye ixn of
berghofe@15797
   425
    NONE => NONE
wenzelm@16289
   426
  | SOME (S', T) => if S = S' then SOME T else tvar_clash ixn S S');
wenzelm@16289
   427
clasohm@0
   428
wenzelm@14790
   429
(* matching *)
clasohm@0
   430
wenzelm@2964
   431
exception TYPE_MATCH;
clasohm@0
   432
wenzelm@16946
   433
fun typ_match tsig =
wenzelm@2964
   434
  let
wenzelm@41421
   435
    fun match (V as TVar (v, S), T) subs =
haftmann@26327
   436
          (case lookup subs (v, S) of
skalberg@15531
   437
            NONE =>
wenzelm@41421
   438
              if V = T then subs
wenzelm@41421
   439
              else 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@41421
   456
fun raw_match (V as TVar (v, S), T) subs =
haftmann@26327
   457
      (case lookup subs (v, S) of
wenzelm@41421
   458
        NONE => if V = T then subs else 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@16946
   470
fun raw_instance (T, U) =
wenzelm@16946
   471
  (raw_match (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@2964
   472
clasohm@0
   473
wenzelm@14790
   474
(* unification *)
wenzelm@2964
   475
clasohm@0
   476
exception TUNIFY;
clasohm@0
   477
wenzelm@26641
   478
(*occurs check*)
wenzelm@2964
   479
fun occurs v tye =
wenzelm@2964
   480
  let
wenzelm@2964
   481
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   482
      | occ (TFree _) = false
berghofe@15797
   483
      | occ (TVar (w, S)) =
wenzelm@29269
   484
          Term.eq_ix (v, w) orelse
haftmann@26327
   485
            (case lookup tye (w, S) of
skalberg@15531
   486
              NONE => false
skalberg@15531
   487
            | SOME U => occ U);
clasohm@0
   488
  in occ end;
clasohm@0
   489
wenzelm@14790
   490
(*chase variable assignments; if devar returns a type var then it must be unassigned*)
wenzelm@16885
   491
fun devar tye (T as TVar v) =
haftmann@26327
   492
      (case lookup tye v of
wenzelm@16885
   493
        SOME U => devar tye U
skalberg@15531
   494
      | NONE => T)
wenzelm@32784
   495
  | devar _ T = T;
clasohm@0
   496
wenzelm@17804
   497
(*order-sorted unification*)
wenzelm@32784
   498
fun unify (TSig {classes = (_, classes), ...}) TU (tyenv, maxidx) =
wenzelm@2964
   499
  let
wenzelm@32738
   500
    val tyvar_count = Unsynchronized.ref maxidx;
wenzelm@32738
   501
    fun gen_tyvar S = TVar ((Name.aT, Unsynchronized.inc tyvar_count), S);
wenzelm@2964
   502
wenzelm@19642
   503
    fun mg_domain a S = Sorts.mg_domain classes a S
wenzelm@19642
   504
      handle Sorts.CLASS_ERROR _ => raise TUNIFY;
wenzelm@2964
   505
wenzelm@16885
   506
    fun meet (_, []) tye = tye
wenzelm@16885
   507
      | meet (TVar (xi, S'), S) tye =
wenzelm@14790
   508
          if Sorts.sort_le classes (S', S) then tye
wenzelm@17412
   509
          else Vartab.update_new
wenzelm@17221
   510
            (xi, (S', gen_tyvar (Sorts.inter_sort classes (S', S)))) tye
wenzelm@16885
   511
      | meet (TFree (_, S'), S) tye =
wenzelm@14790
   512
          if Sorts.sort_le classes (S', S) then tye
wenzelm@2964
   513
          else raise TUNIFY
wenzelm@16885
   514
      | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
wenzelm@16885
   515
    and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
wenzelm@16885
   516
      | meets _ tye = tye;
wenzelm@2964
   517
wenzelm@16885
   518
    fun unif (ty1, ty2) tye =
wenzelm@16885
   519
      (case (devar tye ty1, devar tye ty2) of
wenzelm@2964
   520
        (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@29269
   521
          if Term.eq_ix (v, w) then
berghofe@15797
   522
            if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@14790
   523
          else if Sorts.sort_le classes (S1, S2) then
wenzelm@17412
   524
            Vartab.update_new (w, (S2, T)) tye
wenzelm@14790
   525
          else if Sorts.sort_le classes (S2, S1) then
wenzelm@17412
   526
            Vartab.update_new (v, (S1, U)) tye
wenzelm@2964
   527
          else
wenzelm@14790
   528
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
wenzelm@17412
   529
              Vartab.update_new (v, (S1, S)) (Vartab.update_new (w, (S2, S)) tye)
wenzelm@2964
   530
            end
wenzelm@2964
   531
      | (TVar (v, S), T) =>
wenzelm@2964
   532
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   533
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   534
      | (T, TVar (v, S)) =>
wenzelm@2964
   535
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   536
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   537
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   538
          if a <> b then raise TUNIFY
wenzelm@16885
   539
          else unifs (Ts, Us) tye
wenzelm@16885
   540
      | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16885
   541
    and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
wenzelm@16885
   542
      | unifs _ tye = tye;
wenzelm@16885
   543
  in (unif TU tyenv, ! tyvar_count) end;
clasohm@0
   544
wenzelm@16946
   545
(*purely structural unification*)
wenzelm@16946
   546
fun raw_unify (ty1, ty2) tye =
wenzelm@16946
   547
  (case (devar tye ty1, devar tye ty2) of
wenzelm@32784
   548
    (T as TVar (v, S1), TVar (w, S2)) =>
wenzelm@29269
   549
      if Term.eq_ix (v, w) then
wenzelm@16946
   550
        if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@17412
   551
      else Vartab.update_new (w, (S2, T)) tye
wenzelm@16946
   552
  | (TVar (v, S), T) =>
wenzelm@16946
   553
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   554
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   555
  | (T, TVar (v, S)) =>
wenzelm@16946
   556
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   557
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   558
  | (Type (a, Ts), Type (b, Us)) =>
wenzelm@16946
   559
      if a <> b then raise TUNIFY
wenzelm@16946
   560
      else raw_unifys (Ts, Us) tye
wenzelm@16946
   561
  | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16946
   562
and raw_unifys (T :: Ts, U :: Us) tye = raw_unifys (Ts, Us) (raw_unify (T, U) tye)
wenzelm@19696
   563
  | raw_unifys ([], []) tye = tye
wenzelm@19696
   564
  | raw_unifys _ _ = raise TUNIFY;
wenzelm@16946
   565
wenzelm@17804
   566
(*fast unification filter*)
wenzelm@17804
   567
fun could_unify (Type (a, Ts), Type (b, Us)) = a = b andalso could_unifys (Ts, Us)
wenzelm@17804
   568
  | could_unify (TFree (a, _), TFree (b, _)) = a = b
wenzelm@17804
   569
  | could_unify (TVar _, _) = true
wenzelm@17804
   570
  | could_unify (_, TVar _) = true
wenzelm@17804
   571
  | could_unify _ = false
wenzelm@17804
   572
and could_unifys (T :: Ts, U :: Us) = could_unify (T, U) andalso could_unifys (Ts, Us)
wenzelm@19696
   573
  | could_unifys ([], []) = true
wenzelm@19696
   574
  | could_unifys _ = false;
wenzelm@450
   575
wenzelm@17804
   576
wenzelm@17804
   577
(*equality with respect to a type environment*)
wenzelm@32030
   578
fun equal_type tye (T, T') =
wenzelm@16885
   579
  (case (devar tye T, devar tye T') of
berghofe@16650
   580
     (Type (s, Ts), Type (s', Ts')) =>
wenzelm@32030
   581
       s = s' andalso ListPair.all (equal_type tye) (Ts, Ts')
berghofe@16650
   582
   | (U, U') => U = U');
berghofe@16650
   583
wenzelm@32030
   584
fun eq_type tye =
wenzelm@32030
   585
  if Vartab.is_empty tye then op = else equal_type tye;
wenzelm@32030
   586
wenzelm@450
   587
clasohm@0
   588
wenzelm@14790
   589
(** extend and merge type signatures **)
wenzelm@14790
   590
wenzelm@14790
   591
(* classes *)
wenzelm@14790
   592
wenzelm@47005
   593
fun add_class context (c, cs) tsig =
wenzelm@19642
   594
  tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@16370
   595
    let
wenzelm@16370
   596
      val cs' = map (cert_class tsig) cs
wenzelm@16370
   597
        handle TYPE (msg, _, _) => error msg;
wenzelm@41254
   598
      val _ = Binding.check c;
wenzelm@47005
   599
      val (c', space') = space |> Name_Space.declare context true c;
wenzelm@47005
   600
      val classes' = classes |> Sorts.add_class (Context.pretty_generic context) (c', cs');
wenzelm@19642
   601
    in ((space', classes'), default, types) end);
wenzelm@14790
   602
wenzelm@26669
   603
fun hide_class fully c = map_tsig (fn ((space, classes), default, types) =>
wenzelm@33095
   604
  ((Name_Space.hide fully c space, classes), default, types));
wenzelm@16370
   605
wenzelm@14790
   606
wenzelm@19515
   607
(* arities *)
wenzelm@19515
   608
wenzelm@47005
   609
fun add_arity pp (t, Ss, S) tsig = tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@19515
   610
  let
wenzelm@19515
   611
    val _ =
haftmann@27302
   612
      (case lookup_type tsig t of
wenzelm@33173
   613
        SOME (LogicalType n) => if length Ss <> n then error (bad_nargs t) else ()
wenzelm@33094
   614
      | SOME _ => error ("Logical type constructor expected: " ^ quote t)
wenzelm@19515
   615
      | NONE => error (undecl_type t));
wenzelm@19515
   616
    val (Ss', S') = (map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@19515
   617
      handle TYPE (msg, _, _) => error msg;
wenzelm@47005
   618
    val classes' = classes |> Sorts.add_arities pp ((t, map (fn c' => (c', Ss')) S'));
wenzelm@19642
   619
  in ((space, classes'), default, types) end);
wenzelm@19515
   620
wenzelm@19515
   621
wenzelm@19515
   622
(* classrel *)
wenzelm@19515
   623
wenzelm@47005
   624
fun add_classrel pp rel tsig =
wenzelm@19642
   625
  tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@19515
   626
    let
wenzelm@19515
   627
      val rel' = pairself (cert_class tsig) rel
wenzelm@19515
   628
        handle TYPE (msg, _, _) => error msg;
wenzelm@47005
   629
      val classes' = classes |> Sorts.add_classrel pp rel';
wenzelm@19642
   630
    in ((space, classes'), default, types) end);
wenzelm@19515
   631
wenzelm@19515
   632
wenzelm@14790
   633
(* default sort *)
wenzelm@14790
   634
wenzelm@19642
   635
fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types) =>
wenzelm@19642
   636
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types));
clasohm@0
   637
clasohm@0
   638
wenzelm@14790
   639
(* types *)
wenzelm@14790
   640
wenzelm@14790
   641
local
wenzelm@14790
   642
wenzelm@47005
   643
fun new_decl context (c, decl) types =
wenzelm@47005
   644
  (Binding.check c; #2 (Name_Space.define context true (c, decl) types));
wenzelm@14790
   645
wenzelm@19642
   646
fun map_types f = map_tsig (fn (classes, default, types) =>
wenzelm@19579
   647
  let
wenzelm@19579
   648
    val (space', tab') = f types;
wenzelm@33095
   649
    val _ = Name_Space.intern space' "dummy" = "dummy" orelse
wenzelm@21858
   650
      error "Illegal declaration of dummy type";
wenzelm@19642
   651
  in (classes, default, (space', tab')) end);
wenzelm@2964
   652
wenzelm@14989
   653
fun syntactic types (Type (c, Ts)) =
wenzelm@33173
   654
      (case Symtab.lookup types c of SOME Nonterminal => true | _ => false)
wenzelm@14989
   655
        orelse exists (syntactic types) Ts
wenzelm@14989
   656
  | syntactic _ _ = false;
wenzelm@14989
   657
haftmann@27302
   658
in
haftmann@27302
   659
wenzelm@47005
   660
fun add_type context (c, n) =
wenzelm@42381
   661
  if n < 0 then error ("Bad type constructor declaration " ^ Binding.print c)
wenzelm@47005
   662
  else map_types (new_decl context (c, LogicalType n));
haftmann@27302
   663
wenzelm@47005
   664
fun add_abbrev context (a, vs, rhs) tsig = tsig |> map_types (fn types =>
wenzelm@14790
   665
  let
wenzelm@30343
   666
    fun err msg =
wenzelm@42381
   667
      cat_error msg ("The error(s) above occurred in type abbreviation " ^ Binding.print a);
wenzelm@24274
   668
    val rhs' = strip_sorts (no_tvars (cert_typ_mode mode_syntax tsig rhs))
wenzelm@14790
   669
      handle TYPE (msg, _, _) => err msg;
wenzelm@33094
   670
    val _ =
wenzelm@33094
   671
      (case duplicates (op =) vs of
wenzelm@33094
   672
        [] => []
wenzelm@33094
   673
      | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
wenzelm@33094
   674
    val _ =
wenzelm@33094
   675
      (case subtract (op =) vs (map #1 (Term.add_tfreesT rhs' [])) of
wenzelm@33094
   676
        [] => []
wenzelm@33094
   677
      | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
wenzelm@47005
   678
  in types |> new_decl context (a, Abbreviation (vs, rhs', syntactic (#2 types) rhs')) end);
clasohm@0
   679
wenzelm@47005
   680
fun add_nonterminal context = map_types o new_decl context o rpair Nonterminal;
wenzelm@14790
   681
wenzelm@14790
   682
end;
clasohm@0
   683
wenzelm@26669
   684
fun hide_type fully c = map_tsig (fn (classes, default, (space, types)) =>
wenzelm@33095
   685
  (classes, default, (Name_Space.hide fully c space, types)));
wenzelm@16370
   686
wenzelm@3790
   687
wenzelm@14790
   688
(* merge type signatures *)
wenzelm@14790
   689
wenzelm@47005
   690
fun merge_tsig pp (tsig1, tsig2) =
wenzelm@14790
   691
  let
wenzelm@19515
   692
    val (TSig {classes = (space1, classes1), default = default1, types = types1,
wenzelm@26641
   693
      log_types = _}) = tsig1;
wenzelm@19515
   694
    val (TSig {classes = (space2, classes2), default = default2, types = types2,
wenzelm@26641
   695
      log_types = _}) = tsig2;
wenzelm@14790
   696
wenzelm@33095
   697
    val space' = Name_Space.merge (space1, space2);
wenzelm@47005
   698
    val classes' = Sorts.merge_algebra pp (classes1, classes2);
wenzelm@19515
   699
    val default' = Sorts.inter_sort classes' (default1, default2);
wenzelm@33095
   700
    val types' = Name_Space.merge_tables (types1, types2);
wenzelm@19642
   701
  in build_tsig ((space', classes'), default', types') end;
wenzelm@14790
   702
clasohm@0
   703
end;