src/Pure/type.ML
author wenzelm
Mon Mar 10 15:04:01 2014 +0100 (2014-03-10)
changeset 56026 893fe12639bc
parent 56025 d74fed45fa8b
child 56050 fdccbb97915a
permissions -rw-r--r--
tuned signature -- prefer Name_Space.get with its builtin error;
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@14790
    31
  val defaultS: tsig -> sort
wenzelm@14790
    32
  val logical_types: tsig -> string list
wenzelm@14790
    33
  val eq_sort: tsig -> sort * sort -> bool
wenzelm@14790
    34
  val subsort: tsig -> sort * sort -> bool
wenzelm@14790
    35
  val of_sort: tsig -> typ * sort -> bool
wenzelm@19464
    36
  val inter_sort: tsig -> sort * sort -> sort
wenzelm@14790
    37
  val cert_class: tsig -> class -> class
wenzelm@14790
    38
  val cert_sort: tsig -> sort -> sort
wenzelm@36447
    39
  val minimize_sort: tsig -> sort -> sort
wenzelm@31946
    40
  val witness_sorts: tsig -> (typ * sort) list -> sort list -> (typ * sort) list
wenzelm@24274
    41
  type mode
wenzelm@24274
    42
  val mode_default: mode
wenzelm@24274
    43
  val mode_syntax: mode
wenzelm@24274
    44
  val mode_abbrev: mode
wenzelm@24484
    45
  val get_mode: Proof.context -> mode
wenzelm@24484
    46
  val set_mode: mode -> Proof.context -> Proof.context
wenzelm@24484
    47
  val restore_mode: Proof.context -> Proof.context -> Proof.context
wenzelm@35669
    48
  val type_space: tsig -> Name_Space.T
wenzelm@35680
    49
  val type_alias: Name_Space.naming -> binding -> string -> tsig -> tsig
wenzelm@35669
    50
  val is_logtype: tsig -> string -> bool
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@42383
    57
  val arity_sorts: Context.pretty -> 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@16946
    79
  val raw_instance: typ * typ -> bool
wenzelm@2964
    80
  exception TUNIFY
wenzelm@16946
    81
  val unify: tsig -> typ * typ -> tyenv * int -> tyenv * int
wenzelm@16946
    82
  val raw_unify: typ * typ -> tyenv -> tyenv
wenzelm@19696
    83
  val raw_unifys: typ list * typ list -> tyenv -> tyenv
wenzelm@17804
    84
  val could_unify: typ * typ -> bool
wenzelm@19696
    85
  val could_unifys: typ list * typ list -> bool
berghofe@16650
    86
  val eq_type: tyenv -> typ * typ -> bool
clasohm@0
    87
wenzelm@14790
    88
  (*extend and merge type signatures*)
wenzelm@47005
    89
  val add_class: Context.generic -> binding * class list -> tsig -> tsig
wenzelm@26669
    90
  val hide_class: bool -> string -> tsig -> tsig
wenzelm@14790
    91
  val set_defsort: sort -> tsig -> tsig
wenzelm@47005
    92
  val add_type: Context.generic -> binding * int -> tsig -> tsig
wenzelm@47005
    93
  val add_abbrev: Context.generic -> binding * string list * typ -> tsig -> tsig
wenzelm@47005
    94
  val add_nonterminal: Context.generic -> binding -> tsig -> tsig
wenzelm@26669
    95
  val hide_type: bool -> string -> tsig -> tsig
wenzelm@47005
    96
  val add_arity: Context.pretty -> arity -> tsig -> tsig
wenzelm@47005
    97
  val add_classrel: Context.pretty -> class * class -> tsig -> tsig
wenzelm@47005
    98
  val merge_tsig: Context.pretty -> tsig * tsig -> tsig
wenzelm@2964
    99
end;
wenzelm@2964
   100
wenzelm@2964
   101
structure Type: TYPE =
clasohm@0
   102
struct
clasohm@0
   103
wenzelm@39288
   104
(** constraints **)
wenzelm@39288
   105
wenzelm@39290
   106
(*indicate polymorphic Vars*)
wenzelm@39290
   107
fun mark_polymorphic T = Type ("_polymorphic_", [T]);
wenzelm@39290
   108
wenzelm@39288
   109
fun constraint T t =
wenzelm@39288
   110
  if T = dummyT then t
wenzelm@39288
   111
  else Const ("_type_constraint_", T --> T) $ t;
