src/HOL/Tools/Nitpick/nitpick_nut.ML
author griff
Tue Apr 03 17:26:30 2012 +0900 (2012-04-03)
changeset 47433 07f4bf913230
parent 46115 ecab67f5a5c2
child 47753 792634c6679e
permissions -rw-r--r--
renamed "rel_comp" to "relcomp" (to be consistent with, e.g., "relpow")
blanchet@33982
     1
(*  Title:      HOL/Tools/Nitpick/nitpick_nut.ML
blanchet@33192
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@34982
     3
    Copyright   2008, 2009, 2010
blanchet@33192
     4
blanchet@33192
     5
Nitpick underlying terms (nuts).
blanchet@33192
     6
*)
blanchet@33192
     7
blanchet@33192
     8
signature NITPICK_NUT =
blanchet@33192
     9
sig
blanchet@38170
    10
  type styp = Nitpick_Util.styp
blanchet@35070
    11
  type hol_context = Nitpick_HOL.hol_context
blanchet@33232
    12
  type scope = Nitpick_Scope.scope
blanchet@33232
    13
  type name_pool = Nitpick_Peephole.name_pool
blanchet@33232
    14
  type rep = Nitpick_Rep.rep
blanchet@33192
    15
blanchet@33192
    16
  datatype cst =
blanchet@33192
    17
    False |
blanchet@33192
    18
    True |
blanchet@33192
    19
    Iden |
blanchet@33192
    20
    Num of int |
blanchet@33192
    21
    Unknown |
blanchet@33192
    22
    Unrep |
blanchet@33192
    23
    Suc |
blanchet@33192
    24
    Add |
blanchet@33192
    25
    Subtract |
blanchet@33192
    26
    Multiply |
blanchet@33192
    27
    Divide |
blanchet@33192
    28
    Gcd |
blanchet@33192
    29
    Lcm |
blanchet@33192
    30
    Fracs |
blanchet@33192
    31
    NormFrac |
blanchet@33192
    32
    NatToInt |
blanchet@33192
    33
    IntToNat
blanchet@33192
    34
blanchet@33192
    35
  datatype op1 =
blanchet@33192
    36
    Not |
blanchet@33192
    37
    Finite |
blanchet@33192
    38
    Converse |
blanchet@33192
    39
    Closure |
blanchet@33192
    40
    SingletonSet |
blanchet@34936
    41
    IsUnknown |
blanchet@35671
    42
    SafeThe |
blanchet@33192
    43
    First |
blanchet@33192
    44
    Second |
blanchet@33192
    45
    Cast
blanchet@33192
    46
blanchet@33192
    47
  datatype op2 =
blanchet@33192
    48
    All |
blanchet@33192
    49
    Exist |
blanchet@33192
    50
    Or |
blanchet@33192
    51
    And |
blanchet@33192
    52
    Less |
blanchet@33192
    53
    Subset |
blanchet@33192
    54
    DefEq |
blanchet@33192
    55
    Eq |
blanchet@33192
    56
    Triad |
blanchet@33192
    57
    Composition |
blanchet@33192
    58
    Apply |
blanchet@33192
    59
    Lambda
blanchet@33192
    60
blanchet@33192
    61
  datatype op3 =
blanchet@33192
    62
    Let |
blanchet@33192
    63
    If
blanchet@33192
    64
blanchet@33192
    65
  datatype nut =
blanchet@33192
    66
    Cst of cst * typ * rep |
blanchet@33192
    67
    Op1 of op1 * typ * rep * nut |
blanchet@33192
    68
    Op2 of op2 * typ * rep * nut * nut |
blanchet@33192
    69
    Op3 of op3 * typ * rep * nut * nut * nut |
blanchet@33192
    70
    Tuple of typ * rep * nut list |
blanchet@33192
    71
    Construct of nut list * typ * rep * nut list |
blanchet@33192
    72
    BoundName of int * typ * rep * string |
blanchet@33192
    73
    FreeName of string * typ * rep |
blanchet@33192
    74
    ConstName of string * typ * rep |
blanchet@33192
    75
    BoundRel of Kodkod.n_ary_index * typ * rep * string |
blanchet@33192
    76
    FreeRel of Kodkod.n_ary_index * typ * rep * string |
blanchet@33192
    77
    RelReg of int * typ * rep |
blanchet@33192
    78
    FormulaReg of int * typ * rep
blanchet@33192
    79
blanchet@33192
    80
  structure NameTable : TABLE
blanchet@33192
    81
blanchet@33192
    82
  exception NUT of string * nut list
blanchet@33192
    83
blanchet@33192
    84
  val string_for_nut : Proof.context -> nut -> string
blanchet@33192
    85
  val inline_nut : nut -> bool
blanchet@33192
    86
  val type_of : nut -> typ
blanchet@33192
    87
  val rep_of : nut -> rep
blanchet@33192
    88
  val nickname_of : nut -> string
blanchet@33192
    89
  val is_skolem_name : nut -> bool
blanchet@33192
    90
  val is_eval_name : nut -> bool
blanchet@33192
    91
  val is_Cst : cst -> nut -> bool
blanchet@33192
    92
  val fold_nut : (nut -> 'a -> 'a) -> nut -> 'a -> 'a
blanchet@33192
    93
  val map_nut : (nut -> nut) -> nut -> nut
