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