wenzelm@39288
   112
wenzelm@45445
   113
fun constraint_type ctxt T =
wenzelm@45445
   114
  let fun err () = error ("Malformed internal type constraint: " ^ Syntax.string_of_typ ctxt T);
wenzelm@45445
   115
  in (case T of Type ("fun", [A, B]) => if A = B then A else err () | _ => err ()) end;
wenzelm@45445
   116
wenzelm@39292
   117
fun strip_constraints (Const ("_type_constraint_", _) $ t) = strip_constraints t
wenzelm@39292
   118
  | strip_constraints (t $ u) = strip_constraints t $ strip_constraints u
wenzelm@39292
   119
  | strip_constraints (Abs (x, T, t)) = Abs (x, T, strip_constraints t)
wenzelm@39292
   120
  | strip_constraints a = a;
wenzelm@39292
   121
wenzelm@42383
   122
fun appl_error ctxt (Const ("_type_constraint_", Type ("fun", [T, _]))) _ u U =
wenzelm@39289
   123
      cat_lines
wenzelm@39289
   124
       ["Failed to meet type constraint:", "",
wenzelm@39289
   125
        Pretty.string_of (Pretty.block
wenzelm@42383
   126
         [Pretty.str "Term:", Pretty.brk 2, Syntax.pretty_term ctxt u,
wenzelm@42383
   127
          Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ ctxt U]),
wenzelm@39289
   128
        Pretty.string_of (Pretty.block
wenzelm@42383
   129
         [Pretty.str "Type:", Pretty.brk 2, Syntax.pretty_typ ctxt T])]
wenzelm@42383
   130
  | appl_error ctxt t T u U =
wenzelm@39289
   131
      cat_lines
wenzelm@39289
   132
       ["Type error in application: " ^
wenzelm@39289
   133
          (case T of
wenzelm@39289
   134
            Type ("fun", _) => "incompatible operand type"
wenzelm@39289
   135
          | _ => "operator not of function type"),
wenzelm@39289
   136
        "",
wenzelm@39289
   137
        Pretty.string_of (Pretty.block
wenzelm@42383
   138
          [Pretty.str "Operator:", Pretty.brk 2, Syntax.pretty_term ctxt t,
wenzelm@42383
   139
            Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ ctxt T]),
wenzelm@39289
   140
        Pretty.string_of (Pretty.block
wenzelm@42383
   141
          [Pretty.str "Operand:", Pretty.brk 3, Syntax.pretty_term ctxt u,
wenzelm@42383
   142
            Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ ctxt U])];
wenzelm@39289
   143
wenzelm@39288
   144
wenzelm@39288
   145
wenzelm@14790
   146
(** type signatures and certified types **)
wenzelm@2964
   147
wenzelm@14790
   148
(* type declarations *)
wenzelm@14790
   149
wenzelm@14790
   150
datatype decl =
wenzelm@14790
   151
  LogicalType of int |
wenzelm@14989
   152
  Abbreviation of string list * typ * bool |
wenzelm@14790
   153
  Nonterminal;
wenzelm@14790
   154
wenzelm@14790
   155
wenzelm@14790
   156
(* type tsig *)
wenzelm@14790
   157
wenzelm@14790
   158
datatype tsig =
wenzelm@14790
   159
  TSig of {
wenzelm@33095
   160
    classes: Name_Space.T * Sorts.algebra,  (*order-sorted algebra of type classes*)
wenzelm@16370
   161
    default: sort,                          (*default sort on input*)
wenzelm@33173
   162
    types: decl Name_Space.table,           (*declared types*)
wenzelm@26641
   163
    log_types: string list};                (*logical types sorted by number of arguments*)
wenzelm@14790
   164
wenzelm@35669
   165
fun eq_tsig
wenzelm@35669
   166
   (TSig {classes = classes1, default = default1, types = types1, log_types = _},
wenzelm@35669
   167
    TSig {classes = classes2, default = default2, types = types2, log_types = _}) =
wenzelm@35669
   168
  pointer_eq (classes1, classes2) andalso
wenzelm@35669
   169
  default1 = default2 andalso
wenzelm@35669
   170
  pointer_eq (types1, types2);
wenzelm@35669
   171
wenzelm@14790
   172
fun rep_tsig (TSig comps) = comps;
wenzelm@14790
   173
wenzelm@26641
   174