blanchet@33192
    94
  val untuple : (nut -> 'a) -> nut -> 'a list
blanchet@33192
    95
  val add_free_and_const_names :
blanchet@33192
    96
    nut -> nut list * nut list -> nut list * nut list
blanchet@33192
    97
  val name_ord : (nut * nut) -> order
blanchet@33192
    98
  val the_name : 'a NameTable.table -> nut -> 'a
blanchet@33192
    99
  val the_rel : nut NameTable.table -> nut -> Kodkod.n_ary_index
blanchet@35070
   100
  val nut_from_term : hol_context -> op2 -> term -> nut
blanchet@37262
   101
  val is_fully_representable_set : nut -> bool
blanchet@33192
   102
  val choose_reps_for_free_vars :
blanchet@38170
   103
    scope -> styp list -> nut list -> rep NameTable.table
blanchet@38170
   104
    -> nut list * rep NameTable.table
blanchet@33192
   105
  val choose_reps_for_consts :
blanchet@33192
   106
    scope -> bool -> nut list -> rep NameTable.table
blanchet@33192
   107
    -> nut list * rep NameTable.table
blanchet@33192
   108
  val choose_reps_for_all_sels :
blanchet@33192
   109
    scope -> rep NameTable.table -> nut list * rep NameTable.table
blanchet@33192
   110
  val choose_reps_in_nut :
blanchet@33192
   111
    scope -> bool -> rep NameTable.table -> bool -> nut -> nut
blanchet@33192
   112
  val rename_free_vars :
blanchet@33192
   113
    nut list -> name_pool -> nut NameTable.table
blanchet@33192
   114
    -> nut list * name_pool * nut NameTable.table
blanchet@33192
   115
  val rename_vars_in_nut : name_pool -> nut NameTable.table -> nut -> nut
blanchet@33192
   116
end;
blanchet@33192
   117
blanchet@33232
   118
structure Nitpick_Nut : NITPICK_NUT =
blanchet@33192
   119
struct
blanchet@33192
   120
blanchet@33232
   121
open Nitpick_Util
blanchet@33232
   122
open Nitpick_HOL
blanchet@33232
   123
open Nitpick_Scope
blanchet@33232
   124
open Nitpick_Peephole
blanchet@33232
   125
open Nitpick_Rep
blanchet@33192
   126
blanchet@34126
   127
structure KK = Kodkod
blanchet@34126
   128
blanchet@33192
   129
datatype cst =
blanchet@33192
   130
  False |
blanchet@33192
   131
  True |
blanchet@33192
   132
  Iden |
blanchet@33192
   133
  Num of int |
blanchet@33192
   134
  Unknown |
blanchet@33192
   135
  Unrep |
blanchet@33192
   136
  Suc |
blanchet@33192
   137
  Add |
blanchet@33192
   138
  Subtract |
blanchet@33192
   139
  Multiply |
blanchet@33192
   140
  Divide |
blanchet@33192
   141
  Gcd |
blanchet@33192
   142
  Lcm |
blanchet@33192
   143
  Fracs |
blanchet@33192
   144
  NormFrac |
blanchet@33192
   145
  NatToInt |
blanchet@33192
   146
  IntToNat
blanchet@33192
   147
blanchet@33192
   148
datatype op1 =
blanchet@33192
   149
  Not |
blanchet@33192
   150
  Finite |
blanchet@33192
   151
  Converse |
blanchet@33192
   152
  Closure |
blanchet@33192
   153
  SingletonSet |
blanchet@34936
   154
  IsUnknown |
blanchet@35671
   155
  SafeThe |
blanchet@33192
   156
  First |
blanchet@33192
   157
  Second |
blanchet@33192
   158
  Cast
blanchet@33192
   159
blanchet@33192
   160
datatype op2 =
blanchet@33192
   161
  All |
blanchet@33192
   162
  Exist |
blanchet@33192
   163
  Or |
blanchet@33192
   164
  And |
blanchet@33192
   165
  Less |
blanchet@33192
   166
  Subset |
blanchet@33192
   167
  DefEq |
blanchet@33192
   168
  Eq |
blanchet@33192
   169
  Triad |
blanchet@33192
   170
  Composition |
blanchet@33192
   171
  Apply |
blanchet@33192
   172
  Lambda
blanchet@33192
   173
blanchet@33192
   174
datatype op3 =
blanchet@33192
   175
  Let |
blanchet@33192
   176
  If
blanchet@33192
   177
blanchet@33192
   178
datatype nut =
blanchet@33192
   179
  Cst of cst * typ * rep |
blanchet@33192
   180
  Op1 of op1 * typ * rep * nut |
blanchet@33192
   181
  Op2 of op2 * typ * rep * nut * nut |
blanchet@33192
   182
  Op3 of op3 * typ * rep * nut * nut * nut |
blanchet@33192
   183
  Tuple of typ * rep * nut list |
blanchet@33192
   184
  Construct of nut list * typ * rep * nut list |
blanchet@33192
   185
  BoundName of int * typ * rep * string |
blanchet@33192
   186
  FreeName of string * typ * rep |
blanchet@33192
   187
  ConstName of string * typ * rep |
blanchet@34126
   188
  BoundRel of KK.n_ary_index * typ * rep * string |
blanchet@34126
   189
  FreeRel of KK.n_ary_index * typ * rep * string |
blanchet@33192
   190
  RelReg of int * typ * rep |
blanchet@33192
   191
  FormulaReg of int * typ * rep
blanchet@33192
   192
blanchet@33192
   193
exception NUT of string * nut list
blanchet@33192
   194
blanchet@38190
   195
fun string_for_cst False = "False"
blanchet@33192
   196
  | string_for_cst True = "True"
blanchet@33192
   197
  | string_for_cst Iden = "Iden"
blanchet@33192
   198
  | string_for_cst (Num j) = "Num " ^ signed_string_of_int j
blanchet@33192
   199
  | string_for_cst Unknown = "Unknown"
blanchet@33192
   200
  | string_for_cst Unrep = "Unrep"
blanchet@33192
   201
  | string_for_cst Suc = "Suc"
blanchet@33192
   202
  | string_for_cst Add = "Add"
blanchet@33192
   203
  | string_for_cst Subtract = "Subtract"
blanchet@33192
   204
  | string_for_cst Multiply = "Multiply"
blanchet@33192
   205
  | string_for_cst Divide = "Divide"
blanchet@33192
   206
  | string_for_cst Gcd = "Gcd"
blanchet@33192
   207
  | string_for_cst Lcm = "Lcm"
blanchet@33192
   208
  | string_for_cst Fracs = "Fracs"
blanchet@33192
   209
  | string_for_cst NormFrac = "NormFrac"
blanchet@33192
   210
  | string_for_cst NatToInt = "NatToInt"
blanchet@33192
   211
  | string_for_cst IntToNat = "IntToNat"
blanchet@33192
   212
blanchet@33192
   213
fun string_for_op1 Not = "Not"
blanchet@33192
   214
  | string_for_op1 Finite = "Finite"
blanchet@33192
   215
  | string_for_op1 Converse = "Converse"
blanchet@33192
   216
  | string_for_op1 Closure = "Closure"
blanchet@33192
   217
  | string_for_op1 SingletonSet = "SingletonSet"
blanchet@34936
   218
  | string_for_op1 IsUnknown = "IsUnknown"
blanchet@35671
   219
  | string_for_op1 SafeThe = "SafeThe"
blanchet@33192
   220
  | string_for_op1 First = "First"
blanchet@33192
   221
  | string_for_op1 Second = "Second"
blanchet@33192
   222
  | string_for_op1 Cast = "Cast"
blanchet@33192
   223
blanchet@33192
   224
fun string_for_op2 All = "All"
blanchet@33192
   225
  | string_for_op2 Exist = "Exist"
blanchet@33192
   226
  | string_for_op2 Or = "Or"
blanchet@33192
   227
  | string_for_op2 And = "And"
blanchet@33192
   228
  | string_for_op2 Less = "Less"
blanchet@33192
   229
  | string_for_op2 Subset = "Subset"
blanchet@33192
   230
  | string_for_op2 DefEq = "DefEq"
blanchet@33192
   231
  | string_for_op2 Eq = "Eq"
blanchet@33192
   232
  | string_for_op2 Triad = "Triad"
blanchet@33192
   233
  | string_for_op2 Composition = "Composition"
blanchet@33192
   234
  | string_for_op2 Apply = "Apply"
blanchet@33192
   235
  | string_for_op2 Lambda = "Lambda"
blanchet@33192
   236
blanchet@33192
   237
fun string_for_op3 Let = "Let"
blanchet@33192
   238
  | string_for_op3 If = "If"
blanchet@33192
   239
blanchet@33192
   240
fun basic_string_for_nut indent ctxt u =
blanchet@33192
   241
  let
blanchet@33192
   242
    val sub = basic_string_for_nut (indent + 1) ctxt
blanchet@33192
   243
  in
blanchet@33192
   244
    (if indent = 0 then "" else "\n" ^ implode (replicate (2 * indent) " ")) ^
blanchet@33192
   245
    "(" ^
blanchet@33192
   246
    (case u of
blanchet@33192
   247
       Cst (c, T, R) =>
blanchet@33192
   248
       "Cst " ^ string_for_cst c ^ " " ^ Syntax.string_of_typ ctxt T ^ " " ^
blanchet@33192
   249
       string_for_rep R
blanchet@33192
   250
     | Op1 (oper, T, R, u1) =>
blanchet@33192
   251
       "Op1 " ^ string_for_op1 oper ^ " " ^ Syntax.string_of_typ ctxt T ^ " " ^
blanchet@33192
   252
       string_for_rep R ^ " " ^ sub u1
blanchet@33192
   253
     | Op2 (oper, T, R, u1, u2) =>
blanchet@33192
   254
       "Op2 " ^ string_for_op2 oper ^ " " ^ Syntax.string_of_typ ctxt T ^ " " ^
blanchet@33192
   255
       string_for_rep R ^ " " ^ sub u1 ^ " " ^ sub u2
blanchet@33192
   256
     | Op3 (oper, T, R, u1, u2, u3) =>
blanchet@33192
   257
       "Op3 " ^ string_for_op3 oper ^ " " ^ Syntax.string_of_typ ctxt T ^ " " ^
blanchet@33192
   258
       string_for_rep R ^ " " ^ sub u1 ^ " " ^ sub u2 ^ " " ^ sub u3
blanchet@33192
   259
     | Tuple (T, R, us) =>
blanchet@33192
   260
       "Tuple " ^ Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^
blanchet@33192
   261
       implode (map sub us)
blanchet@33192
   262
     | Construct (us', T, R, us) =>
blanchet@35665
   263
       "Construct " ^ implode (map sub us') ^ " " ^
blanchet@35665
   264
       Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^ " " ^
blanchet@35665
   265
       implode (map sub us)
blanchet@33192
   266
     | BoundName (j, T, R, nick) =>
blanchet@33192
   267
       "BoundName " ^ signed_string_of_int j ^ " " ^
blanchet@33192
   268
       Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^ " " ^ nick
blanchet@33192
   269
     | FreeName (s, T, R) =>
blanchet@33192
   270
       "FreeName " ^ s ^ " " ^ Syntax.string_of_typ ctxt T ^ " " ^
blanchet@33192
   271
       string_for_rep R
blanchet@33192
   272
     | ConstName (s, T, R) =>
blanchet@33192
   273
       "ConstName " ^ s ^ " " ^ Syntax.string_of_typ ctxt T ^ " " ^
blanchet@33192
   274
       string_for_rep R
blanchet@33192
   275
     | BoundRel ((n, j), T, R, nick) =>
blanchet@33192
   276
       "BoundRel " ^ string_of_int n ^ "." ^ signed_string_of_int j ^ " " ^
blanchet@33192
   277
       Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^ " " ^ nick
blanchet@33192
   278
     | FreeRel ((n, j), T, R, nick) =>
blanchet@33192
   279
       "FreeRel " ^ string_of_int n ^ "." ^ signed_string_of_int j ^ " " ^
blanchet@33192
   280
       Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^ " " ^ nick
blanchet@33192
   281
     | RelReg (j, T, R) =>
blanchet@33192
   282
       "RelReg " ^ signed_string_of_int j ^ " " ^ Syntax.string_of_typ ctxt T ^
blanchet@33192
   283
       " " ^ string_for_rep R
blanchet@33192
   284
     | FormulaReg (j, T, R) =>
blanchet@33192
   285
       "FormulaReg " ^ signed_string_of_int j ^ " " ^
blanchet@33192
   286
       Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R) ^
blanchet@33192
   287
    ")"
blanchet@33192
   288
  end
blanchet@33192
   289
val string_for_nut = basic_string_for_nut 0
blanchet@33192
   290
blanchet@33192
   291
fun inline_nut (Op1 _) = false
blanchet@33192
   292
  | inline_nut (Op2 _) = false
blanchet@33192
   293
  | inline_nut (Op3 _) = false
blanchet@33192
   294
  | inline_nut (Tuple (_, _, us)) = forall inline_nut us
blanchet@33192
   295
  | inline_nut _ = true
blanchet@33192
   296
blanchet@33192
   297
fun type_of (Cst (_, T, _)) = T
blanchet@33192
   298
  | type_of (Op1 (_, T, _, _)) = T
blanchet@33192
   299
  | type_of (Op2 (_, T, _, _, _)) = T
blanchet@33192
   300
  | type_of (Op3 (_, T, _, _, _, _)) = T
blanchet@33192
   301
  | type_of (Tuple (T, _, _)) = T
blanchet@33192
   302
  | type_of (Construct (_, T, _, _)) = T
blanchet@33192
   303
  | type_of (BoundName (_, T, _, _)) = T
blanchet@33192
   304
  | type_of (FreeName (_, T, _)) = T
blanchet@33192
   305
  | type_of (ConstName (_, T, _)) = T
blanchet@33192
   306
  | type_of (BoundRel (_, T, _, _)) = T
blanchet@33192
   307
  | type_of (FreeRel (_, T, _, _)) = T
blanchet@33192
   308
  | type_of (RelReg (_, T, _)) = T
blanchet@33192
   309
  | type_of (FormulaReg (_, T, _)) = T
blanchet@33192
   310
blanchet@33192
   311
fun rep_of (Cst (_, _, R)) = R
blanchet@33192
   312
  | rep_of (Op1 (_, _, R, _)) = R
blanchet@33192
   313
  | rep_of (Op2 (_, _, R, _, _)) = R
blanchet@33192
   314
  | rep_of (Op3 (_, _, R, _, _, _)) = R
blanchet@33192
   315
  | rep_of (Tuple (_, R, _)) = R
blanchet@33192
   316
  | rep_of (Construct (_, _, R, _)) = R
blanchet@33192
   317
  | rep_of (BoundName (_, _, R, _)) = R
blanchet@33192
   318
  | rep_of (FreeName (_, _, R)) = R
blanchet@33192
   319
  | rep_of (ConstName (_, _, R)) = R
blanchet@33192
   320
  | rep_of (BoundRel (_, _, R, _)) = R
blanchet@33192
   321
  | rep_of (FreeRel (_, _, R, _)) = R
blanchet@33192
   322
  | rep_of (RelReg (_, _, R)) = R
blanchet@33192
   323
  | rep_of (FormulaReg (_, _, R)) = R
blanchet@33192
   324
blanchet@33192
   325
fun nickname_of (BoundName (_, _, _, nick)) = nick
blanchet@33192
   326
  | nickname_of (FreeName (s, _, _)) = s
blanchet@33192
   327
  | nickname_of (ConstName (s, _, _)) = s
blanchet@33192
   328
  | nickname_of (BoundRel (_, _, _, nick)) = nick
blanchet@33192
   329
  | nickname_of (FreeRel (_, _, _, nick)) = nick
blanchet@33232
   330
  | nickname_of u = raise NUT ("Nitpick_Nut.nickname_of", [u])
blanchet@33192
   331
blanchet@33192
   332
fun is_skolem_name u =
blanchet@33192
   333
  space_explode name_sep (nickname_of u)
blanchet@33192
   334
  |> exists (String.isPrefix skolem_prefix)
blanchet@33232
   335
  handle NUT ("Nitpick_Nut.nickname_of", _) => false
blanchet@33192
   336
fun is_eval_name u =
blanchet@33192
   337
  String.isPrefix eval_prefix (nickname_of u)
blanchet@33232
   338
  handle NUT ("Nitpick_Nut.nickname_of", _) => false
blanchet@33192
   339
fun is_Cst cst (Cst (cst', _, _)) = (cst = cst')
blanchet@33192
   340
  | is_Cst _ _ = false
blanchet@33192
   341
blanchet@33192
   342
fun fold_nut f u =
blanchet@33192
   343
  case u of
blanchet@33192
   344
    Op1 (_, _, _, u1) => fold_nut f u1
blanchet@33192
   345
  | Op2 (_, _, _, u1, u2) => fold_nut f u1 #> fold_nut f u2
blanchet@33192
   346
  | Op3 (_, _, _, u1, u2, u3) => fold_nut f u1 #> fold_nut f u2 #> fold_nut f u3
blanchet@33192
   347
  | Tuple (_, _, us) => fold (fold_nut f) us
blanchet@33192
   348
  | Construct (us', _, _, us) => fold (fold_nut f) us #> fold (fold_nut f) us'
blanchet@33192
   349
  | _ => f u
blanchet@33192
   350
fun map_nut f u =
blanchet@33192
   351
  case u of
blanchet@33192
   352
    Op1 (oper, T, R, u1) => Op1 (oper, T, R, map_nut f u1)
blanchet@33192
   353
  | Op2 (oper, T, R, u1, u2) => Op2 (oper, T, R, map_nut f u1, map_nut f u2)
blanchet@33192
   354
  | Op3 (oper, T, R, u1, u2, u3) =>
blanchet@33192
   355
    Op3 (oper, T, R, map_nut f u1, map_nut f u2, map_nut f u3)
blanchet@33192
   356
  | Tuple (T, R, us) => Tuple (T, R, map (map_nut f) us)
blanchet@33192
   357
  | Construct (us', T, R, us) =>
blanchet@33192
   358
    Construct (map (map_nut f) us', T, R, map (map_nut f) us)
blanchet@33192
   359
  | _ => f u
blanchet@33192
   360
blanchet@33192
   361
fun name_ord (BoundName (j1, _, _, _), BoundName (j2, _, _, _)) =
blanchet@33192
   362
    int_ord (j1, j2)
blanchet@33192
   363
  | name_ord (BoundName _, _) = LESS
blanchet@33192
   364
  | name_ord (_, BoundName _) = GREATER
blanchet@33192
   365
  | name_ord (FreeName (s1, T1, _), FreeName (s2, T2, _)) =
blanchet@33192
   366
    (case fast_string_ord (s1, s2) of
wenzelm@35408
   367
       EQUAL => Term_Ord.typ_ord (T1, T2)
blanchet@33192
   368
     | ord => ord)
blanchet@33192
   369
  | name_ord (FreeName _, _) = LESS
blanchet@33192
   370
  | name_ord (_, FreeName _) = GREATER
blanchet@33192
   371
  | name_ord (ConstName (s1, T1, _), ConstName (s2, T2, _)) =
blanchet@33192
   372
    (case fast_string_ord (s1, s2) of
wenzelm@35408
   373
       EQUAL => Term_Ord.typ_ord (T1, T2)
blanchet@33192
   374
     | ord => ord)
blanchet@33232
   375
  | name_ord (u1, u2) = raise NUT ("Nitpick_Nut.name_ord", [u1, u2])
blanchet@33192
   376
blanchet@36913
   377
fun num_occurrences_in_nut needle_u stack_u =
blanchet@33192
   378
  fold_nut (fn u => if u = needle_u then Integer.add 1 else I) stack_u 0
blanchet@36913
   379
val is_subnut_of = not_equal 0 oo num_occurrences_in_nut
blanchet@33192
   380
blanchet@33192
   381
fun substitute_in_nut needle_u needle_u' =
blanchet@33192
   382
  map_nut (fn u => if u = needle_u then needle_u' else u)
blanchet@33192
   383
blanchet@33192
   384
val add_free_and_const_names =
blanchet@33192
   385
  fold_nut (fn u => case u of
blanchet@33192
   386
                      FreeName _ => apfst (insert (op =) u)
blanchet@33192
   387
                    | ConstName _ => apsnd (insert (op =) u)
blanchet@33192
   388
                    | _ => I)
blanchet@33192
   389
blanchet@33192
   390
fun modify_name_rep (BoundName (j, T, _, nick)) R = BoundName (j, T, R, nick)
blanchet@33192
   391
  | modify_name_rep (FreeName (s, T, _)) R = FreeName (s, T, R)
blanchet@33192
   392
  | modify_name_rep (ConstName (s, T, _)) R = ConstName (s, T, R)
blanchet@33232
   393
  | modify_name_rep u _ = raise NUT ("Nitpick_Nut.modify_name_rep", [u])
blanchet@33192
   394
blanchet@33192
   395
structure NameTable = Table(type key = nut val ord = name_ord)
blanchet@33192
   396
blanchet@33192
   397
fun the_name table name =
blanchet@33192
   398
  case NameTable.lookup table name of
blanchet@33192
   399
    SOME u => u
blanchet@33232
   400
  | NONE => raise NUT ("Nitpick_Nut.the_name", [name])
blanchet@33192
   401
fun the_rel table name =
blanchet@33192
   402
  case the_name table name of
blanchet@33192
   403
    FreeRel (x, _, _, _) => x
blanchet@33232
   404
  | u => raise NUT ("Nitpick_Nut.the_rel", [u])
blanchet@33192
   405
blanchet@33192
   406
fun mk_fst (_, Const (@{const_name Pair}, T) $ t1 $ _) = (domain_type T, t1)
blanchet@33192
   407
  | mk_fst (T, t) =
blanchet@33192
   408
    let val res_T = fst (HOLogic.dest_prodT T) in
blanchet@33192
   409
      (res_T, Const (@{const_name fst}, T --> res_T) $ t)
blanchet@33192
   410
    end
blanchet@33192
   411
fun mk_snd (_, Const (@{const_name Pair}, T) $ _ $ t2) =
blanchet@33192
   412
    (domain_type (range_type T), t2)
blanchet@33192
   413
  | mk_snd (T, t) =
blanchet@33192
   414
    let val res_T = snd (HOLogic.dest_prodT T) in
blanchet@33192
   415
      (res_T, Const (@{const_name snd}, T --> res_T) $ t)
blanchet@33192
   416
    end
blanchet@38190
   417
fun factorize (z as (Type (@{type_name prod}, _), _)) =
blanchet@35665
   418
    maps factorize [mk_fst z, mk_snd z]
blanchet@33192
   419
  | factorize z = [z]
blanchet@33192
   420
blanchet@39359
   421
fun nut_from_term (hol_ctxt as {thy, ctxt, stds, ...}) eq =
blanchet@33192
   422
  let
blanchet@33192
   423
    fun aux eq ss Ts t =
blanchet@33192
   424
      let
blanchet@33192
   425
        val sub = aux Eq ss Ts
blanchet@33192
   426
        val sub' = aux eq ss Ts
blanchet@33192
   427
        fun sub_abs s T = aux eq (s :: ss) (T :: Ts)
blanchet@33192
   428
        fun sub_equals T t1 t2 =
blanchet@33192
   429
          let
blanchet@33192
   430
            val (binder_Ts, body_T) = strip_type (domain_type T)
blanchet@33192
   431
            val n = length binder_Ts
blanchet@33192
   432
          in
blanchet@33192
   433
            if eq = Eq andalso n > 0 then
blanchet@33192
   434
              let
blanchet@33192
   435
                val t1 = incr_boundvars n t1
blanchet@33192
   436
                val t2 = incr_boundvars n t2
blanchet@33192
   437
                val xs = map Bound (n - 1 downto 0)
haftmann@38864
   438
                val equation = Const (@{const_name HOL.eq},
blanchet@33192
   439
                                      body_T --> body_T --> bool_T)
blanchet@33192
   440
                                   $ betapplys (t1, xs) $ betapplys (t2, xs)
blanchet@33192
   441
                val t =
blanchet@33192
   442
                  fold_rev (fn T => fn (t, j) =>
blanchet@33192
   443
                               (Const (@{const_name All}, T --> bool_T)
blanchet@33192
   444
                                $ Abs ("x" ^ nat_subscript j, T, t), j - 1))
blanchet@33192
   445
                           binder_Ts (equation, n) |> fst
blanchet@33192
   446
              in sub' t end
blanchet@33192
   447
            else
blanchet@33192
   448
              Op2 (eq, bool_T, Any, aux Eq ss Ts t1, aux Eq ss Ts t2)
blanchet@33192
   449
          end
blanchet@33192
   450
        fun do_quantifier quant s T t1 =
blanchet@33192
   451
          let
blanchet@33192
   452
            val bound_u = BoundName (length Ts, T, Any, s)
blanchet@33192
   453
            val body_u = sub_abs s T t1
blanchet@36913
   454
          in Op2 (quant, bool_T, Any, bound_u, body_u) end
blanchet@33192
   455
        fun do_apply t0 ts =
blanchet@33192
   456
          let
blanchet@33192
   457
            val (ts', t2) = split_last ts
blanchet@33192
   458
            val t1 = list_comb (t0, ts')
blanchet@33192
   459
            val T1 = fastype_of1 (Ts, t1)
blanchet@46083
   460
          in Op2 (Apply, pseudo_range_type T1, Any, sub t1, sub t2) end
blanchet@35671
   461
        fun do_construct (x as (_, T)) ts =
blanchet@35280
   462
          case num_binder_types T - length ts of
blanchet@35280
   463
            0 => Construct (map ((fn (s', T') => ConstName (s', T', Any))
blanchet@35280
   464
                                  o nth_sel_for_constr x)
blanchet@35280
   465
                                (~1 upto num_sels_for_constr_type T - 1),
blanchet@35280
   466
                            body_type T, Any,
blanchet@35280
   467
                            ts |> map (`(curry fastype_of1 Ts))
blanchet@35280
   468
                               |> maps factorize |> map (sub o snd))
blanchet@35280
   469
          | k => sub (eta_expand Ts t k)
blanchet@33192
   470
      in
blanchet@33192
   471
        case strip_comb t of
blanchet@33192
   472
          (Const (@{const_name all}, _), [Abs (s, T, t1)]) =>
blanchet@33192
   473
          do_quantifier All s T t1
blanchet@35280
   474
        | (t0 as Const (@{const_name all}, _), [t1]) =>
blanchet@33192
   475
          sub' (t0 $ eta_expand Ts t1 1)
blanchet@33192
   476
        | (Const (@{const_name "=="}, T), [t1, t2]) => sub_equals T t1 t2
blanchet@33192
   477
        | (Const (@{const_name "==>"}, _), [t1, t2]) =>
blanchet@33192
   478
          Op2 (Or, prop_T, Any, Op1 (Not, prop_T, Any, sub t1), sub' t2)
blanchet@33192
   479
        | (Const (@{const_name Pure.conjunction}, _), [t1, t2]) =>
blanchet@33192
   480
          Op2 (And, prop_T, Any, sub' t1, sub' t2)
blanchet@33192
   481
        | (Const (@{const_name Trueprop}, _), [t1]) => sub' t1
blanchet@33192
   482
        | (Const (@{const_name Not}, _), [t1]) =>
blanchet@33192
   483
          (case sub t1 of
blanchet@33192
   484
             Op1 (Not, _, _, u11) => u11
blanchet@33192
   485
           | u1 => Op1 (Not, bool_T, Any, u1))
blanchet@33192
   486
        | (Const (@{const_name False}, T), []) => Cst (False, T, Any)
blanchet@33192
   487
        | (Const (@{const_name True}, T), []) => Cst (True, T, Any)
blanchet@33192
   488
        | (Const (@{const_name All}, _), [Abs (s, T, t1)]) =>
blanchet@33192
   489
          do_quantifier All s T t1
blanchet@35280
   490
        | (t0 as Const (@{const_name All}, _), [t1]) =>
blanchet@33192
   491
          sub' (t0 $ eta_expand Ts t1 1)
blanchet@33192
   492
        | (Const (@{const_name Ex}, _), [Abs (s, T, t1)]) =>
blanchet@33192
   493
          do_quantifier Exist s T t1
blanchet@35280
   494
        | (t0 as Const (@{const_name Ex}, _), [t1]) =>
blanchet@33192
   495
          sub' (t0 $ eta_expand Ts t1 1)
haftmann@38864
   496
        | (Const (@{const_name HOL.eq}, T), [t1]) =>
blanchet@37476
   497
          Op1 (SingletonSet, range_type T, Any, sub t1)
haftmann@38864
   498
        | (Const (@{const_name HOL.eq}, T), [t1, t2]) => sub_equals T t1 t2
haftmann@38795
   499
        | (Const (@{const_name HOL.conj}, _), [t1, t2]) =>
blanchet@33192
   500
          Op2 (And, bool_T, Any, sub' t1, sub' t2)
haftmann@38795
   501
        | (Const (@{const_name HOL.disj}, _), [t1, t2]) =>
blanchet@33192
   502
          Op2 (Or, bool_T, Any, sub t1, sub t2)
haftmann@38786
   503
        | (Const (@{const_name HOL.implies}, _), [t1, t2]) =>
blanchet@33192
   504
          Op2 (Or, bool_T, Any, Op1 (Not, bool_T, Any, sub t1), sub' t2)
blanchet@33192
   505
        | (Const (@{const_name If}, T), [t1, t2, t3]) =>
blanchet@33192
   506
          Op3 (If, nth_range_type 3 T, Any, sub t1, sub t2, sub t3)
blanchet@33192
   507
        | (Const (@{const_name Let}, T), [t1, Abs (s, T', t2)]) =>
blanchet@33192
   508
          Op3 (Let, nth_range_type 2 T, Any, BoundName (length Ts, T', Any, s),
blanchet@33192
   509
               sub t1, sub_abs s T' t2)
blanchet@35280
   510
        | (t0 as Const (@{const_name Let}, _), [t1, t2]) =>
blanchet@33192
   511
          sub (t0 $ t1 $ eta_expand Ts t2 1)
blanchet@33192
   512
        | (Const (@{const_name Pair}, T), [t1, t2]) =>
blanchet@33192
   513
          Tuple (nth_range_type 2 T, Any, map sub [t1, t2])
blanchet@33192
   514
        | (Const (@{const_name fst}, T), [t1]) =>
blanchet@33192
   515
          Op1 (First, range_type T, Any, sub t1)
blanchet@33192
   516
        | (Const (@{const_name snd}, T), [t1]) =>
blanchet@33192
   517
          Op1 (Second, range_type T, Any, sub t1)
blanchet@46083
   518
        | (Const (@{const_name Set.member}, _), [t1, t2]) => do_apply t2 [t1]
blanchet@46083
   519
        | (Const (@{const_name Collect}, _), [t1]) => sub t1
blanchet@33192
   520
        | (Const (@{const_name Id}, T), []) => Cst (Iden, T, Any)
blanchet@33192
   521
        | (Const (@{const_name converse}, T), [t1]) =>
blanchet@33192
   522
          Op1 (Converse, range_type T, Any, sub t1)
blanchet@33192
   523
        | (Const (@{const_name trancl}, T), [t1]) =>
blanchet@33192
   524
          Op1 (Closure, range_type T, Any, sub t1)
griff@47433
   525
        | (Const (@{const_name relcomp}, T), [t1, t2]) =>
blanchet@33192
   526
          Op2 (Composition, nth_range_type 2 T, Any, sub t1, sub t2)
blanchet@35280
   527
        | (Const (x as (s as @{const_name Suc}, T)), []) =>
blanchet@39359
   528
          if is_built_in_const thy stds x then Cst (Suc, T, Any)
blanchet@37256
   529
          else if is_constr ctxt stds x then do_construct x []
blanchet@35280
   530
          else ConstName (s, T, Any)
blanchet@33192
   531
        | (Const (@{const_name finite}, T), [t1]) =>
blanchet@35070
   532
          (if is_finite_type hol_ctxt (domain_type T) then
blanchet@33877
   533
             Cst (True, bool_T, Any)
blanchet@33877
   534
           else case t1 of
blanchet@33877
   535
             Const (@{const_name top}, _) => Cst (False, bool_T, Any)
blanchet@33877
   536
           | _ => Op1 (Finite, bool_T, Any, sub t1))
blanchet@33192
   537
        | (Const (@{const_name nat}, T), []) => Cst (IntToNat, T, Any)
blanchet@35220
   538
        | (Const (x as (s as @{const_name zero_class.zero}, T)), []) =>
blanchet@39359
   539
          if is_built_in_const thy stds x then Cst (Num 0, T, Any)
blanchet@37256
   540
          else if is_constr ctxt stds x then do_construct x []
blanchet@35280
   541
          else ConstName (s, T, Any)
blanchet@35220
   542
        | (Const (x as (s as @{const_name one_class.one}, T)), []) =>
blanchet@39359
   543
          if is_built_in_const thy stds x then Cst (Num 1, T, Any)
blanchet@35220
   544
          else ConstName (s, T, Any)
blanchet@35220
   545
        | (Const (x as (s as @{const_name plus_class.plus}, T)), []) =>
blanchet@39359
   546
          if is_built_in_const thy stds x then Cst (Add, T, Any)
blanchet@35220
   547
          else ConstName (s, T, Any)
blanchet@35220
   548
        | (Const (x as (s as @{const_name minus_class.minus}, T)), []) =>
blanchet@39359
   549
          if is_built_in_const thy stds x then Cst (Subtract, T, Any)
blanchet@35220
   550
          else ConstName (s, T, Any)
blanchet@35220
   551
        | (Const (x as (s as @{const_name times_class.times}, T)), []) =>
blanchet@39359
   552
          if is_built_in_const thy stds x then Cst (Multiply, T, Any)
blanchet@35220
   553
          else ConstName (s, T, Any)
blanchet@35220
   554
        | (Const (x as (s as @{const_name div_class.div}, T)), []) =>
blanchet@39359
   555
          if is_built_in_const thy stds x then Cst (Divide, T, Any)
blanchet@35220
   556
          else ConstName (s, T, Any)
blanchet@35280
   557
        | (t0 as Const (x as (@{const_name ord_class.less}, _)),
blanchet@35220
   558
           ts as [t1, t2]) =>
blanchet@39359
   559
          if is_built_in_const thy stds x then
blanchet@35220
   560
            Op2 (Less, bool_T, Any, sub t1, sub t2)
blanchet@35220
   561
          else
blanchet@35220
   562
            do_apply t0 ts
blanchet@46083
   563
        | (t0 as Const (x as (@{const_name ord_class.less_eq}, T)),
blanchet@35220
   564
           ts as [t1, t2]) =>
blanchet@46085
   565
          if is_set_like_type (domain_type T) then
blanchet@46085
   566
            Op2 (Subset, bool_T, Any, sub t1, sub t2)
blanchet@46085
   567
          else if is_built_in_const thy stds x then
blanchet@46083
   568
            (* FIXME: find out if this case is necessary *)
blanchet@35220
   569
            Op1 (Not, bool_T, Any, Op2 (Less, bool_T, Any, sub t2, sub t1))
blanchet@35220
   570
          else
blanchet@35220
   571
            do_apply t0 ts
blanchet@33192
   572
        | (Const (@{const_name nat_gcd}, T), []) => Cst (Gcd, T, Any)
blanchet@33192
   573
        | (Const (@{const_name nat_lcm}, T), []) => Cst (Lcm, T, Any)
blanchet@35220
   574
        | (Const (x as (s as @{const_name uminus_class.uminus}, T)), []) =>
blanchet@39359
   575
          if is_built_in_const thy stds x then
blanchet@35220
   576
            let val num_T = domain_type T in
blanchet@35220
   577
              Op2 (Apply, num_T --> num_T, Any,
blanchet@35220
   578
                   Cst (Subtract, num_T --> num_T --> num_T, Any),
blanchet@35220
   579
                   Cst (Num 0, num_T, Any))
blanchet@35220
   580
            end
blanchet@35220
   581
          else
blanchet@35220
   582
            ConstName (s, T, Any)
blanchet@34936
   583
        | (Const (@{const_name unknown}, T), []) => Cst (Unknown, T, Any)
blanchet@35280
   584
        | (Const (@{const_name is_unknown}, _), [t1]) =>
blanchet@34936
   585
          Op1 (IsUnknown, bool_T, Any, sub t1)
blanchet@35671
   586
        | (Const (@{const_name safe_The},
blanchet@35671
   587
                  Type (@{type_name fun}, [_, T2])), [t1]) =>
blanchet@35671
   588
          Op1 (SafeThe, T2, Any, sub t1)
blanchet@33192
   589
        | (Const (@{const_name Frac}, T), []) => Cst (Fracs, T, Any)
blanchet@33192
   590
        | (Const (@{const_name norm_frac}, T), []) => Cst (NormFrac, T, Any)
blanchet@33192
   591
        | (Const (@{const_name of_nat}, T as @{typ "nat => int"}), []) =>
blanchet@33192
   592
          Cst (NatToInt, T, Any)
blanchet@34124
   593
        | (Const (@{const_name of_nat},
blanchet@34124
   594
                  T as @{typ "unsigned_bit word => signed_bit word"}), []) =>
blanchet@34124
   595
          Cst (NatToInt, T, Any)
blanchet@33192
   596
        | (t0 as Const (x as (s, T)), ts) =>
blanchet@37256
   597
          if is_constr ctxt stds x then
blanchet@35671
   598
            do_construct x ts
blanchet@33192
   599
          else if String.isPrefix numeral_prefix s then
blanchet@33192
   600
            Cst (Num (the (Int.fromString (unprefix numeral_prefix s))), T, Any)
blanchet@33192
   601
          else
blanchet@39359
   602
            (case arity_of_built_in_const thy stds x of
blanchet@33192
   603
               SOME n =>
blanchet@33192
   604
               (case n - length ts of
blanchet@33232
   605
                  0 => raise TERM ("Nitpick_Nut.nut_from_term.aux", [t])
blanchet@33192
   606
                | k => if k > 0 then sub (eta_expand Ts t k)
blanchet@33192
   607
                       else do_apply t0 ts)
blanchet@33192
   608
             | NONE => if null ts then ConstName (s, T, Any)
blanchet@33192
   609
                       else do_apply t0 ts)
blanchet@33192
   610
        | (Free (s, T), []) => FreeName (s, T, Any)
blanchet@33877
   611
        | (Var _, []) => raise TERM ("Nitpick_Nut.nut_from_term.aux", [t])
blanchet@33192
   612
        | (Bound j, []) =>
blanchet@33192
   613
          BoundName (length Ts - j - 1, nth Ts j, Any, nth ss j)
blanchet@33192
   614
        | (Abs (s, T, t1), []) =>
blanchet@33192
   615
          Op2 (Lambda, T --> fastype_of1 (T :: Ts, t1), Any,
blanchet@33192
   616
               BoundName (length Ts, T, Any, s), sub_abs s T t1)
blanchet@33192
   617
        | (t0, ts) => do_apply t0 ts
blanchet@33192
   618
      end
blanchet@33192
   619
  in aux eq [] [] end
blanchet@33192
   620
blanchet@37262
   621
fun is_fully_representable_set u =
blanchet@37262
   622
  not (is_opt_rep (rep_of u)) andalso
blanchet@37262
   623
  case u of
blanchet@37262
   624
    FreeName _ => true
blanchet@37262
   625
  | Op1 (SingletonSet, _, _, _) => true
blanchet@37262
   626
  | Op1 (Converse, _, _, u1) => is_fully_representable_set u1
blanchet@39343
   627
  | Op2 (Lambda, _, _, _, Cst (False, _, _)) => true
blanchet@39343
   628
  | Op2 (oper, _, _, u1, _) =>
blanchet@37476
   629
    if oper = Apply then
blanchet@37262
   630
      case u1 of
blanchet@37266
   631
        ConstName (s, _, _) =>
blanchet@37266
   632
        is_sel_like_and_no_discr s orelse s = @{const_name set}
blanchet@37262
   633
      | _ => false
blanchet@37262
   634
    else
blanchet@37262
   635
      false
blanchet@37262
   636
  | _ => false
blanchet@37262
   637
blanchet@33192
   638
fun rep_for_abs_fun scope T =
blanchet@33192
   639
  let val (R1, R2) = best_non_opt_symmetric_reps_for_fun_type scope T in
blanchet@33192
   640
    Func (R1, (card_of_rep R1 <> card_of_rep R2 ? Opt) R2)
blanchet@33192
   641
  end
blanchet@33192
   642
blanchet@38170
   643
fun choose_rep_for_free_var scope pseudo_frees v (vs, table) =
blanchet@33192
   644
  let
blanchet@38170
   645
    val R = (if exists (curry (op =) (nickname_of v) o fst) pseudo_frees then
blanchet@38170
   646
               best_opt_set_rep_for_type
blanchet@38170
   647
             else
blanchet@38170
   648
               best_non_opt_set_rep_for_type) scope (type_of v)
blanchet@33192
   649
    val v = modify_name_rep v R
blanchet@33192
   650
  in (v :: vs, NameTable.update (v, R) table) end
blanchet@41856
   651
fun choose_rep_for_const (scope as {hol_ctxt = {ctxt, ...}, ...}) total_consts v
blanchet@35280
   652
                         (vs, table) =
blanchet@33192
   653
  let
blanchet@33192
   654
    val x as (s, T) = (nickname_of v, type_of v)
blanchet@37256
   655
    val R = (if is_abs_fun ctxt x then
blanchet@33192
   656
               rep_for_abs_fun
blanchet@37256
   657
             else if is_rep_fun ctxt x then
blanchet@33192
   658
               Func oo best_non_opt_symmetric_reps_for_fun_type
blanchet@41856
   659
             else if total_consts orelse is_skolem_name v orelse
blanchet@39360
   660
                     member (op =) [@{const_name bisim},
blanchet@39360
   661
                                    @{const_name bisim_iterator_max}]
blanchet@39360
   662
                            (original_name s) then
blanchet@33192
   663
               best_non_opt_set_rep_for_type
blanchet@34121
   664
             else if member (op =) [@{const_name set}, @{const_name distinct},
blanchet@34121
   665
                                    @{const_name ord_class.less},
blanchet@34121
   666
                                    @{const_name ord_class.less_eq}]
blanchet@39360
   667
                            (original_name s) then
blanchet@33192
   668
               best_set_rep_for_type
blanchet@33192
   669
             else
blanchet@33192
   670
               best_opt_set_rep_for_type) scope T
blanchet@33192
   671
    val v = modify_name_rep v R
blanchet@33192
   672
  in (v :: vs, NameTable.update (v, R) table) end
blanchet@33192
   673
blanchet@38170
   674
fun choose_reps_for_free_vars scope pseudo_frees vs table =
blanchet@38170
   675
  fold (choose_rep_for_free_var scope pseudo_frees) vs ([], table)
blanchet@41856
   676
fun choose_reps_for_consts scope total_consts vs table =
blanchet@41856
   677
  fold (choose_rep_for_const scope total_consts) vs ([], table)
blanchet@33192
   678
blanchet@35190
   679
fun choose_rep_for_nth_sel_for_constr (scope as {hol_ctxt, binarize, ...})
blanchet@35190
   680
                                      (x as (_, T)) n (vs, table) =
blanchet@33192
   681
  let
blanchet@35190
   682
    val (s', T') = binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize x n
blanchet@34936
   683
    val R' = if n = ~1 orelse is_word_type (body_type T) orelse
blanchet@34936
   684
                (is_fun_type (range_type T') andalso
blanchet@46115
   685
                 is_boolean_type (body_type T')) orelse
blanchet@46115
   686
                (is_set_type (body_type T')) then
blanchet@34124
   687
               best_non_opt_set_rep_for_type scope T'
blanchet@34124
   688
             else
blanchet@34124
   689
               best_opt_set_rep_for_type scope T' |> unopt_rep
blanchet@33192
   690
    val v = ConstName (s', T', R')
blanchet@33192
   691
  in (v :: vs, NameTable.update (v, R') table) end
blanchet@33192
   692
fun choose_rep_for_sels_for_constr scope (x as (_, T)) =
blanchet@33192
   693
  fold_rev (choose_rep_for_nth_sel_for_constr scope x)
blanchet@33192
   694
           (~1 upto num_sels_for_constr_type T - 1)
blanchet@38126
   695
fun choose_rep_for_sels_of_datatype _ ({deep = false, ...} : datatype_spec) = I
blanchet@33558
   696
  | choose_rep_for_sels_of_datatype scope {constrs, ...} =
blanchet@33558
   697
    fold_rev (choose_rep_for_sels_for_constr scope o #const) constrs
blanchet@33192
   698
fun choose_reps_for_all_sels (scope as {datatypes, ...}) =
blanchet@33192
   699
  fold (choose_rep_for_sels_of_datatype scope) datatypes o pair []
blanchet@33192
   700
blanchet@42412
   701
val min_univ_card = 2
blanchet@42412
   702
blanchet@42412
   703
fun choose_rep_for_bound_var scope v =
blanchet@42412
   704
  let
blanchet@42412
   705
    val R = best_one_rep_for_type scope (type_of v)
blanchet@42412
   706
    val arity = arity_of_rep R
blanchet@42412
   707
  in
blanchet@42412
   708
    if arity > KK.max_arity min_univ_card then
blanchet@42412
   709
      raise TOO_LARGE ("Nitpick_Nut.choose_rep_for_bound_var",
blanchet@42412
   710
                       "arity " ^ string_of_int arity ^ " of bound variable \
blanchet@42412
   711
                       \too large")
blanchet@42412
   712
    else
blanchet@42412
   713
      NameTable.update (v, R)
blanchet@33192
   714
  end
blanchet@33192
   715
blanchet@33192
   716
(* A nut is said to be constructive if whenever it evaluates to unknown in our
blanchet@36913
   717
   three-valued logic, it would evaluate to an unrepresentable value ("Unrep")
blanchet@33631
   718
   according to the HOL semantics. For example, "Suc n" is constructive if "n"
blanchet@35312
   719
   is representable or "Unrep", because unknown implies "Unrep". *)
blanchet@33192
   720
fun is_constructive u =
blanchet@33192
   721
  is_Cst Unrep u orelse
blanchet@46115
   722
  (not (is_fun_or_set_type (type_of u)) andalso
blanchet@46115
   723
   not (is_opt_rep (rep_of u))) orelse
blanchet@33192
   724
  case u of
blanchet@33192
   725
    Cst (Num _, _, _) => true
blanchet@38171
   726
  | Cst (cst, T, _) => body_type T = nat_T andalso (cst = Suc orelse cst = Add)
blanchet@33192
   727
  | Op2 (Apply, _, _, u1, u2) => forall is_constructive [u1, u2]
blanchet@33192
   728
  | Op3 (If, _, _, u1, u2, u3) =>
blanchet@33192
   729
    not (is_opt_rep (rep_of u1)) andalso forall is_constructive [u2, u3]
blanchet@33192
   730
  | Tuple (_, _, us) => forall is_constructive us
blanchet@33192
   731
  | Construct (_, _, _, us) => forall is_constructive us
blanchet@33192
   732
  | _ => false
blanchet@33192
   733
blanchet@33192
   734
fun unknown_boolean T R =
blanchet@34936
   735
  Cst (case R of Formula Pos => False | Formula Neg => True | _ => Unknown,
blanchet@34936
   736
       T, R)
blanchet@33192
   737
blanchet@33192
   738
fun s_op1 oper T R u1 =
blanchet@33192
   739
  ((if oper = Not then
blanchet@33192
   740
      if is_Cst True u1 then Cst (False, T, R)
blanchet@33192
   741
      else if is_Cst False u1 then Cst (True, T, R)
blanchet@33192
   742
      else raise SAME ()
blanchet@33192
   743
    else
blanchet@33192
   744
      raise SAME ())
blanchet@33192
   745
   handle SAME () => Op1 (oper, T, R, u1))
blanchet@33192
   746
fun s_op2 oper T R u1 u2 =
blanchet@33192
   747
  ((case oper of
blanchet@36913
   748
      All => if is_subnut_of u1 u2 then Op2 (All, T, R, u1, u2) else u2
blanchet@36913
   749
    | Exist => if is_subnut_of u1 u2 then Op2 (Exist, T, R, u1, u2) else u2
blanchet@36913
   750
    | Or =>
blanchet@33192
   751
      if exists (is_Cst True) [u1, u2] then Cst (True, T, unopt_rep R)
blanchet@33192
   752
      else if is_Cst False u1 then u2
blanchet@33192
   753
      else if is_Cst False u2 then u1
blanchet@33192
   754
      else raise SAME ()
blanchet@33192
   755
    | And =>
blanchet@33192
   756
      if exists (is_Cst False) [u1, u2] then Cst (False, T, unopt_rep R)
blanchet@33192
   757
      else if is_Cst True u1 then u2
blanchet@33192
   758
      else if is_Cst True u2 then u1
blanchet@33192
   759
      else raise SAME ()
blanchet@33192
   760
    | Eq =>
blanchet@33192
   761
      (case pairself (is_Cst Unrep) (u1, u2) of
blanchet@33192
   762
         (true, true) => unknown_boolean T R
blanchet@33192
   763
       | (false, false) => raise SAME ()
blanchet@33192
   764
       | _ => if forall (is_opt_rep o rep_of) [u1, u2] then raise SAME ()
blanchet@33192
   765
              else Cst (False, T, Formula Neut))
blanchet@33192
   766
    | Triad =>
blanchet@33192
   767
      if is_Cst True u1 then u1
blanchet@33192
   768
      else if is_Cst False u2 then u2
blanchet@33192
   769
      else raise SAME ()
blanchet@33192
   770
    | Apply =>
blanchet@33192
   771
      if is_Cst Unrep u1 then
blanchet@33192
   772
        Cst (Unrep, T, R)
blanchet@33192
   773
      else if is_Cst Unrep u2 then
blanchet@36913
   774
        if is_boolean_type T then
blanchet@35312
   775
          if is_fully_representable_set u1 then Cst (False, T, Formula Neut)
blanchet@33631
   776
          else unknown_boolean T R
blanchet@36913
   777
        else if is_constructive u1 then
blanchet@36913
   778
          Cst (Unrep, T, R)
blanchet@33192
   779
        else case u1 of
blanchet@33192
   780
          Op2 (Apply, _, _, ConstName (@{const_name List.append}, _, _), _) =>
blanchet@33192
   781
          Cst (Unrep, T, R)
blanchet@33192
   782
        | _ => raise SAME ()
blanchet@33192
   783
      else
blanchet@33192
   784
        raise SAME ()
blanchet@33192
   785
    | _ => raise SAME ())
blanchet@33192
   786
   handle SAME () => Op2 (oper, T, R, u1, u2))
blanchet@33192
   787
fun s_op3 oper T R u1 u2 u3 =
blanchet@33192
   788
  ((case oper of
blanchet@33192
   789
      Let =>
blanchet@36913
   790
      if inline_nut u2 orelse num_occurrences_in_nut u1 u3 < 2 then
blanchet@33192
   791
        substitute_in_nut u1 u2 u3
blanchet@33192
   792
      else
blanchet@33192
   793
        raise SAME ()
blanchet@33192
   794
    | _ => raise SAME ())
blanchet@33192
   795
   handle SAME () => Op3 (oper, T, R, u1, u2, u3))
blanchet@33192
   796
fun s_tuple T R us =
blanchet@38190
   797
  if exists (is_Cst Unrep) us then Cst (Unrep, T, R) else Tuple (T, R, us)
blanchet@33192
   798
blanchet@33192
   799
fun untuple f (Tuple (_, _, us)) = maps (untuple f) us
blanchet@38190
   800
  | untuple f u = [f u]
blanchet@33192
   801
blanchet@35280
   802
fun choose_reps_in_nut (scope as {card_assigns, bits, datatypes, ofs, ...})
blanchet@35185
   803
                       unsound table def =
blanchet@33192
   804
  let
blanchet@33192
   805
    val bool_atom_R = Atom (2, offset_of_type ofs bool_T)
blanchet@33192
   806
    fun bool_rep polar opt =
blanchet@33192
   807
      if polar = Neut andalso opt then Opt bool_atom_R else Formula polar
blanchet@33192
   808
    fun triad u1 u2 = s_op2 Triad (type_of u1) (Opt bool_atom_R) u1 u2
blanchet@33192
   809
    fun triad_fn f = triad (f Pos) (f Neg)
blanchet@33192
   810
    fun unrepify_nut_in_nut table def polar needle_u =
blanchet@33192
   811
      let val needle_T = type_of needle_u in
blanchet@46115
   812
        substitute_in_nut needle_u
blanchet@46115
   813
            (Cst (if is_fun_or_set_type needle_T then Unknown
blanchet@46115
   814
                  else Unrep, needle_T, Any))
blanchet@33192
   815
        #> aux table def polar
blanchet@33192
   816
      end
blanchet@33192
   817
    and aux table def polar u =
blanchet@33192
   818
      let
blanchet@33192
   819
        val gsub = aux table
blanchet@33192
   820
        val sub = gsub false Neut
blanchet@33192
   821
      in
blanchet@33192
   822
        case u of
blanchet@33192
   823
          Cst (False, T, _) => Cst (False, T, Formula Neut)
blanchet@33192
   824
        | Cst (True, T, _) => Cst (True, T, Formula Neut)
blanchet@33192
   825
        | Cst (Num j, T, _) =>
blanchet@34124
   826
          if is_word_type T then
blanchet@34126
   827
            Cst (if is_twos_complement_representable bits j then Num j
blanchet@34126
   828
                 else Unrep, T, best_opt_set_rep_for_type scope T)
blanchet@34124
   829
          else
blanchet@38190
   830
             let
blanchet@38190
   831
               val (k, j0) = spec_of_type scope T
blanchet@38190
   832
               val ok = (if T = int_T then atom_for_int (k, j0) j <> ~1
blanchet@38190
   833
                         else j < k)
blanchet@38190
   834
             in
blanchet@38190
   835
               if ok then Cst (Num j, T, Atom (k, j0))
blanchet@38190
   836
               else Cst (Unrep, T, Opt (Atom (k, j0)))
blanchet@38190
   837
             end
blanchet@35665
   838
        | Cst (Suc, T as Type (@{type_name fun}, [T1, _]), _) =>
blanchet@33192
   839
          let val R = Atom (spec_of_type scope T1) in
blanchet@33192
   840
            Cst (Suc, T, Func (R, Opt R))
blanchet@33192
   841
          end
blanchet@33192
   842
        | Cst (Fracs, T, _) =>
blanchet@33192
   843
          Cst (Fracs, T, best_non_opt_set_rep_for_type scope T)
blanchet@33192
   844
        | Cst (NormFrac, T, _) =>
blanchet@33192
   845
          let val R1 = Atom (spec_of_type scope (domain_type T)) in
blanchet@33192
   846
            Cst (NormFrac, T, Func (R1, Func (R1, Opt (Struct [R1, R1]))))
blanchet@33192
   847
          end
blanchet@33192
   848
        | Cst (cst, T, _) =>
blanchet@34121
   849
          if cst = Unknown orelse cst = Unrep then
blanchet@37483
   850
            case (is_boolean_type T, polar |> unsound ? flip_polarity) of
blanchet@33192
   851
              (true, Pos) => Cst (False, T, Formula Pos)
blanchet@33192
   852
            | (true, Neg) => Cst (True, T, Formula Neg)
blanchet@33192
   853
            | _ => Cst (cst, T, best_opt_set_rep_for_type scope T)
blanchet@34124
   854
          else if member (op =) [Add, Subtract, Multiply, Divide, Gcd, Lcm]
blanchet@34124
   855
                         cst then
blanchet@33192
   856
            let
blanchet@33192
   857
              val T1 = domain_type T
blanchet@33192
   858
              val R1 = Atom (spec_of_type scope T1)
blanchet@34936
   859
              val total = T1 = nat_T andalso
blanchet@34936
   860
                          (cst = Subtract orelse cst = Divide orelse cst = Gcd)
blanchet@33192
   861
            in Cst (cst, T, Func (R1, Func (R1, (not total ? Opt) R1))) end
blanchet@34121
   862
          else if cst = NatToInt orelse cst = IntToNat then
blanchet@33192
   863
            let
blanchet@34124
   864
              val (dom_card, dom_j0) = spec_of_type scope (domain_type T)
blanchet@34124
   865
              val (ran_card, ran_j0) = spec_of_type scope (range_type T)
blanchet@34936
   866
              val total = not (is_word_type (domain_type T)) andalso
blanchet@34936
   867
                          (if cst = NatToInt then
blanchet@34936
   868
                             max_int_for_card ran_card >= dom_card + 1
blanchet@34936
   869
                           else
blanchet@34936
   870
                             max_int_for_card dom_card < ran_card)
blanchet@33192
   871
            in
blanchet@34124
   872
              Cst (cst, T, Func (Atom (dom_card, dom_j0),
blanchet@34124
   873
                                 Atom (ran_card, ran_j0) |> not total ? Opt))
blanchet@33192
   874
            end
blanchet@33192
   875
          else
blanchet@33192
   876
            Cst (cst, T, best_set_rep_for_type scope T)
blanchet@33192
   877
        | Op1 (Not, T, _, u1) =>
blanchet@33192
   878
          (case gsub def (flip_polarity polar) u1 of
blanchet@35280
   879
             Op2 (Triad, T, _, u11, u12) =>
blanchet@33192
   880
             triad (s_op1 Not T (Formula Pos) u12)
blanchet@33192
   881
                   (s_op1 Not T (Formula Neg) u11)
blanchet@33192
   882
           | u1' => s_op1 Not T (flip_rep_polarity (rep_of u1')) u1')
blanchet@34936
   883
        | Op1 (IsUnknown, T, _, u1) =>
blanchet@34936
   884
          let val u1 = sub u1 in
blanchet@34936
   885
            if is_opt_rep (rep_of u1) then Op1 (IsUnknown, T, Formula Neut, u1)
blanchet@34936
   886
            else Cst (False, T, Formula Neut)
blanchet@34936
   887
          end
blanchet@33192
   888
        | Op1 (oper, T, _, u1) =>
blanchet@33192
   889
          let
blanchet@33192
   890
            val u1 = sub u1
blanchet@33192
   891
            val R1 = rep_of u1
blanchet@33192
   892
            val R = case oper of
blanchet@33192
   893
                      Finite => bool_rep polar (is_opt_rep R1)
blanchet@33192
   894
                    | _ => (if is_opt_rep R1 then best_opt_set_rep_for_type
blanchet@33192
   895
                            else best_non_opt_set_rep_for_type) scope T
blanchet@33192
   896
          in s_op1 oper T R u1 end
blanchet@33192
   897
        | Op2 (Less, T, _, u1, u2) =>
blanchet@33192
   898
          let
blanchet@33192
   899
            val u1 = sub u1
blanchet@33192
   900
            val u2 = sub u2
blanchet@33192
   901
            val R = bool_rep polar (exists (is_opt_rep o rep_of) [u1, u2])
blanchet@33192
   902
          in s_op2 Less T R u1 u2 end
blanchet@33192
   903
        | Op2 (Subset, T, _, u1, u2) =>
blanchet@33192
   904
          let
blanchet@33192
   905
            val u1 = sub u1
blanchet@33192
   906
            val u2 = sub u2
blanchet@33192
   907
            val opt = exists (is_opt_rep o rep_of) [u1, u2]
blanchet@33192
   908
            val R = bool_rep polar opt
blanchet@33192
   909
          in
blanchet@33192
   910
            if is_opt_rep R then
blanchet@33192
   911
              triad_fn (fn polar => s_op2 Subset T (Formula polar) u1 u2)
blanchet@36912
   912
            else if not opt orelse unsound orelse polar = Neg orelse
blanchet@36912
   913
                    is_concrete_type datatypes true (type_of u1) then
blanchet@36912
   914
              s_op2 Subset T R u1 u2
blanchet@36912
   915
            else
blanchet@33192
   916
              Cst (False, T, Formula Pos)
blanchet@33192
   917
          end
blanchet@33192
   918
        | Op2 (DefEq, T, _, u1, u2) =>
blanchet@33192
   919
          s_op2 DefEq T (Formula Neut) (sub u1) (sub u2)
blanchet@33192
   920
        | Op2 (Eq, T, _, u1, u2) =>
blanchet@33192
   921
          let
blanchet@33192
   922
            val u1' = sub u1
blanchet@33192
   923
            val u2' = sub u2
blanchet@33192
   924
            fun non_opt_case () = s_op2 Eq T (Formula polar) u1' u2'
blanchet@33192
   925
            fun opt_opt_case () =
blanchet@33192
   926
              if polar = Neut then
blanchet@33192
   927
                triad_fn (fn polar => s_op2 Eq T (Formula polar) u1' u2')
blanchet@33192
   928
              else
blanchet@33192
   929
                non_opt_case ()
blanchet@33192
   930
            fun hybrid_case u =
blanchet@33192
   931
              (* hackish optimization *)
blanchet@33192
   932
              if is_constructive u then s_op2 Eq T (Formula Neut) u1' u2'
blanchet@33192
   933
              else opt_opt_case ()
blanchet@33192
   934
          in
blanchet@35185
   935
            if unsound orelse polar = Neg orelse
blanchet@35385
   936
               is_concrete_type datatypes true (type_of u1) then
blanchet@33192
   937
              case (is_opt_rep (rep_of u1'), is_opt_rep (rep_of u2')) of
blanchet@33192
   938
                (true, true) => opt_opt_case ()
blanchet@33192
   939
              | (true, false) => hybrid_case u1'
blanchet@33192
   940
              | (false, true) => hybrid_case u2'
blanchet@33192
   941
              | (false, false) => non_opt_case ()
blanchet@33192
   942
            else
blanchet@33192
   943
              Cst (False, T, Formula Pos)
blanchet@33192
   944
              |> polar = Neut ? (fn pos_u => triad pos_u (gsub def Neg u))
blanchet@33192
   945
          end
blanchet@33192
   946
        | Op2 (Apply, T, _, u1, u2) =>
blanchet@33192
   947
          let
blanchet@33192
   948
            val u1 = sub u1
blanchet@33192
   949
            val u2 = sub u2
blanchet@33192
   950
            val T1 = type_of u1
blanchet@33192
   951
            val R1 = rep_of u1
blanchet@33192
   952
            val R2 = rep_of u2
blanchet@33192
   953
            val opt =
blanchet@33192
   954
              case (u1, is_opt_rep R2) of
blanchet@33192
   955
                (ConstName (@{const_name set}, _, _), false) => false
blanchet@33192
   956
              | _ => exists is_opt_rep [R1, R2]
blanchet@33192
   957
            val ran_R =
blanchet@33192
   958
              if is_boolean_type T then
blanchet@33192
   959
                bool_rep polar opt
blanchet@33192
   960
              else
blanchet@36128
   961
                lazy_range_rep ofs T1 (fn () => card_of_type card_assigns T)
blanchet@36128
   962
                               (unopt_rep R1)
blanchet@33192
   963
                |> opt ? opt_rep ofs T
blanchet@33192
   964
          in s_op2 Apply T ran_R u1 u2 end
blanchet@33192
   965
        | Op2 (Lambda, T, _, u1, u2) =>
blanchet@33192
   966
          (case best_set_rep_for_type scope T of
blanchet@38190
   967
             R as Func (R1, _) =>
blanchet@33192
   968
             let
blanchet@33192
   969
               val table' = NameTable.update (u1, R1) table
blanchet@33192
   970
               val u1' = aux table' false Neut u1
blanchet@33192
   971
               val u2' = aux table' false Neut u2
blanchet@33192
   972
               val R =
blanchet@34936
   973
                 if is_opt_rep (rep_of u2') orelse
blanchet@46085
   974
                    (pseudo_range_type T = bool_T andalso
blanchet@34936
   975
                     not (is_Cst False (unrepify_nut_in_nut table false Neut
blanchet@36913
   976
                                                            u1 u2))) then
blanchet@33192
   977
                   opt_rep ofs T R
blanchet@33192
   978
                 else
blanchet@33192
   979
                   unopt_rep R
blanchet@33192
   980
             in s_op2 Lambda T R u1' u2' end
blanchet@36913
   981
           | _ => raise NUT ("Nitpick_Nut.choose_reps_in_nut.aux", [u]))
blanchet@33192
   982
        | Op2 (oper, T, _, u1, u2) =>
blanchet@34121
   983
          if oper = All orelse oper = Exist then
blanchet@33192
   984
            let
blanchet@33192
   985
              val table' = fold (choose_rep_for_bound_var scope) (untuple I u1)
blanchet@33192
   986
                                table
blanchet@33192
   987
              val u1' = aux table' def polar u1
blanchet@33192
   988
              val u2' = aux table' def polar u2
blanchet@33192
   989
            in
blanchet@33192
   990
              if polar = Neut andalso is_opt_rep (rep_of u2') then
blanchet@33192
   991
                triad_fn (fn polar => gsub def polar u)
blanchet@33192
   992
              else
blanchet@33192
   993
                let val quant_u = s_op2 oper T (Formula polar) u1' u2' in
blanchet@34936
   994
                  if def orelse
blanchet@35185
   995
                     (unsound andalso (polar = Pos) = (oper = All)) orelse
blanchet@35385
   996
                     is_complete_type datatypes true (type_of u1) then
blanchet@33192
   997
                    quant_u
blanchet@33192
   998
                  else
blanchet@33192
   999
                    let
blanchet@33192
  1000
                      val connective = if oper = All then And else Or
blanchet@33192
  1001
                      val unrepified_u = unrepify_nut_in_nut table def polar
blanchet@33192
  1002
                                                             u1 u2
blanchet@33192
  1003
                    in
blanchet@33192
  1004
                      s_op2 connective T
blanchet@33192
  1005
                            (min_rep (rep_of quant_u) (rep_of unrepified_u))
blanchet@33192
  1006
                            quant_u unrepified_u
blanchet@33192
  1007
                    end
blanchet@33192
  1008
                end
blanchet@33192
  1009
            end
blanchet@34121
  1010
          else if oper = Or orelse oper = And then
blanchet@33192
  1011
            let
blanchet@33192
  1012
              val u1' = gsub def polar u1
blanchet@33192
  1013
              val u2' = gsub def polar u2
blanchet@33192
  1014
            in
blanchet@33192
  1015
              (if polar = Neut then
blanchet@33192
  1016
                 case (is_opt_rep (rep_of u1'), is_opt_rep (rep_of u2')) of
blanchet@33192
  1017
                   (true, true) => triad_fn (fn polar => gsub def polar u)
blanchet@33192
  1018
                 | (true, false) =>
blanchet@33192
  1019
                   s_op2 oper T (Opt bool_atom_R)
blanchet@33192
  1020
                         (triad_fn (fn polar => gsub def polar u1)) u2'
blanchet@33192
  1021
                 | (false, true) =>
blanchet@33192
  1022
                   s_op2 oper T (Opt bool_atom_R)
blanchet@33192
  1023
                         u1' (triad_fn (fn polar => gsub def polar u2))
blanchet@33192
  1024
                 | (false, false) => raise SAME ()
blanchet@33192
  1025
               else
blanchet@33192
  1026
                 raise SAME ())
blanchet@33192
  1027
              handle SAME () => s_op2 oper T (Formula polar) u1' u2'
blanchet@33192
  1028
            end
blanchet@33192
  1029
          else
blanchet@33192
  1030
            let
blanchet@33192
  1031
              val u1 = sub u1
blanchet@33192
  1032
              val u2 = sub u2
blanchet@33192
  1033
              val R =
blanchet@33192
  1034
                best_non_opt_set_rep_for_type scope T
blanchet@33192
  1035
                |> exists (is_opt_rep o rep_of) [u1, u2] ? opt_rep ofs T
blanchet@33192
  1036
            in s_op2 oper T R u1 u2 end
blanchet@33192
  1037
        | Op3 (Let, T, _, u1, u2, u3) =>
blanchet@33192
  1038
          let
blanchet@33192
  1039
            val u2 = sub u2
blanchet@33192
  1040
            val R2 = rep_of u2
blanchet@33192
  1041
            val table' = NameTable.update (u1, R2) table
blanchet@33192
  1042
            val u1 = modify_name_rep u1 R2
blanchet@33192
  1043
            val u3 = aux table' false polar u3
blanchet@33192
  1044
          in s_op3 Let T (rep_of u3) u1 u2 u3 end
blanchet@33192
  1045
        | Op3 (If, T, _, u1, u2, u3) =>
blanchet@33192
  1046
          let
blanchet@33192
  1047
            val u1 = sub u1
blanchet@33192
  1048
            val u2 = gsub def polar u2
blanchet@33192
  1049
            val u3 = gsub def polar u3
blanchet@33192
  1050
            val min_R = min_rep (rep_of u2) (rep_of u3)
blanchet@33192
  1051
            val R = min_R |> is_opt_rep (rep_of u1) ? opt_rep ofs T
blanchet@33192
  1052
          in s_op3 If T R u1 u2 u3 end
blanchet@33192
  1053
        | Tuple (T, _, us) =>
blanchet@33192
  1054
          let
blanchet@33192
  1055
            val Rs = map (best_one_rep_for_type scope o type_of) us
blanchet@33192
  1056
            val us = map sub us
blanchet@38190
  1057
            val R' = Struct Rs
blanchet@38190
  1058
                     |> exists (is_opt_rep o rep_of) us ? opt_rep ofs T
blanchet@33192
  1059
          in s_tuple T R' us end
blanchet@33192
  1060
        | Construct (us', T, _, us) =>
blanchet@33192
  1061
          let
blanchet@33192
  1062
            val us = map sub us
blanchet@33192
  1063
            val Rs = map rep_of us
blanchet@33192
  1064
            val R = best_one_rep_for_type scope T
blanchet@33192
  1065
            val {total, ...} =
blanchet@33192
  1066
              constr_spec datatypes (original_name (nickname_of (hd us')), T)
blanchet@33192
  1067
            val opt = exists is_opt_rep Rs orelse not total
blanchet@33192
  1068
          in Construct (map sub us', T, R |> opt ? Opt, us) end
blanchet@33192
  1069
        | _ =>
blanchet@33192
  1070
          let val u = modify_name_rep u (the_name table u) in
blanchet@34936
  1071
            if polar = Neut orelse not (is_boolean_type (type_of u)) orelse
blanchet@34936
  1072
               not (is_opt_rep (rep_of u)) then
blanchet@33192
  1073
              u
blanchet@33192
  1074
            else
blanchet@33192
  1075
              s_op1 Cast (type_of u) (Formula polar) u
blanchet@33192
  1076
          end
blanchet@33192
  1077
      end
blanchet@33192
  1078
  in aux table def Pos end
blanchet@33192
  1079
blanchet@33192
  1080
fun fresh_n_ary_index n [] ys = (0, (n, 1) :: ys)
blanchet@33192
  1081
  | fresh_n_ary_index n ((m, j) :: xs) ys =
blanchet@33192
  1082
    if m = n then (j, ys @ ((m, j + 1) :: xs))
blanchet@33192
  1083
    else fresh_n_ary_index n xs ((m, j) :: ys)
blanchet@33192
  1084
fun fresh_rel n {rels, vars, formula_reg, rel_reg} =
blanchet@33192
  1085
  let val (j, rels') = fresh_n_ary_index n rels [] in
blanchet@33192
  1086
    (j, {rels = rels', vars = vars, formula_reg = formula_reg,
blanchet@33192
  1087
         rel_reg = rel_reg})
blanchet@33192
  1088
  end
blanchet@33192
  1089
fun fresh_var n {rels, vars, formula_reg, rel_reg} =
blanchet@33192
  1090
  let val (j, vars') = fresh_n_ary_index n vars [] in
blanchet@33192
  1091
    (j, {rels = rels, vars = vars', formula_reg = formula_reg,
blanchet@33192
  1092
         rel_reg = rel_reg})
blanchet@33192
  1093
  end
blanchet@33192
  1094
fun fresh_formula_reg {rels, vars, formula_reg, rel_reg} =
blanchet@33192
  1095
  (formula_reg, {rels = rels, vars = vars, formula_reg = formula_reg + 1,
blanchet@33192
  1096
                 rel_reg = rel_reg})
blanchet@33192
  1097
fun fresh_rel_reg {rels, vars, formula_reg, rel_reg} =
blanchet@33192
  1098
  (rel_reg, {rels = rels, vars = vars, formula_reg = formula_reg,
blanchet@33192
  1099
             rel_reg = rel_reg + 1})
blanchet@33192
  1100
blanchet@33192
  1101
fun rename_plain_var v (ws, pool, table) =
blanchet@33192
  1102
  let
blanchet@33192
  1103
    val is_formula = (rep_of v = Formula Neut)
blanchet@33192
  1104
    val fresh = if is_formula then fresh_formula_reg else fresh_rel_reg
blanchet@33192
  1105
    val (j, pool) = fresh pool
blanchet@33192
  1106
    val constr = if is_formula then FormulaReg else RelReg
blanchet@33192
  1107
    val w = constr (j, type_of v, rep_of v)
blanchet@33192
  1108
  in (w :: ws, pool, NameTable.update (v, w) table) end
blanchet@33192
  1109
blanchet@38190
  1110
fun shape_tuple (T as Type (@{type_name prod}, [T1, T2])) (R as Struct [R1, R2])
blanchet@35665
  1111
                us =
blanchet@33192
  1112
    let val arity1 = arity_of_rep R1 in
blanchet@33192
  1113
      Tuple (T, R, [shape_tuple T1 R1 (List.take (us, arity1)),
blanchet@33192
  1114
                    shape_tuple T2 R2 (List.drop (us, arity1))])
blanchet@33192
  1115
    end
blanchet@46086
  1116
  | shape_tuple T (R as Vect (k, R')) us =
blanchet@46086
  1117
    Tuple (T, R, map (shape_tuple (pseudo_range_type T) R')
blanchet@46086
  1118
                     (batch_list (length us div k) us))
blanchet@35280
  1119
  | shape_tuple T _ [u] =
blanchet@33232
  1120
    if type_of u = T then u else raise NUT ("Nitpick_Nut.shape_tuple", [u])
blanchet@33232
  1121
  | shape_tuple _ _ us = raise NUT ("Nitpick_Nut.shape_tuple", us)
blanchet@33192
  1122
blanchet@33192
  1123
fun rename_n_ary_var rename_free v (ws, pool, table) =
blanchet@33192
  1124
  let
blanchet@33192
  1125
    val T = type_of v
blanchet@33192
  1126
    val R = rep_of v
blanchet@33192
  1127
    val arity = arity_of_rep R
blanchet@33192
  1128
    val nick = nickname_of v
blanchet@33192
  1129
    val (constr, fresh) = if rename_free then (FreeRel, fresh_rel)
blanchet@33192
  1130
                          else (BoundRel, fresh_var)
blanchet@33192
  1131
  in
blanchet@33192
  1132
    if not rename_free andalso arity > 1 then
blanchet@33192
  1133
      let
blanchet@33192
  1134
        val atom_schema = atom_schema_of_rep R
blanchet@33192
  1135
        val type_schema = type_schema_of_rep T R
blanchet@33192
  1136
        val (js, pool) = funpow arity (fn (js, pool) =>
blanchet@33192
  1137
                                          let val (j, pool) = fresh 1 pool in
blanchet@33192
  1138
                                            (j :: js, pool)
blanchet@33192
  1139
                                          end)
blanchet@33192
  1140
                                ([], pool)
blanchet@33192
  1141
        val ws' = map3 (fn j => fn x => fn T =>
blanchet@33192
  1142
                           constr ((1, j), T, Atom x,
blanchet@33192
  1143
                                   nick ^ " [" ^ string_of_int j ^ "]"))
blanchet@33192
  1144
                       (rev js) atom_schema type_schema
blanchet@33192
  1145
      in (ws' @ ws, pool, NameTable.update (v, shape_tuple T R ws') table) end
blanchet@33192
  1146
    else
blanchet@33192
  1147
      let
blanchet@34124
  1148
        val (j, pool) =
blanchet@34124
  1149
          case v of
blanchet@34124
  1150
            ConstName _ =>
blanchet@34124
  1151
            if is_sel_like_and_no_discr nick then
blanchet@34124
  1152
              case domain_type T of
blanchet@34124
  1153
                @{typ "unsigned_bit word"} =>
blanchet@34124
  1154
                (snd unsigned_bit_word_sel_rel, pool)
blanchet@34124
  1155
              | @{typ "signed_bit word"} => (snd signed_bit_word_sel_rel, pool)
blanchet@34124
  1156
              | _ => fresh arity pool
blanchet@34124
  1157
            else
blanchet@34124
  1158
              fresh arity pool
blanchet@34124
  1159
          | _ => fresh arity pool
blanchet@33192
  1160
        val w = constr ((arity, j), T, R, nick)
blanchet@33192
  1161
      in (w :: ws, pool, NameTable.update (v, w) table) end
blanchet@33192
  1162
  end
blanchet@33192
  1163
blanchet@33192
  1164
fun rename_free_vars vs pool table =
blanchet@33192
  1165
  let
blanchet@33192
  1166
    val (vs, pool, table) = fold (rename_n_ary_var true) vs ([], pool, table)
blanchet@33192
  1167
  in (rev vs, pool, table) end
blanchet@33192
  1168
blanchet@33192
  1169
fun rename_vars_in_nut pool table u =
blanchet@33192
  1170
  case u of
blanchet@33192
  1171
    Cst _ => u
blanchet@33192
  1172
  | Op1 (oper, T, R, u1) => Op1 (oper, T, R, rename_vars_in_nut pool table u1)
blanchet@33192
  1173
  | Op2 (oper, T, R, u1, u2) =>
blanchet@34121
  1174
    if oper = All orelse oper = Exist orelse oper = Lambda then
blanchet@33192
  1175
      let
blanchet@33192
  1176
        val (_, pool, table) = fold (rename_n_ary_var false) (untuple I u1)
blanchet@33192
  1177
                                    ([], pool, table)
blanchet@33192
  1178
      in
blanchet@33192
  1179
        Op2 (oper, T, R, rename_vars_in_nut pool table u1,
blanchet@33192
  1180
             rename_vars_in_nut pool table u2)
blanchet@33192
  1181
      end
blanchet@33192
  1182
    else
blanchet@33192
  1183
      Op2 (oper, T, R, rename_vars_in_nut pool table u1,
blanchet@33192
  1184
           rename_vars_in_nut pool table u2)
blanchet@33192
  1185
  | Op3 (Let, T, R, u1, u2, u3) =>
blanchet@38190
  1186
    if inline_nut u2 then
blanchet@33192
  1187
      let
blanchet@33192
  1188
        val u2 = rename_vars_in_nut pool table u2
blanchet@33192
  1189
        val table = NameTable.update (u1, u2) table
blanchet@33192
  1190
      in rename_vars_in_nut pool table u3 end
blanchet@33192
  1191
    else
blanchet@33192
  1192
      let
blanchet@33192
  1193
        val bs = untuple I u1
blanchet@33192
  1194
        val (_, pool, table') = fold rename_plain_var bs ([], pool, table)
blanchet@33192
  1195
      in
blanchet@33192
  1196
        Op3 (Let, T, R, rename_vars_in_nut pool table' u1,
blanchet@33192
  1197
             rename_vars_in_nut pool table u2,
blanchet@33192
  1198
             rename_vars_in_nut pool table' u3)
blanchet@33192
  1199
      end
blanchet@33192
  1200
  | Op3 (oper, T, R, u1, u2, u3) =>
blanchet@33192
  1201
    Op3 (oper, T, R, rename_vars_in_nut pool table u1,
blanchet@33192
  1202
         rename_vars_in_nut pool table u2, rename_vars_in_nut pool table u3)
blanchet@33192
  1203
  | Tuple (T, R, us) => Tuple (T, R, map (rename_vars_in_nut pool table) us)
blanchet@33192
  1204
  | Construct (us', T, R, us) =>
blanchet@33192
  1205
    Construct (map (rename_vars_in_nut pool table) us', T, R,
blanchet@33192
  1206
               map (rename_vars_in_nut pool table) us)
blanchet@33192
  1207
  | _ => the_name table u
blanchet@33192
  1208
blanchet@33192
  1209
end;