fun make_tsig (classes, default, types, log_types) =
wenzelm@26641
   175
  TSig {classes = classes, default = default, types = types, log_types = log_types};
wenzelm@14790
   176
wenzelm@33094
   177
fun build_tsig (classes, default, types) =
wenzelm@14790
   178
  let
wenzelm@14790
   179
    val log_types =
wenzelm@56025
   180
      Name_Space.fold_table (fn (c, LogicalType n) => cons (c, n) | _ => I) types []
wenzelm@33094
   181
      |> Library.sort (int_ord o pairself snd) |> map fst;
wenzelm@33094
   182
  in make_tsig (classes, default, types, log_types) end;
wenzelm@14790
   183
wenzelm@26641
   184
fun map_tsig f (TSig {classes, default, types, log_types = _}) =
wenzelm@19642
   185
  build_tsig (f (classes, default, types));
wenzelm@14790
   186
wenzelm@16370
   187
val empty_tsig =
wenzelm@50201
   188
  build_tsig ((Name_Space.empty Markup.classN, Sorts.empty_algebra), [],
wenzelm@50201
   189
    Name_Space.empty_table Markup.type_nameN);
wenzelm@14790
   190
wenzelm@14790
   191
wenzelm@14790
   192
(* classes and sorts *)
wenzelm@14790
   193
wenzelm@35669
   194
val class_space = #1 o #classes o rep_tsig;
wenzelm@35669
   195
wenzelm@35680
   196
fun class_alias naming binding name = map_tsig (fn ((space, classes), default, types) =>
wenzelm@35680
   197
  ((Name_Space.alias naming binding name space, classes), default, types));
wenzelm@35680
   198
wenzelm@14790
   199
fun defaultS (TSig {default, ...}) = default;
wenzelm@14790
   200
fun logical_types (TSig {log_types, ...}) = log_types;
wenzelm@14790
   201
wenzelm@16370
   202
fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq (#2 classes);
wenzelm@16370
   203
fun subsort (TSig {classes, ...}) = Sorts.sort_le (#2 classes);
wenzelm@19642
   204
fun of_sort (TSig {classes, ...}) = Sorts.of_sort (#2 classes);
wenzelm@19464
   205
fun inter_sort (TSig {classes, ...}) = Sorts.inter_sort (#2 classes);
wenzelm@14790
   206
wenzelm@45595
   207
fun cert_class (TSig {classes = (_, algebra), ...}) c =
wenzelm@45595
   208
  if can (Graph.get_entry (Sorts.classes_of algebra)) c then c
wenzelm@45595
   209
  else raise TYPE ("Undeclared class: " ^ quote c, [], []);
wenzelm@45595
   210
wenzelm@45595
   211
val cert_sort = map o cert_class;
wenzelm@45595
   212
wenzelm@36447
   213
fun minimize_sort (TSig {classes, ...}) = Sorts.minimize_sort (#2 classes);
wenzelm@19515
   214
wenzelm@32784
   215
fun witness_sorts (TSig {classes, log_types, ...}) =
wenzelm@19642
   216
  Sorts.witness_sorts (#2 classes) log_types;
wenzelm@14790
   217
wenzelm@14790
   218
wenzelm@24274
   219
(* certification mode *)
wenzelm@24274
   220
wenzelm@24274
   221
datatype mode = Mode of {normalize: bool, logical: bool};
wenzelm@24274
   222
wenzelm@24274
   223
val mode_default = Mode {normalize = true, logical = true};
wenzelm@24274
   224
val mode_syntax = Mode {normalize = true, logical = false};
wenzelm@24274
   225
val mode_abbrev = Mode {normalize = false, logical = false};
wenzelm@24274
   226
wenzelm@33519
   227
structure Mode = Proof_Data
wenzelm@24484
   228
(
wenzelm@24484
   229
  type T = mode;
wenzelm@24484
   230
  fun init _ = mode_default;
wenzelm@24484
   231
);
wenzelm@24484
   232
wenzelm@24484
   233
val get_mode = Mode.get;
wenzelm@24484
   234
fun set_mode mode = Mode.map (K mode);
wenzelm@24484
   235
fun restore_mode ctxt = set_mode (get_mode ctxt);
wenzelm@24484
   236
wenzelm@24274
   237
wenzelm@35669
   238
(* types *)
wenzelm@35669
   239
wenzelm@56025
   240
val type_space = Name_Space.space_of_table o #types o rep_tsig;
wenzelm@35669
   241
wenzelm@56025
   242
fun type_alias naming binding name = map_tsig (fn (classes, default, types) =>
wenzelm@56025
   243
  (classes, default, (Name_Space.alias_table naming binding name types)));
wenzelm@35680
   244
wenzelm@35669
   245
val is_logtype = member (op =) o logical_types;
wenzelm@35669
   246
wenzelm@27313
   247
wenzelm@27313
   248
fun undecl_type c = "Undeclared type constructor: " ^ quote c;
wenzelm@27313
   249
wenzelm@56025
   250
fun lookup_type (TSig {types, ...}) = Option.map #2 o Name_Space.lookup_key types;
wenzelm@27313
   251
wenzelm@55956
   252
fun check_decl context (TSig {types, ...}) (c, pos) =
wenzelm@55956
   253
  Name_Space.check_reports context types (c, [pos]);
wenzelm@55841
   254
wenzelm@42468
   255
fun the_decl tsig (c, pos) =
wenzelm@35359
   256
  (case lookup_type tsig c of
wenzelm@48992
   257
    NONE => error (undecl_type c ^ Position.here pos)
wenzelm@35359
   258
  | SOME decl => decl);
wenzelm@35359
   259
wenzelm@27313
   260
wenzelm@14790
   261
(* certified types *)
wenzelm@14790
   262
wenzelm@14790
   263
fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
wenzelm@14830
   264
wenzelm@14998
   265
local
wenzelm@14998
   266
wenzelm@14998
   267
fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
wenzelm@18957
   268
  | inst_typ env (T as TFree (x, _)) = the_default T (AList.lookup (op =) env x)
wenzelm@14998
   269
  | inst_typ _ T = T;
wenzelm@14998
   270
wenzelm@24274
   271
in
wenzelm@24274
   272
wenzelm@24274
   273
fun cert_typ_mode (Mode {normalize, logical}) tsig ty =
wenzelm@14790
   274
  let
wenzelm@14790
   275
    fun err msg = raise TYPE (msg, [ty], []);
wenzelm@14790
   276
wenzelm@24274
   277
    val check_logical =
wenzelm@24274
   278
      if logical then fn c => err ("Illegal occurrence of syntactic type: " ^ quote c)
wenzelm@24274
   279
      else fn _ => ();
wenzelm@14989
   280
wenzelm@14989
   281
    fun cert (T as Type (c, Ts)) =
wenzelm@14989
   282
          let
wenzelm@14989
   283
            val Ts' = map cert Ts;
wenzelm@14989
   284
            fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
wenzelm@14989
   285
          in
wenzelm@42468
   286
            (case the_decl tsig (c, Position.none) of
wenzelm@35359
   287
              LogicalType n => (nargs n; Type (c, Ts'))
wenzelm@35359
   288
            | Abbreviation (vs, U, syn) =>
wenzelm@24274
   289
               (nargs (length vs);
wenzelm@24274
   290
                if syn then check_logical c else ();
wenzelm@14993
   291
                if normalize then inst_typ (vs ~~ Ts') U
wenzelm@14989
   292
                else Type (c, Ts'))
wenzelm@35359
   293
            | Nonterminal => (nargs 0; check_logical c; T))
wenzelm@14790
   294
          end
wenzelm@19515
   295
      | cert (TFree (x, S)) = TFree (x, cert_sort tsig S)
wenzelm@14989
   296
      | cert (TVar (xi as (_, i), S)) =
wenzelm@14993
   297
          if i < 0 then
wenzelm@14993
   298
            err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
wenzelm@19515
   299
          else TVar (xi, cert_sort tsig S);
wenzelm@14790
   300
wenzelm@14989
   301
    val ty' = cert ty;
wenzelm@14993
   302
  in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
wenzelm@14830
   303
wenzelm@24274
   304
val cert_typ = cert_typ_mode mode_default;
wenzelm@14790
   305
wenzelm@14998
   306
end;
wenzelm@14998
   307
wenzelm@14790
   308
wenzelm@19464
   309
(* type arities *)
wenzelm@19464
   310
haftmann@27302
   311
fun arity_number tsig a =
haftmann@27302
   312
  (case lookup_type tsig a of
wenzelm@33173
   313
    SOME (LogicalType n) => n
wenzelm@19464
   314
  | _ => error (undecl_type a));
wenzelm@19464
   315
wenzelm@19464
   316
fun arity_sorts _ tsig a [] = replicate (arity_number tsig a) []
wenzelm@47005
   317
  | arity_sorts pp (TSig {classes, ...}) a S =
wenzelm@47005
   318
      Sorts.mg_domain (#2 classes) a S
wenzelm@47005
   319
        handle Sorts.CLASS_ERROR err => error (Sorts.class_error pp err);
wenzelm@19464
   320
wenzelm@19464
   321
wenzelm@14790
   322
wenzelm@14790
   323
(** special treatment of type vars **)
wenzelm@14790
   324
wenzelm@36621
   325
(* sort_of_atyp *)
wenzelm@36621
   326
wenzelm@36621
   327
fun sort_of_atyp (TFree (_, S)) = S
wenzelm@36621
   328
  | sort_of_atyp (TVar (_, S)) = S
wenzelm@36621
   329
  | sort_of_atyp T = raise TYPE ("sort_of_atyp", [T], []);
wenzelm@36621
   330
wenzelm@36621
   331
wenzelm@14790
   332
(* strip_sorts *)
wenzelm@14790
   333
wenzelm@49687
   334
val strip_sorts = map_atyps
wenzelm@49687
   335
  (fn TFree (x, _) => TFree (x, [])
wenzelm@49687
   336
    | TVar (xi, _) => TVar (xi, []));
wenzelm@49687
   337
wenzelm@49687
   338
val strip_sorts_dummy = map_atyps
wenzelm@49687
   339
  (fn TFree (x, _) => TFree (x, dummyS)
wenzelm@49687
   340
    | TVar (xi, _) => TVar (xi, dummyS));
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)
wenzelm@51930
   377
    handle Option.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@51930
   381
  handle Option.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
wenzelm@51701
   414
fun tvar_clash ixn S S' =
wenzelm@51701
   415
  raise TYPE ("Type variable has two distinct sorts", [TVar (ixn, S), TVar (ixn, S')], []);
clasohm@0
   416
haftmann@26327
   417
fun lookup tye (ixn, S) =
wenzelm@17412
   418
  (case Vartab.lookup tye ixn of
berghofe@15797
   419
    NONE => NONE
wenzelm@16289
   420
  | SOME (S', T) => if S = S' then SOME T else tvar_clash ixn S S');
wenzelm@16289
   421
clasohm@0
   422
wenzelm@14790
   423
(* matching *)
clasohm@0
   424
wenzelm@2964
   425
exception TYPE_MATCH;
clasohm@0
   426
wenzelm@16946
   427
fun typ_match tsig =
wenzelm@2964
   428
  let
wenzelm@41421
   429
    fun match (V as TVar (v, S), T) subs =
haftmann@26327
   430
          (case lookup subs (v, S) of
skalberg@15531
   431
            NONE =>
wenzelm@41421
   432
              if V = T then subs
wenzelm@41421
   433
              else if of_sort tsig (T, S) then Vartab.update_new (v, (S, T)) subs
wenzelm@14993
   434
              else raise TYPE_MATCH
skalberg@15531
   435
          | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16340
   436
      | match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@2964
   437
          if a <> b then raise TYPE_MATCH
wenzelm@16885
   438
          else matches (Ts, Us) subs
wenzelm@16340
   439
      | match (TFree x, TFree y) subs =
wenzelm@2964
   440
          if x = y then subs else raise TYPE_MATCH
wenzelm@16885
   441
      | match _ _ = raise TYPE_MATCH
wenzelm@16885
   442
    and matches (T :: Ts, U :: Us) subs = matches (Ts, Us) (match (T, U) subs)
wenzelm@16885
   443
      | matches _ subs = subs;
wenzelm@16946
   444
  in match end;
clasohm@0
   445
wenzelm@14790
   446
fun typ_instance tsig (T, U) =
wenzelm@16946
   447
  (typ_match tsig (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@16946
   448
wenzelm@16946
   449
(*purely structural matching*)
wenzelm@41421
   450
fun raw_match (V as TVar (v, S), T) subs =
haftmann@26327
   451
      (case lookup subs (v, S) of
wenzelm@41421
   452
        NONE => if V = T then subs else Vartab.update_new (v, (S, T)) subs
wenzelm@16946
   453
      | SOME U => if U = T then subs else raise TYPE_MATCH)
wenzelm@16946
   454
  | raw_match (Type (a, Ts), Type (b, Us)) subs =
wenzelm@16946
   455
      if a <> b then raise TYPE_MATCH
wenzelm@16946
   456
      else raw_matches (Ts, Us) subs
wenzelm@16946
   457
  | raw_match (TFree x, TFree y) subs =
wenzelm@16946
   458
      if x = y then subs else raise TYPE_MATCH
wenzelm@16946
   459
  | raw_match _ _ = raise TYPE_MATCH
wenzelm@16946
   460
and raw_matches (T :: Ts, U :: Us) subs = raw_matches (Ts, Us) (raw_match (T, U) subs)
wenzelm@19694
   461
  | raw_matches ([], []) subs = subs
wenzelm@19694
   462
  | raw_matches _ _ = raise TYPE_MATCH;
wenzelm@16946
   463
wenzelm@16946
   464
fun raw_instance (T, U) =
wenzelm@16946
   465
  (raw_match (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
wenzelm@2964
   466
clasohm@0
   467
wenzelm@14790
   468
(* unification *)
wenzelm@2964
   469
clasohm@0
   470
exception TUNIFY;
clasohm@0
   471
wenzelm@26641
   472
(*occurs check*)
wenzelm@2964
   473
fun occurs v tye =
wenzelm@2964
   474
  let
wenzelm@2964
   475
    fun occ (Type (_, Ts)) = exists occ Ts
wenzelm@2964
   476
      | occ (TFree _) = false
berghofe@15797
   477
      | occ (TVar (w, S)) =
wenzelm@29269
   478
          Term.eq_ix (v, w) orelse
haftmann@26327
   479
            (case lookup tye (w, S) of
skalberg@15531
   480
              NONE => false
skalberg@15531
   481
            | SOME U => occ U);
clasohm@0
   482
  in occ end;
clasohm@0
   483
wenzelm@14790
   484
(*chase variable assignments; if devar returns a type var then it must be unassigned*)
wenzelm@16885
   485
fun devar tye (T as TVar v) =
haftmann@26327
   486
      (case lookup tye v of
wenzelm@16885
   487
        SOME U => devar tye U
skalberg@15531
   488
      | NONE => T)
wenzelm@32784
   489
  | devar _ T = T;
clasohm@0
   490
wenzelm@17804
   491
(*order-sorted unification*)
wenzelm@32784
   492
fun unify (TSig {classes = (_, classes), ...}) TU (tyenv, maxidx) =
wenzelm@2964
   493
  let
wenzelm@32738
   494
    val tyvar_count = Unsynchronized.ref maxidx;
wenzelm@32738
   495
    fun gen_tyvar S = TVar ((Name.aT, Unsynchronized.inc tyvar_count), S);
wenzelm@2964
   496
wenzelm@19642
   497
    fun mg_domain a S = Sorts.mg_domain classes a S
wenzelm@19642
   498
      handle Sorts.CLASS_ERROR _ => raise TUNIFY;
wenzelm@2964
   499
wenzelm@16885
   500
    fun meet (_, []) tye = tye
wenzelm@16885
   501
      | meet (TVar (xi, S'), S) tye =
wenzelm@14790
   502
          if Sorts.sort_le classes (S', S) then tye
wenzelm@17412
   503
          else Vartab.update_new
wenzelm@17221
   504
            (xi, (S', gen_tyvar (Sorts.inter_sort classes (S', S)))) tye
wenzelm@16885
   505
      | meet (TFree (_, S'), S) tye =
wenzelm@14790
   506
          if Sorts.sort_le classes (S', S) then tye
wenzelm@2964
   507
          else raise TUNIFY
wenzelm@16885
   508
      | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
wenzelm@16885
   509
    and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
wenzelm@16885
   510
      | meets _ tye = tye;
wenzelm@2964
   511
wenzelm@16885
   512
    fun unif (ty1, ty2) tye =
wenzelm@16885
   513
      (case (devar tye ty1, devar tye ty2) of
wenzelm@2964
   514
        (T as TVar (v, S1), U as TVar (w, S2)) =>
wenzelm@29269
   515
          if Term.eq_ix (v, w) then
berghofe@15797
   516
            if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@14790
   517
          else if Sorts.sort_le classes (S1, S2) then
wenzelm@17412
   518
            Vartab.update_new (w, (S2, T)) tye
wenzelm@14790
   519
          else if Sorts.sort_le classes (S2, S1) then
wenzelm@17412
   520
            Vartab.update_new (v, (S1, U)) tye
wenzelm@2964
   521
          else
wenzelm@14790
   522
            let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
wenzelm@17412
   523
              Vartab.update_new (v, (S1, S)) (Vartab.update_new (w, (S2, S)) tye)
wenzelm@2964
   524
            end
wenzelm@2964
   525
      | (TVar (v, S), T) =>
wenzelm@2964
   526
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   527
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   528
      | (T, TVar (v, S)) =>
wenzelm@2964
   529
          if occurs v tye T then raise TUNIFY
wenzelm@17412
   530
          else meet (T, S) (Vartab.update_new (v, (S, T)) tye)
wenzelm@2964
   531
      | (Type (a, Ts), Type (b, Us)) =>
wenzelm@2964
   532
          if a <> b then raise TUNIFY
wenzelm@16885
   533
          else unifs (Ts, Us) tye
wenzelm@16885
   534
      | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16885
   535
    and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
wenzelm@16885
   536
      | unifs _ tye = tye;
wenzelm@16885
   537
  in (unif TU tyenv, ! tyvar_count) end;
clasohm@0
   538
wenzelm@16946
   539
(*purely structural unification*)
wenzelm@16946
   540
fun raw_unify (ty1, ty2) tye =
wenzelm@16946
   541
  (case (devar tye ty1, devar tye ty2) of
wenzelm@32784
   542
    (T as TVar (v, S1), TVar (w, S2)) =>
wenzelm@29269
   543
      if Term.eq_ix (v, w) then
wenzelm@16946
   544
        if S1 = S2 then tye else tvar_clash v S1 S2
wenzelm@17412
   545
      else Vartab.update_new (w, (S2, T)) tye
wenzelm@16946
   546
  | (TVar (v, S), T) =>
wenzelm@16946
   547
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   548
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   549
  | (T, TVar (v, S)) =>
wenzelm@16946
   550
      if occurs v tye T then raise TUNIFY
wenzelm@17412
   551
      else Vartab.update_new (v, (S, T)) tye
wenzelm@16946
   552
  | (Type (a, Ts), Type (b, Us)) =>
wenzelm@16946
   553
      if a <> b then raise TUNIFY
wenzelm@16946
   554
      else raw_unifys (Ts, Us) tye
wenzelm@16946
   555
  | (T, U) => if T = U then tye else raise TUNIFY)
wenzelm@16946
   556
and raw_unifys (T :: Ts, U :: Us) tye = raw_unifys (Ts, Us) (raw_unify (T, U) tye)
wenzelm@19696
   557
  | raw_unifys ([], []) tye = tye
wenzelm@19696
   558
  | raw_unifys _ _ = raise TUNIFY;
wenzelm@16946
   559
wenzelm@17804
   560
(*fast unification filter*)
wenzelm@17804
   561
fun could_unify (Type (a, Ts), Type (b, Us)) = a = b andalso could_unifys (Ts, Us)
wenzelm@17804
   562
  | could_unify (TFree (a, _), TFree (b, _)) = a = b
wenzelm@17804
   563
  | could_unify (TVar _, _) = true
wenzelm@17804
   564
  | could_unify (_, TVar _) = true
wenzelm@17804
   565
  | could_unify _ = false
wenzelm@17804
   566
and could_unifys (T :: Ts, U :: Us) = could_unify (T, U) andalso could_unifys (Ts, Us)
wenzelm@19696
   567
  | could_unifys ([], []) = true
wenzelm@19696
   568
  | could_unifys _ = false;
wenzelm@450
   569
wenzelm@17804
   570
wenzelm@17804
   571
(*equality with respect to a type environment*)
wenzelm@32030
   572
fun equal_type tye (T, T') =
wenzelm@16885
   573
  (case (devar tye T, devar tye T') of
berghofe@16650
   574
     (Type (s, Ts), Type (s', Ts')) =>
wenzelm@32030
   575
       s = s' andalso ListPair.all (equal_type tye) (Ts, Ts')
berghofe@16650
   576
   | (U, U') => U = U');
berghofe@16650
   577
wenzelm@32030
   578
fun eq_type tye =
wenzelm@32030
   579
  if Vartab.is_empty tye then op = else equal_type tye;
wenzelm@32030
   580
wenzelm@450
   581
clasohm@0
   582
wenzelm@14790
   583
(** extend and merge type signatures **)
wenzelm@14790
   584
wenzelm@14790
   585
(* classes *)
wenzelm@14790
   586
wenzelm@47005
   587
fun add_class context (c, cs) tsig =
wenzelm@19642
   588
  tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@16370
   589
    let
wenzelm@16370
   590
      val cs' = map (cert_class tsig) cs
wenzelm@16370
   591
        handle TYPE (msg, _, _) => error msg;
wenzelm@41254
   592
      val _ = Binding.check c;
wenzelm@47005
   593
      val (c', space') = space |> Name_Space.declare context true c;
wenzelm@47005
   594
      val classes' = classes |> Sorts.add_class (Context.pretty_generic context) (c', cs');
wenzelm@19642
   595
    in ((space', classes'), default, types) end);
wenzelm@14790
   596
wenzelm@26669
   597
fun hide_class fully c = map_tsig (fn ((space, classes), default, types) =>
wenzelm@33095
   598
  ((Name_Space.hide fully c space, classes), default, types));
wenzelm@16370
   599
wenzelm@14790
   600
wenzelm@19515
   601
(* arities *)
wenzelm@19515
   602
wenzelm@47005
   603
fun add_arity pp (t, Ss, S) tsig = tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@19515
   604
  let
wenzelm@19515
   605
    val _ =
haftmann@27302
   606
      (case lookup_type tsig t of
wenzelm@33173
   607
        SOME (LogicalType n) => if length Ss <> n then error (bad_nargs t) else ()
wenzelm@33094
   608
      | SOME _ => error ("Logical type constructor expected: " ^ quote t)
wenzelm@19515
   609
      | NONE => error (undecl_type t));
wenzelm@19515
   610
    val (Ss', S') = (map (cert_sort tsig) Ss, cert_sort tsig S)
wenzelm@19515
   611
      handle TYPE (msg, _, _) => error msg;
wenzelm@47005
   612
    val classes' = classes |> Sorts.add_arities pp ((t, map (fn c' => (c', Ss')) S'));
wenzelm@19642
   613
  in ((space, classes'), default, types) end);
wenzelm@19515
   614
wenzelm@19515
   615
wenzelm@19515
   616
(* classrel *)
wenzelm@19515
   617
wenzelm@47005
   618
fun add_classrel pp rel tsig =
wenzelm@19642
   619
  tsig |> map_tsig (fn ((space, classes), default, types) =>
wenzelm@19515
   620
    let
wenzelm@19515
   621
      val rel' = pairself (cert_class tsig) rel
wenzelm@19515
   622
        handle TYPE (msg, _, _) => error msg;
wenzelm@47005
   623
      val classes' = classes |> Sorts.add_classrel pp rel';
wenzelm@19642
   624
    in ((space, classes'), default, types) end);
wenzelm@19515
   625
wenzelm@19515
   626
wenzelm@14790
   627
(* default sort *)
wenzelm@14790
   628
wenzelm@19642
   629
fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types) =>
wenzelm@19642
   630
  (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types));
clasohm@0
   631
clasohm@0
   632
wenzelm@14790
   633
(* types *)
wenzelm@14790
   634
wenzelm@14790
   635
local
wenzelm@14790
   636
wenzelm@47005
   637
fun new_decl context (c, decl) types =
wenzelm@47005
   638
  (Binding.check c; #2 (Name_Space.define context true (c, decl) types));
wenzelm@14790
   639
wenzelm@19642
   640
fun map_types f = map_tsig (fn (classes, default, types) =>
wenzelm@19579
   641
  let
wenzelm@56025
   642
    val types' = f types;
wenzelm@56025
   643
    val _ =
wenzelm@56025
   644
      Name_Space.intern (Name_Space.space_of_table types') "dummy" = "dummy" orelse
wenzelm@56025
   645
        error "Illegal declaration of dummy type";
wenzelm@56025
   646
  in (classes, default, types') end);
wenzelm@2964
   647
wenzelm@56025
   648
fun syntactic tsig (Type (c, Ts)) =
wenzelm@56025
   649
      (case lookup_type tsig c of SOME Nonterminal => true | _ => false)
wenzelm@56025
   650
        orelse exists (syntactic tsig) 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@56025
   673
  in types |> new_decl context (a, Abbreviation (vs, rhs', syntactic tsig 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@56025
   679
fun hide_type fully c = map_tsig (fn (classes, default, types) =>
wenzelm@56025
   680
  (classes, default, Name_Space.hide_table fully c 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;