src/HOL/Library/refute.ML
author wenzelm
Thu Aug 13 11:05:19 2015 +0200 (2015-08-13)
changeset 60924 610794dff23c
parent 60190 906de96ba68a
child 61770 a20048c78891
permissions -rw-r--r--
tuned signature, in accordance to sortBy in Scala;
wenzelm@50530
     1
(*  Title:      HOL/Library/refute.ML
wenzelm@29265
     2
    Author:     Tjark Weber, TU Muenchen
webertj@14350
     3
webertj@14965
     4
Finite model generation for HOL formulas, using a SAT solver.
webertj@14350
     5
*)
webertj@14350
     6
webertj@14350
     7
signature REFUTE =
webertj@14350
     8
sig
webertj@14350
     9
wenzelm@22567
    10
  exception REFUTE of string * string
webertj@14456
    11
webertj@14456
    12
(* ------------------------------------------------------------------------- *)
webertj@14807
    13
(* Model/interpretation related code (translation HOL -> propositional logic *)
webertj@14456
    14
(* ------------------------------------------------------------------------- *)
webertj@14456
    15
wenzelm@22567
    16
  type params
wenzelm@22567
    17
  type interpretation
wenzelm@22567
    18
  type model
wenzelm@22567
    19
  type arguments
webertj@14456
    20
wenzelm@22567
    21
  exception MAXVARS_EXCEEDED
webertj@14456
    22
wenzelm@39049
    23
  val add_interpreter : string -> (Proof.context -> model -> arguments -> term ->
wenzelm@22567
    24
    (interpretation * model * arguments) option) -> theory -> theory
wenzelm@39049
    25
  val add_printer : string -> (Proof.context -> model -> typ ->
wenzelm@33243
    26
    interpretation -> (int -> bool) -> term option) -> theory -> theory
webertj@14456
    27
wenzelm@39049
    28
  val interpret : Proof.context -> model -> arguments -> term ->
wenzelm@22567
    29
    (interpretation * model * arguments)
webertj@14807
    30
wenzelm@39049
    31
  val print : Proof.context -> model -> typ -> interpretation -> (int -> bool) -> term
wenzelm@39049
    32
  val print_model : Proof.context -> model -> (int -> bool) -> string
webertj@14456
    33
webertj@14456
    34
(* ------------------------------------------------------------------------- *)
webertj@14456
    35
(* Interface                                                                 *)
webertj@14456
    36
(* ------------------------------------------------------------------------- *)
webertj@14456
    37
wenzelm@22567
    38
  val set_default_param  : (string * string) -> theory -> theory
wenzelm@39049
    39
  val get_default_param  : Proof.context -> string -> string option
wenzelm@39049
    40
  val get_default_params : Proof.context -> (string * string) list
wenzelm@39049
    41
  val actual_params      : Proof.context -> (string * string) list -> params
webertj@14456
    42
blanchet@45387
    43
  val find_model :
blanchet@45387
    44
    Proof.context -> params -> term list -> term -> bool -> string
webertj@14456
    45
wenzelm@22567
    46
  (* tries to find a model for a formula: *)
blanchet@34120
    47
  val satisfy_term :
blanchet@45387
    48
    Proof.context -> (string * string) list -> term list -> term -> string
wenzelm@22567
    49
  (* tries to find a model that refutes a formula: *)
blanchet@34120
    50
  val refute_term :
blanchet@45387
    51
    Proof.context -> (string * string) list -> term list -> term -> string
blanchet@34120
    52
  val refute_goal :
blanchet@45387
    53
    Proof.context -> (string * string) list -> thm -> int -> string
webertj@14456
    54
blanchet@29802
    55
(* ------------------------------------------------------------------------- *)
blanchet@29802
    56
(* Additional functions used by Nitpick (to be factored out)                 *)
blanchet@29802
    57
(* ------------------------------------------------------------------------- *)
blanchet@29802
    58
wenzelm@33243
    59
  val get_classdef : theory -> string -> (string * term) option
wenzelm@33243
    60
  val norm_rhs : term -> term
wenzelm@33243
    61
  val get_def : theory -> string * typ -> (string * term) option
wenzelm@33243
    62
  val get_typedef : theory -> typ -> (string * term) option
wenzelm@33243
    63
  val is_IDT_constructor : theory -> string * typ -> bool
wenzelm@33243
    64
  val is_IDT_recursor : theory -> string * typ -> bool
wenzelm@33243
    65
  val is_const_of_class: theory -> string * typ -> bool
wenzelm@33243
    66
  val string_of_typ : typ -> string
wenzelm@39046
    67
end;
wenzelm@39046
    68
webertj@14456
    69
structure Refute : REFUTE =
webertj@14456
    70
struct
webertj@14456
    71
wenzelm@41471
    72
open Prop_Logic;
webertj@14456
    73
wenzelm@39046
    74
(* We use 'REFUTE' only for internal error conditions that should    *)
wenzelm@39046
    75
(* never occur in the first place (i.e. errors caused by bugs in our *)
wenzelm@39046
    76
(* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
wenzelm@39046
    77
(* 'error'.                                                          *)
wenzelm@39046
    78
exception REFUTE of string * string;  (* ("in function", "cause") *)
webertj@14350
    79
wenzelm@39046
    80
(* should be raised by an interpreter when more variables would be *)
wenzelm@39046
    81
(* required than allowed by 'maxvars'                              *)
wenzelm@39046
    82
exception MAXVARS_EXCEEDED;
wenzelm@39046
    83
webertj@14350
    84
webertj@14350
    85
(* ------------------------------------------------------------------------- *)
webertj@14350
    86
(* TREES                                                                     *)
webertj@14350
    87
(* ------------------------------------------------------------------------- *)
webertj@14350
    88
webertj@14350
    89
(* ------------------------------------------------------------------------- *)
webertj@14350
    90
(* tree: implements an arbitrarily (but finitely) branching tree as a list   *)
webertj@14350
    91
(*       of (lists of ...) elements                                          *)
webertj@14350
    92
(* ------------------------------------------------------------------------- *)
webertj@14350
    93
wenzelm@39046
    94
datatype 'a tree =
wenzelm@39046
    95
    Leaf of 'a
wenzelm@39046
    96
  | Node of ('a tree) list;
webertj@14350
    97
wenzelm@39046
    98
fun tree_map f tr =
wenzelm@39046
    99
  case tr of
wenzelm@39046
   100
    Leaf x  => Leaf (f x)
wenzelm@39046
   101
  | Node xs => Node (map (tree_map f) xs);
webertj@14350
   102
wenzelm@39046
   103
fun tree_pair (t1, t2) =
wenzelm@39046
   104
  case t1 of
wenzelm@39046
   105
    Leaf x =>
wenzelm@22567
   106
      (case t2 of
wenzelm@22567
   107
          Leaf y => Leaf (x,y)
wenzelm@22567
   108
        | Node _ => raise REFUTE ("tree_pair",
wenzelm@22567
   109
            "trees are of different height (second tree is higher)"))
wenzelm@39046
   110
  | Node xs =>
wenzelm@22567
   111
      (case t2 of
wenzelm@22567
   112
          (* '~~' will raise an exception if the number of branches in   *)
wenzelm@22567
   113
          (* both trees is different at the current node                 *)
wenzelm@22567
   114
          Node ys => Node (map tree_pair (xs ~~ ys))
wenzelm@22567
   115
        | Leaf _  => raise REFUTE ("tree_pair",
wenzelm@22567
   116
            "trees are of different height (first tree is higher)"));
webertj@14350
   117
webertj@14350
   118
(* ------------------------------------------------------------------------- *)
webertj@14807
   119
(* params: parameters that control the translation into a propositional      *)
webertj@14807
   120
(*         formula/model generation                                          *)
webertj@14807
   121
(*                                                                           *)
webertj@14807
   122
(* The following parameters are supported (and required (!), except for      *)
blanchet@30314
   123
(* "sizes" and "expect"):                                                    *)
webertj@14807
   124
(*                                                                           *)
webertj@14807
   125
(* Name          Type    Description                                         *)
webertj@14807
   126
(*                                                                           *)
webertj@14807
   127
(* "sizes"       (string * int) list                                         *)
webertj@14807
   128
(*                       Size of ground types (e.g. 'a=2), or depth of IDTs. *)
webertj@14807
   129
(* "minsize"     int     If >0, minimal size of each ground type/IDT depth.  *)
webertj@14807
   130
(* "maxsize"     int     If >0, maximal size of each ground type/IDT depth.  *)
webertj@14807
   131
(* "maxvars"     int     If >0, use at most 'maxvars' Boolean variables      *)
webertj@14807
   132
(*                       when transforming the term into a propositional     *)
webertj@14807
   133
(*                       formula.                                            *)
webertj@14807
   134
(* "maxtime"     int     If >0, terminate after at most 'maxtime' seconds.   *)
webertj@14807
   135
(* "satsolver"   string  SAT solver to be used.                              *)
blanchet@34120
   136
(* "no_assms"    bool    If "true", assumptions in structured proofs are     *)
blanchet@34120
   137
(*                       not considered.                                     *)
blanchet@30314
   138
(* "expect"      string  Expected result ("genuine", "potential", "none", or *)
blanchet@34120
   139
(*                       "unknown").                                         *)
webertj@14807
   140
(* ------------------------------------------------------------------------- *)
webertj@14807
   141
wenzelm@39046
   142
type params =
wenzelm@39046
   143
  {
wenzelm@39046
   144
    sizes    : (string * int) list,
wenzelm@39046
   145
    minsize  : int,
wenzelm@39046
   146
    maxsize  : int,
wenzelm@39046
   147
    maxvars  : int,
wenzelm@39046
   148
    maxtime  : int,
wenzelm@39046
   149
    satsolver: string,
wenzelm@39046
   150
    no_assms : bool,
wenzelm@39046
   151
    expect   : string
wenzelm@39046
   152
  };
webertj@14807
   153
webertj@14807
   154
(* ------------------------------------------------------------------------- *)
webertj@14456
   155
(* interpretation: a term's interpretation is given by a variable of type    *)
webertj@14456
   156
(*                 'interpretation'                                          *)
webertj@14350
   157
(* ------------------------------------------------------------------------- *)
webertj@14350
   158
wenzelm@39046
   159
type interpretation =
wenzelm@39046
   160
  prop_formula list tree;
webertj@14350
   161
webertj@14350
   162
(* ------------------------------------------------------------------------- *)
webertj@14456
   163
(* model: a model specifies the size of types and the interpretation of      *)
webertj@14456
   164
(*        terms                                                              *)
webertj@14350
   165
(* ------------------------------------------------------------------------- *)
webertj@14350
   166
wenzelm@39046
   167
type model =
wenzelm@39046
   168
  (typ * int) list * (term * interpretation) list;
webertj@14350
   169
webertj@14456
   170
(* ------------------------------------------------------------------------- *)
webertj@14456
   171
(* arguments: additional arguments required during interpretation of terms   *)
webertj@14456
   172
(* ------------------------------------------------------------------------- *)
webertj@14807
   173
wenzelm@39046
   174
type arguments =
wenzelm@39046
   175
  {
wenzelm@39046
   176
    (* just passed unchanged from 'params': *)
wenzelm@39046
   177
    maxvars   : int,
wenzelm@39046
   178
    (* whether to use 'make_equality' or 'make_def_equality': *)
wenzelm@39046
   179
    def_eq    : bool,
wenzelm@39046
   180
    (* the following may change during the translation: *)
wenzelm@39046
   181
    next_idx  : int,
wenzelm@39046
   182
    bounds    : interpretation list,
wenzelm@39046
   183
    wellformed: prop_formula
wenzelm@39046
   184
  };
webertj@14456
   185
wenzelm@39049
   186
structure Data = Theory_Data
wenzelm@39046
   187
(
wenzelm@39046
   188
  type T =
wenzelm@39049
   189
    {interpreters: (string * (Proof.context -> model -> arguments -> term ->
wenzelm@39046
   190
      (interpretation * model * arguments) option)) list,
wenzelm@39049
   191
     printers: (string * (Proof.context -> model -> typ -> interpretation ->
wenzelm@39046
   192
      (int -> bool) -> term option)) list,
wenzelm@39046
   193
     parameters: string Symtab.table};
wenzelm@46960
   194
  val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
wenzelm@39046
   195
  val extend = I;
wenzelm@39046
   196
  fun merge
wenzelm@39046
   197
    ({interpreters = in1, printers = pr1, parameters = pa1},
wenzelm@39046
   198
     {interpreters = in2, printers = pr2, parameters = pa2}) : T =
wenzelm@39046
   199
    {interpreters = AList.merge (op =) (K true) (in1, in2),
wenzelm@39046
   200
     printers = AList.merge (op =) (K true) (pr1, pr2),
wenzelm@41472
   201
     parameters = Symtab.merge (op =) (pa1, pa2)};
wenzelm@39046
   202
);
webertj@14456
   203
wenzelm@42361
   204
val get_data = Data.get o Proof_Context.theory_of;
wenzelm@39049
   205
webertj@14350
   206
webertj@14350
   207
(* ------------------------------------------------------------------------- *)
webertj@15334
   208
(* interpret: interprets the term 't' using a suitable interpreter; returns  *)
webertj@15334
   209
(*            the interpretation and a (possibly extended) model that keeps  *)
webertj@15334
   210
(*            track of the interpretation of subterms                        *)
webertj@14350
   211
(* ------------------------------------------------------------------------- *)
webertj@14350
   212
wenzelm@39049
   213
fun interpret ctxt model args t =
wenzelm@39049
   214
  case get_first (fn (_, f) => f ctxt model args t)
wenzelm@39049
   215
      (#interpreters (get_data ctxt)) of
wenzelm@39046
   216
    NONE => raise REFUTE ("interpret",
wenzelm@39049
   217
      "no interpreter for term " ^ quote (Syntax.string_of_term ctxt t))
wenzelm@39046
   218
  | SOME x => x;
webertj@14456
   219
webertj@14456
   220
(* ------------------------------------------------------------------------- *)
webertj@25014
   221
(* print: converts the interpretation 'intr', which must denote a term of    *)
webertj@25014
   222
(*        type 'T', into a term using a suitable printer                     *)
webertj@14456
   223
(* ------------------------------------------------------------------------- *)
webertj@14350
   224
wenzelm@39049
   225
fun print ctxt model T intr assignment =
wenzelm@39049
   226
  case get_first (fn (_, f) => f ctxt model T intr assignment)
wenzelm@39049
   227
      (#printers (get_data ctxt)) of
wenzelm@39046
   228
    NONE => raise REFUTE ("print",
wenzelm@39049
   229
      "no printer for type " ^ quote (Syntax.string_of_typ ctxt T))
wenzelm@39046
   230
  | SOME x => x;
webertj@14456
   231
webertj@14456
   232
(* ------------------------------------------------------------------------- *)
webertj@14456
   233
(* print_model: turns the model into a string, using a fixed interpretation  *)
webertj@14807
   234
(*              (given by an assignment for Boolean variables) and suitable  *)
webertj@14456
   235
(*              printers                                                     *)
webertj@14456
   236
(* ------------------------------------------------------------------------- *)
webertj@14456
   237
wenzelm@39049
   238
fun print_model ctxt model assignment =
wenzelm@22567
   239
  let
wenzelm@22567
   240
    val (typs, terms) = model
wenzelm@22567
   241
    val typs_msg =
wenzelm@22567
   242
      if null typs then
wenzelm@22567
   243
        "empty universe (no type variables in term)\n"
wenzelm@22567
   244
      else
wenzelm@22567
   245
        "Size of types: " ^ commas (map (fn (T, i) =>
wenzelm@39049
   246
          Syntax.string_of_typ ctxt T ^ ": " ^ string_of_int i) typs) ^ "\n"
wenzelm@22567
   247
    val show_consts_msg =
wenzelm@39050
   248
      if not (Config.get ctxt show_consts) andalso Library.exists (is_Const o fst) terms then
wenzelm@39050
   249
        "enable \"show_consts\" to show the interpretation of constants\n"
wenzelm@22567
   250
      else
wenzelm@22567
   251
        ""
wenzelm@22567
   252
    val terms_msg =
wenzelm@22567
   253
      if null terms then
wenzelm@22567
   254
        "empty interpretation (no free variables in term)\n"
wenzelm@22567
   255
      else
wenzelm@32952
   256
        cat_lines (map_filter (fn (t, intr) =>
wenzelm@22567
   257
          (* print constants only if 'show_consts' is true *)
wenzelm@39050
   258
          if Config.get ctxt show_consts orelse not (is_Const t) then
wenzelm@39049
   259
            SOME (Syntax.string_of_term ctxt t ^ ": " ^
wenzelm@39049
   260
              Syntax.string_of_term ctxt
wenzelm@39049
   261
                (print ctxt model (Term.type_of t) intr assignment))
wenzelm@22567
   262
          else
wenzelm@22567
   263
            NONE) terms) ^ "\n"
wenzelm@22567
   264
  in
wenzelm@22567
   265
    typs_msg ^ show_consts_msg ^ terms_msg
wenzelm@22567
   266
  end;
webertj@14456
   267
webertj@14456
   268
webertj@14456
   269
(* ------------------------------------------------------------------------- *)
webertj@14456
   270
(* PARAMETER MANAGEMENT                                                      *)
webertj@14456
   271
(* ------------------------------------------------------------------------- *)
webertj@14456
   272
wenzelm@39049
   273
fun add_interpreter name f = Data.map (fn {interpreters, printers, parameters} =>
wenzelm@39049
   274
  case AList.lookup (op =) interpreters name of
wenzelm@39049
   275
    NONE => {interpreters = (name, f) :: interpreters,
wenzelm@39049
   276
      printers = printers, parameters = parameters}
wenzelm@39049
   277
  | SOME _ => error ("Interpreter " ^ name ^ " already declared"));
webertj@14456
   278
wenzelm@39049
   279
fun add_printer name f = Data.map (fn {interpreters, printers, parameters} =>
wenzelm@39049
   280
  case AList.lookup (op =) printers name of
wenzelm@39049
   281
    NONE => {interpreters = interpreters,
wenzelm@39049
   282
      printers = (name, f) :: printers, parameters = parameters}
wenzelm@39049
   283
  | SOME _ => error ("Printer " ^ name ^ " already declared"));
webertj@14456
   284
webertj@14456
   285
(* ------------------------------------------------------------------------- *)
wenzelm@39049
   286
(* set_default_param: stores the '(name, value)' pair in Data's              *)
webertj@14456
   287
(*                    parameter table                                        *)
webertj@14456
   288
(* ------------------------------------------------------------------------- *)
webertj@14456
   289
wenzelm@39049
   290
fun set_default_param (name, value) = Data.map
wenzelm@39046
   291
  (fn {interpreters, printers, parameters} =>
wenzelm@39046
   292
    {interpreters = interpreters, printers = printers,
wenzelm@39046
   293
      parameters = Symtab.update (name, value) parameters});
webertj@14350
   294
webertj@14350
   295
(* ------------------------------------------------------------------------- *)
webertj@14456
   296
(* get_default_param: retrieves the value associated with 'name' from        *)
wenzelm@39049
   297
(*                    Data's parameter table                                 *)
webertj@14456
   298
(* ------------------------------------------------------------------------- *)
webertj@14456
   299
wenzelm@39049
   300
val get_default_param = Symtab.lookup o #parameters o get_data;
webertj@14456
   301
webertj@14456
   302
(* ------------------------------------------------------------------------- *)
webertj@14456
   303
(* get_default_params: returns a list of all '(name, value)' pairs that are  *)
wenzelm@39049
   304
(*                     stored in Data's parameter table                      *)
webertj@14456
   305
(* ------------------------------------------------------------------------- *)
webertj@14456
   306
wenzelm@39049
   307
val get_default_params = Symtab.dest o #parameters o get_data;
webertj@14456
   308
webertj@14456
   309
(* ------------------------------------------------------------------------- *)
webertj@14456
   310
(* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
wenzelm@39049
   311
(*      override the default parameters currently specified, and             *)
webertj@14807
   312
(*      returns a record that can be passed to 'find_model'.                 *)
webertj@14456
   313
(* ------------------------------------------------------------------------- *)
webertj@14456
   314
wenzelm@39049
   315
fun actual_params ctxt override =
wenzelm@22567
   316
  let
blanchet@34120
   317
    fun read_bool (parms, name) =
blanchet@34120
   318
      case AList.lookup (op =) parms name of
blanchet@34120
   319
        SOME "true" => true
blanchet@34120
   320
      | SOME "false" => false
blanchet@34120
   321
      | SOME s => error ("parameter " ^ quote name ^
wenzelm@39046
   322
          " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
blanchet@34120
   323
      | NONE   => error ("parameter " ^ quote name ^
blanchet@34120
   324
          " must be assigned a value")
wenzelm@22567
   325
    fun read_int (parms, name) =
wenzelm@22567
   326
      case AList.lookup (op =) parms name of
wenzelm@39046
   327
        SOME s =>
wenzelm@39046
   328
          (case Int.fromString s of
wenzelm@39046
   329
            SOME i => i
wenzelm@39046
   330
          | NONE   => error ("parameter " ^ quote name ^
wenzelm@39046
   331
            " (value is " ^ quote s ^ ") must be an integer value"))
wenzelm@39046
   332
      | NONE => error ("parameter " ^ quote name ^
wenzelm@22567
   333
          " must be assigned a value")
wenzelm@22567
   334
    fun read_string (parms, name) =
wenzelm@22567
   335
      case AList.lookup (op =) parms name of
wenzelm@22567
   336
        SOME s => s
wenzelm@39046
   337
      | NONE => error ("parameter " ^ quote name ^
wenzelm@22567
   338
        " must be assigned a value")
wenzelm@22567
   339
    (* 'override' first, defaults last: *)
wenzelm@39049
   340
    val allparams = override @ get_default_params ctxt
wenzelm@39046
   341
    val minsize = read_int (allparams, "minsize")
wenzelm@39046
   342
    val maxsize = read_int (allparams, "maxsize")
wenzelm@39046
   343
    val maxvars = read_int (allparams, "maxvars")
wenzelm@39046
   344
    val maxtime = read_int (allparams, "maxtime")
wenzelm@22567
   345
    val satsolver = read_string (allparams, "satsolver")
blanchet@34120
   346
    val no_assms = read_bool (allparams, "no_assms")
blanchet@30314
   347
    val expect = the_default "" (AList.lookup (op =) allparams "expect")
wenzelm@22567
   348
    (* all remaining parameters of the form "string=int" are collected in *)
wenzelm@22567
   349
    (* 'sizes'                                                            *)
wenzelm@22567
   350
    (* TODO: it is currently not possible to specify a size for a type    *)
wenzelm@22567
   351
    (*       whose name is one of the other parameters (e.g. 'maxvars')   *)
wenzelm@22567
   352
    (* (string * int) list *)
wenzelm@39046
   353
    val sizes = map_filter
wenzelm@22567
   354
      (fn (name, value) => Option.map (pair name) (Int.fromString value))
wenzelm@33317
   355
      (filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
wenzelm@22567
   356
        andalso name<>"maxvars" andalso name<>"maxtime"
blanchet@34120
   357
        andalso name<>"satsolver" andalso name<>"no_assms") allparams)
wenzelm@22567
   358
  in
wenzelm@22567
   359
    {sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars,
blanchet@34120
   360
      maxtime=maxtime, satsolver=satsolver, no_assms=no_assms, expect=expect}
wenzelm@22567
   361
  end;
webertj@14807
   362
webertj@14807
   363
webertj@14807
   364
(* ------------------------------------------------------------------------- *)
webertj@14807
   365
(* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
webertj@14807
   366
(* ------------------------------------------------------------------------- *)
webertj@14807
   367
blanchet@58120
   368
fun typ_of_dtyp _ typ_assoc (Old_Datatype_Aux.DtTFree a) =
blanchet@58120
   369
    the (AList.lookup (op =) typ_assoc (Old_Datatype_Aux.DtTFree a))
blanchet@58120
   370
  | typ_of_dtyp descr typ_assoc (Old_Datatype_Aux.DtType (s, Us)) =
blanchet@55891
   371
    Type (s, map (typ_of_dtyp descr typ_assoc) Us)
blanchet@58120
   372
  | typ_of_dtyp descr typ_assoc (Old_Datatype_Aux.DtRec i) =
blanchet@55891
   373
    let val (s, ds, _) = the (AList.lookup (op =) descr i) in
blanchet@55891
   374
      Type (s, map (typ_of_dtyp descr typ_assoc) ds)
blanchet@55891
   375
    end
blanchet@55891
   376
blanchet@54757
   377
val close_form = ATP_Util.close_form
blanchet@43085
   378
val monomorphic_term = ATP_Util.monomorphic_term
blanchet@43085
   379
val specialize_type = ATP_Util.specialize_type
webertj@21985
   380
webertj@21985
   381
(* ------------------------------------------------------------------------- *)
webertj@21985
   382
(* is_const_of_class: returns 'true' iff 'Const (s, T)' is a constant that   *)
webertj@21985
   383
(*                    denotes membership to an axiomatic type class          *)
webertj@21985
   384
(* ------------------------------------------------------------------------- *)
webertj@21985
   385
blanchet@46096
   386
fun is_const_of_class thy (s, _) =
wenzelm@22567
   387
  let
wenzelm@22567
   388
    val class_const_names = map Logic.const_of_class (Sign.all_classes thy)
wenzelm@22567
   389
  in
wenzelm@22567
   390
    (* I'm not quite sure if checking the name 's' is sufficient, *)
wenzelm@22567
   391
    (* or if we should also check the type 'T'.                   *)
haftmann@36692
   392
    member (op =) class_const_names s
wenzelm@22567
   393
  end;
webertj@21985
   394
webertj@21985
   395
(* ------------------------------------------------------------------------- *)
webertj@21985
   396
(* is_IDT_constructor: returns 'true' iff 'Const (s, T)' is the constructor  *)
webertj@21985
   397
(*                     of an inductive datatype in 'thy'                     *)
webertj@21985
   398
(* ------------------------------------------------------------------------- *)
webertj@21985
   399
wenzelm@39046
   400
fun is_IDT_constructor thy (s, T) =
wenzelm@39046
   401
  (case body_type T of
wenzelm@39046
   402
    Type (s', _) =>
blanchet@58129
   403
      (case BNF_LFP_Compat.get_constrs thy s' of
wenzelm@22567
   404
        SOME constrs =>
wenzelm@39046
   405
          List.exists (fn (cname, cty) =>
wenzelm@39046
   406
            cname = s andalso Sign.typ_instance thy (T, cty)) constrs
wenzelm@39046
   407
      | NONE => false)
wenzelm@39046
   408
  | _  => false);
webertj@21985
   409
webertj@21985
   410
(* ------------------------------------------------------------------------- *)
webertj@21985
   411
(* is_IDT_recursor: returns 'true' iff 'Const (s, T)' is the recursion       *)
webertj@21985
   412
(*                  operator of an inductive datatype in 'thy'               *)
webertj@21985
   413
(* ------------------------------------------------------------------------- *)
webertj@21985
   414
blanchet@46096
   415
fun is_IDT_recursor thy (s, _) =
wenzelm@22567
   416
  let
blanchet@58354
   417
    val rec_names = Symtab.fold (append o #rec_names o snd) (BNF_LFP_Compat.get_all thy []) []
wenzelm@22567
   418
  in
wenzelm@22567
   419
    (* I'm not quite sure if checking the name 's' is sufficient, *)
wenzelm@22567
   420
    (* or if we should also check the type 'T'.                   *)
haftmann@36692
   421
    member (op =) rec_names s
wenzelm@22567
   422
  end;
webertj@21985
   423
webertj@21985
   424
(* ------------------------------------------------------------------------- *)
blanchet@30275
   425
(* norm_rhs: maps  f ?t1 ... ?tn == rhs  to  %t1...tn. rhs                   *)
blanchet@30275
   426
(* ------------------------------------------------------------------------- *)
blanchet@30275
   427
wenzelm@39046
   428
fun norm_rhs eqn =
blanchet@30275
   429
  let
blanchet@30275
   430
    fun lambda (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
wenzelm@39046
   431
      | lambda v t = raise TERM ("lambda", [v, t])
blanchet@30275
   432
    val (lhs, rhs) = Logic.dest_equals eqn
wenzelm@39046
   433
    val (_, args) = Term.strip_comb lhs
blanchet@30275
   434
  in
blanchet@30275
   435
    fold lambda (rev args) rhs
blanchet@30275
   436
  end
blanchet@30275
   437
blanchet@30275
   438
(* ------------------------------------------------------------------------- *)
haftmann@37405
   439
(* get_def: looks up the definition of a constant                            *)
webertj@21985
   440
(* ------------------------------------------------------------------------- *)
webertj@21985
   441
wenzelm@39046
   442
fun get_def thy (s, T) =
wenzelm@22567
   443
  let
wenzelm@22567
   444
    fun get_def_ax [] = NONE
wenzelm@22567
   445
      | get_def_ax ((axname, ax) :: axioms) =
wenzelm@39046
   446
          (let
wenzelm@39046
   447
            val (lhs, _) = Logic.dest_equals ax  (* equations only *)
wenzelm@39046
   448
            val c        = Term.head_of lhs
wenzelm@39046
   449
            val (s', T') = Term.dest_Const c
wenzelm@22567
   450
          in
wenzelm@39046
   451
            if s=s' then
wenzelm@39046
   452
              let
wenzelm@39046
   453
                val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
wenzelm@39046
   454
                val ax'      = monomorphic_term typeSubs ax
wenzelm@39046
   455
                val rhs      = norm_rhs ax'
wenzelm@39046
   456
              in
wenzelm@39046
   457
                SOME (axname, rhs)
wenzelm@39046
   458
              end
wenzelm@39046
   459
            else
wenzelm@39046
   460
              get_def_ax axioms
wenzelm@39046
   461
          end handle ERROR _         => get_def_ax axioms
wenzelm@39046
   462
                   | TERM _          => get_def_ax axioms
wenzelm@39046
   463
                   | Type.TYPE_MATCH => get_def_ax axioms)
wenzelm@22567
   464
  in
wenzelm@22567
   465
    get_def_ax (Theory.all_axioms_of thy)
wenzelm@22567
   466
  end;
webertj@21985
   467
webertj@21985
   468
(* ------------------------------------------------------------------------- *)
webertj@21985
   469
(* get_typedef: looks up the definition of a type, as created by "typedef"   *)
webertj@21985
   470
(* ------------------------------------------------------------------------- *)
webertj@21985
   471
wenzelm@39046
   472
fun get_typedef thy T =
wenzelm@22567
   473
  let
wenzelm@22567
   474
    fun get_typedef_ax [] = NONE
wenzelm@22567
   475
      | get_typedef_ax ((axname, ax) :: axioms) =
wenzelm@39046
   476
          (let
wenzelm@39046
   477
            fun type_of_type_definition (Const (s', T')) =
wenzelm@39046
   478
                  if s'= @{const_name type_definition} then
wenzelm@39046
   479
                    SOME T'
wenzelm@39046
   480
                  else
wenzelm@39046
   481
                    NONE
wenzelm@39046
   482
              | type_of_type_definition (Free _) = NONE
wenzelm@39046
   483
              | type_of_type_definition (Var _) = NONE
wenzelm@39046
   484
              | type_of_type_definition (Bound _) = NONE
wenzelm@39046
   485
              | type_of_type_definition (Abs (_, _, body)) =
wenzelm@39046
   486
                  type_of_type_definition body
wenzelm@39046
   487
              | type_of_type_definition (t1 $ t2) =
wenzelm@39046
   488
                  (case type_of_type_definition t1 of
wenzelm@39046
   489
                    SOME x => SOME x
wenzelm@39046
   490
                  | NONE => type_of_type_definition t2)
wenzelm@22567
   491
          in
wenzelm@39046
   492
            case type_of_type_definition ax of
wenzelm@39046
   493
              SOME T' =>
wenzelm@39046
   494
                let
wenzelm@39049
   495
                  val T'' = domain_type (domain_type T')
wenzelm@39046
   496
                  val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
wenzelm@39046
   497
                in
wenzelm@39046
   498
                  SOME (axname, monomorphic_term typeSubs ax)
wenzelm@39046
   499
                end
wenzelm@39046
   500
            | NONE => get_typedef_ax axioms
wenzelm@39046
   501
          end handle ERROR _         => get_typedef_ax axioms
wenzelm@39046
   502
                   | TERM _          => get_typedef_ax axioms
wenzelm@39046
   503
                   | Type.TYPE_MATCH => get_typedef_ax axioms)
wenzelm@22567
   504
  in
wenzelm@22567
   505
    get_typedef_ax (Theory.all_axioms_of thy)
wenzelm@22567
   506
  end;
webertj@21985
   507
webertj@21985
   508
(* ------------------------------------------------------------------------- *)
webertj@21985
   509
(* get_classdef: looks up the defining axiom for an axiomatic type class, as *)
webertj@21985
   510
(*               created by the "axclass" command                            *)
webertj@21985
   511
(* ------------------------------------------------------------------------- *)
webertj@21985
   512
wenzelm@39046
   513
fun get_classdef thy class =
wenzelm@22567
   514
  let
wenzelm@22567
   515
    val axname = class ^ "_class_def"
wenzelm@22567
   516
  in
wenzelm@22567
   517
    Option.map (pair axname)
wenzelm@22567
   518
      (AList.lookup (op =) (Theory.all_axioms_of thy) axname)
wenzelm@22567
   519
  end;
webertj@21985
   520
webertj@21985
   521
(* ------------------------------------------------------------------------- *)
webertj@21985
   522
(* unfold_defs: unfolds all defined constants in a term 't', beta-eta        *)
webertj@21985
   523
(*              normalizes the result term; certain constants are not        *)
webertj@21985
   524
(*              unfolded (cf. 'collect_axioms' and the various interpreters  *)
webertj@21985
   525
(*              below): if the interpretation respects a definition anyway,  *)
webertj@21985
   526
(*              that definition does not need to be unfolded                 *)
webertj@21985
   527
(* ------------------------------------------------------------------------- *)
webertj@21985
   528
wenzelm@39046
   529
(* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
wenzelm@39046
   530
(*       normalization; this would save some unfolding for terms where    *)
wenzelm@39046
   531
(*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
wenzelm@39046
   532
(*       the other hand, this would cause additional work for terms where *)
wenzelm@39046
   533
(*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
webertj@21985
   534
wenzelm@39046
   535
fun unfold_defs thy t =
wenzelm@22567
   536
  let
wenzelm@22567
   537
    fun unfold_loop t =
wenzelm@22567
   538
      case t of
wenzelm@22567
   539
      (* Pure *)
wenzelm@56245
   540
        Const (@{const_name Pure.all}, _) => t
wenzelm@56245
   541
      | Const (@{const_name Pure.eq}, _) => t
wenzelm@56245
   542
      | Const (@{const_name Pure.imp}, _) => t
wenzelm@56243
   543
      | Const (@{const_name Pure.type}, _) => t  (* axiomatic type classes *)
wenzelm@22567
   544
      (* HOL *)
blanchet@29802
   545
      | Const (@{const_name Trueprop}, _) => t
blanchet@29802
   546
      | Const (@{const_name Not}, _) => t
wenzelm@22567
   547
      | (* redundant, since 'True' is also an IDT constructor *)
blanchet@29802
   548
        Const (@{const_name True}, _) => t
wenzelm@22567
   549
      | (* redundant, since 'False' is also an IDT constructor *)
blanchet@29802
   550
        Const (@{const_name False}, _) => t
blanchet@29802
   551
      | Const (@{const_name undefined}, _) => t
blanchet@29802
   552
      | Const (@{const_name The}, _) => t
blanchet@29820
   553
      | Const (@{const_name Hilbert_Choice.Eps}, _) => t
blanchet@29802
   554
      | Const (@{const_name All}, _) => t
blanchet@29802
   555
      | Const (@{const_name Ex}, _) => t
haftmann@38864
   556
      | Const (@{const_name HOL.eq}, _) => t
haftmann@38795
   557
      | Const (@{const_name HOL.conj}, _) => t
haftmann@38795
   558
      | Const (@{const_name HOL.disj}, _) => t
haftmann@38786
   559
      | Const (@{const_name HOL.implies}, _) => t
wenzelm@22567
   560
      (* sets *)
blanchet@29802
   561
      | Const (@{const_name Collect}, _) => t
haftmann@37677
   562
      | Const (@{const_name Set.member}, _) => t
wenzelm@22567
   563
      (* other optimizations *)
blanchet@29820
   564
      | Const (@{const_name Finite_Set.card}, _) => t
blanchet@29820
   565
      | Const (@{const_name Finite_Set.finite}, _) => t
haftmann@37388
   566
      | Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
wenzelm@39046
   567
          Type ("fun", [@{typ nat}, @{typ bool}])])) => t
haftmann@37388
   568
      | Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
wenzelm@39046
   569
          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
haftmann@37388
   570
      | Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
wenzelm@39046
   571
          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
haftmann@37388
   572
      | Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
wenzelm@39046
   573
          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
wenzelm@56252
   574
      | Const (@{const_name append}, _) => t
blanchet@29820
   575
      | Const (@{const_name fst}, _) => t
blanchet@29820
   576
      | Const (@{const_name snd}, _) => t
wenzelm@22567
   577
      (* simply-typed lambda calculus *)
wenzelm@22567
   578
      | Const (s, T) =>
wenzelm@39046
   579
          (if is_IDT_constructor thy (s, T)
wenzelm@39046
   580
            orelse is_IDT_recursor thy (s, T) then
wenzelm@39046
   581
            t  (* do not unfold IDT constructors/recursors *)
wenzelm@39046
   582
          (* unfold the constant if there is a defining equation *)
wenzelm@39046
   583
          else
wenzelm@39046
   584
            case get_def thy (s, T) of
blanchet@46096
   585
              SOME ((*axname*) _, rhs) =>
wenzelm@39046
   586
              (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
wenzelm@39046
   587
              (* occurs on the right-hand side of the equation, i.e. in  *)
wenzelm@39046
   588
              (* 'rhs', we must not use this equation to unfold, because *)
wenzelm@39046
   589
              (* that would loop.  Here would be the right place to      *)
wenzelm@39046
   590
              (* check this.  However, getting this really right seems   *)
wenzelm@39046
   591
              (* difficult because the user may state arbitrary axioms,  *)
wenzelm@39046
   592
              (* which could interact with overloading to create loops.  *)
wenzelm@39046
   593
              ((*tracing (" unfolding: " ^ axname);*)
wenzelm@39046
   594
               unfold_loop rhs)
wenzelm@39046
   595
            | NONE => t)
wenzelm@39046
   596
      | Free _ => t
wenzelm@39046
   597
      | Var _ => t
wenzelm@39046
   598
      | Bound _ => t
wenzelm@22567
   599
      | Abs (s, T, body) => Abs (s, T, unfold_loop body)
wenzelm@39046
   600
      | t1 $ t2 => (unfold_loop t1) $ (unfold_loop t2)
wenzelm@22567
   601
    val result = Envir.beta_eta_contract (unfold_loop t)
wenzelm@22567
   602
  in
wenzelm@22567
   603
    result
wenzelm@22567
   604
  end;
webertj@21985
   605
webertj@21985
   606
(* ------------------------------------------------------------------------- *)
webertj@21985
   607
(* collect_axioms: collects (monomorphic, universally quantified, unfolded   *)
webertj@21985
   608
(*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
webertj@14807
   609
(* ------------------------------------------------------------------------- *)
webertj@14807
   610
wenzelm@39046
   611
(* Note: to make the collection of axioms more easily extensible, this    *)
wenzelm@39046
   612
(*       function could be based on user-supplied "axiom collectors",     *)
wenzelm@39046
   613
(*       similar to 'interpret'/interpreters or 'print'/printers          *)
webertj@14807
   614
wenzelm@39046
   615
(* Note: currently we use "inverse" functions to the definitional         *)
wenzelm@39046
   616
(*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
wenzelm@39046
   617
(*       "typedef", "definition".  A more general approach could consider *)
wenzelm@39046
   618
(*       *every* axiom of the theory and collect it if it has a constant/ *)
wenzelm@39046
   619
(*       type/typeclass in common with the term 't'.                      *)
webertj@21985
   620
wenzelm@39046
   621
(* Which axioms are "relevant" for a particular term/type goes hand in    *)
wenzelm@39046
   622
(* hand with the interpretation of that term/type by its interpreter (see *)
wenzelm@39046
   623
(* way below): if the interpretation respects an axiom anyway, the axiom  *)
wenzelm@39046
   624
(* does not need to be added as a constraint here.                        *)
webertj@14807
   625
wenzelm@39046
   626
(* To avoid collecting the same axiom multiple times, we use an           *)
wenzelm@39046
   627
(* accumulator 'axs' which contains all axioms collected so far.          *)
webertj@14807
   628
wenzelm@56256
   629
local
wenzelm@56256
   630
wenzelm@56256
   631
fun get_axiom thy xname =
wenzelm@56256
   632
  Name_Space.check (Context.Theory thy) (Theory.axiom_table thy) (xname, Position.none);
wenzelm@56256
   633
wenzelm@56256
   634
val the_eq_trivial = get_axiom @{theory HOL} "the_eq_trivial";
wenzelm@56256
   635
val someI = get_axiom @{theory Hilbert_Choice} "someI";
wenzelm@56256
   636
wenzelm@56256
   637
in
wenzelm@56256
   638
wenzelm@39049
   639
fun collect_axioms ctxt t =
wenzelm@22567
   640
  let
wenzelm@42361
   641
    val thy = Proof_Context.theory_of ctxt
wenzelm@32950
   642
    val _ = tracing "Adding axioms..."
wenzelm@22567
   643
    fun collect_this_axiom (axname, ax) axs =
wenzelm@33246
   644
      let
wenzelm@33246
   645
        val ax' = unfold_defs thy ax
wenzelm@33246
   646
      in
wenzelm@33246
   647
        if member (op aconv) axs ax' then axs
wenzelm@33246
   648
        else (tracing axname; collect_term_axioms ax' (ax' :: axs))
wenzelm@33246
   649
      end
wenzelm@33246
   650
    and collect_sort_axioms T axs =
wenzelm@33246
   651
      let
wenzelm@33246
   652
        val sort =
wenzelm@33246
   653
          (case T of
wenzelm@33246
   654
            TFree (_, sort) => sort
wenzelm@33246
   655
          | TVar (_, sort)  => sort
wenzelm@33246
   656
          | _ => raise REFUTE ("collect_axioms",
wenzelm@39049
   657
              "type " ^ Syntax.string_of_typ ctxt T ^ " is not a variable"))
wenzelm@33246
   658
        (* obtain axioms for all superclasses *)
wenzelm@33246
   659
        val superclasses = sort @ maps (Sign.super_classes thy) sort
wenzelm@33246
   660
        (* merely an optimization, because 'collect_this_axiom' disallows *)
wenzelm@33246
   661
        (* duplicate axioms anyway:                                       *)
wenzelm@33246
   662
        val superclasses = distinct (op =) superclasses
wenzelm@33246
   663
        val class_axioms = maps (fn class => map (fn ax =>
wenzelm@33246
   664
          ("<" ^ class ^ ">", Thm.prop_of ax))
wenzelm@51685
   665
          (#axioms (Axclass.get_info thy class) handle ERROR _ => []))
wenzelm@33246
   666
          superclasses
wenzelm@33246
   667
        (* replace the (at most one) schematic type variable in each axiom *)
wenzelm@33246
   668
        (* by the actual type 'T'                                          *)
wenzelm@33246
   669
        val monomorphic_class_axioms = map (fn (axname, ax) =>
wenzelm@33246
   670
          (case Term.add_tvars ax [] of
wenzelm@33246
   671
            [] => (axname, ax)
wenzelm@33246
   672
          | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
wenzelm@33246
   673
          | _ =>
wenzelm@33246
   674
            raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
wenzelm@39049
   675
              Syntax.string_of_term ctxt ax ^
wenzelm@33246
   676
              ") contains more than one type variable")))
wenzelm@33246
   677
          class_axioms
wenzelm@33246
   678
      in
wenzelm@33246
   679
        fold collect_this_axiom monomorphic_class_axioms axs
wenzelm@33246
   680
      end
wenzelm@33246
   681
    and collect_type_axioms T axs =
wenzelm@22567
   682
      case T of
wenzelm@22567
   683
      (* simple types *)
wenzelm@56252
   684
        Type (@{type_name prop}, []) => axs
wenzelm@56252
   685
      | Type (@{type_name fun}, [T1, T2]) => collect_type_axioms T2 (collect_type_axioms T1 axs)
blanchet@46098
   686
      | Type (@{type_name set}, [T1]) => collect_type_axioms T1 axs
wenzelm@22567
   687
      (* axiomatic type classes *)
wenzelm@56252
   688
      | Type (@{type_name itself}, [T1]) => collect_type_axioms T1 axs
wenzelm@33246
   689
      | Type (s, Ts) =>
blanchet@58354
   690
        (case BNF_LFP_Compat.get_info thy [] s of
blanchet@46096
   691
          SOME _ =>  (* inductive datatype *)
wenzelm@22567
   692
            (* only collect relevant type axioms for the argument types *)
wenzelm@33246
   693
            fold collect_type_axioms Ts axs
wenzelm@22567
   694
        | NONE =>
wenzelm@22567
   695
          (case get_typedef thy T of
wenzelm@22567
   696
            SOME (axname, ax) =>
wenzelm@39046
   697
              collect_this_axiom (axname, ax) axs
wenzelm@22567
   698
          | NONE =>
wenzelm@22567
   699
            (* unspecified type, perhaps introduced with "typedecl" *)
wenzelm@22567
   700
            (* at least collect relevant type axioms for the argument types *)
wenzelm@33246
   701
            fold collect_type_axioms Ts axs))
wenzelm@22567
   702
      (* axiomatic type classes *)
wenzelm@33246
   703
      | TFree _ => collect_sort_axioms T axs
wenzelm@33246
   704
      (* axiomatic type classes *)
wenzelm@33246
   705
      | TVar _ => collect_sort_axioms T axs
wenzelm@33246
   706
    and collect_term_axioms t axs =
wenzelm@22567
   707
      case t of
wenzelm@22567
   708
      (* Pure *)
wenzelm@56245
   709
        Const (@{const_name Pure.all}, _) => axs
wenzelm@56245
   710
      | Const (@{const_name Pure.eq}, _) => axs
wenzelm@56245
   711
      | Const (@{const_name Pure.imp}, _) => axs
wenzelm@22567
   712
      (* axiomatic type classes *)
wenzelm@56243
   713
      | Const (@{const_name Pure.type}, T) => collect_type_axioms T axs
wenzelm@22567
   714
      (* HOL *)
blanchet@29802
   715
      | Const (@{const_name Trueprop}, _) => axs
blanchet@29802
   716
      | Const (@{const_name Not}, _) => axs
wenzelm@22567
   717
      (* redundant, since 'True' is also an IDT constructor *)
blanchet@29802
   718
      | Const (@{const_name True}, _) => axs
wenzelm@22567
   719
      (* redundant, since 'False' is also an IDT constructor *)
blanchet@29802
   720
      | Const (@{const_name False}, _) => axs
wenzelm@33246
   721
      | Const (@{const_name undefined}, T) => collect_type_axioms T axs
blanchet@29802
   722
      | Const (@{const_name The}, T) =>
wenzelm@39046
   723
          let
wenzelm@56256
   724
            val ax = specialize_type thy (@{const_name The}, T) (#2 the_eq_trivial)
wenzelm@39046
   725
          in
wenzelm@56256
   726
            collect_this_axiom (#1 the_eq_trivial, ax) axs
wenzelm@39046
   727
          end
blanchet@29820
   728
      | Const (@{const_name Hilbert_Choice.Eps}, T) =>
wenzelm@39046
   729
          let
wenzelm@56256
   730
            val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T) (#2 someI)
wenzelm@39046
   731
          in
wenzelm@56256
   732
            collect_this_axiom (#1 someI, ax) axs
wenzelm@39046
   733
          end
wenzelm@33246
   734
      | Const (@{const_name All}, T) => collect_type_axioms T axs
wenzelm@33246
   735
      | Const (@{const_name Ex}, T) => collect_type_axioms T axs
haftmann@38864
   736
      | Const (@{const_name HOL.eq}, T) => collect_type_axioms T axs
haftmann@38795
   737
      | Const (@{const_name HOL.conj}, _) => axs
haftmann@38795
   738
      | Const (@{const_name HOL.disj}, _) => axs
haftmann@38786
   739
      | Const (@{const_name HOL.implies}, _) => axs
wenzelm@22567
   740
      (* sets *)
wenzelm@33246
   741
      | Const (@{const_name Collect}, T) => collect_type_axioms T axs
haftmann@37677
   742
      | Const (@{const_name Set.member}, T) => collect_type_axioms T axs
wenzelm@22567
   743
      (* other optimizations *)
wenzelm@33246
   744
      | Const (@{const_name Finite_Set.card}, T) => collect_type_axioms T axs
blanchet@29820
   745
      | Const (@{const_name Finite_Set.finite}, T) =>
wenzelm@33246
   746
        collect_type_axioms T axs
haftmann@37388
   747
      | Const (@{const_name Orderings.less}, T as Type ("fun", [@{typ nat},
haftmann@38553
   748
        Type ("fun", [@{typ nat}, @{typ bool}])])) =>
wenzelm@33246
   749
          collect_type_axioms T axs
haftmann@37388
   750
      | Const (@{const_name Groups.plus}, T as Type ("fun", [@{typ nat},
haftmann@37388
   751
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33246
   752
          collect_type_axioms T axs
haftmann@37388
   753
      | Const (@{const_name Groups.minus}, T as Type ("fun", [@{typ nat},
haftmann@37388
   754
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33246
   755
          collect_type_axioms T axs
haftmann@37388
   756
      | Const (@{const_name Groups.times}, T as Type ("fun", [@{typ nat},
haftmann@37388
   757
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33246
   758
          collect_type_axioms T axs
wenzelm@56252
   759
      | Const (@{const_name append}, T) => collect_type_axioms T axs
wenzelm@33246
   760
      | Const (@{const_name fst}, T) => collect_type_axioms T axs
wenzelm@33246
   761
      | Const (@{const_name snd}, T) => collect_type_axioms T axs
wenzelm@22567
   762
      (* simply-typed lambda calculus *)
blanchet@29802
   763
      | Const (s, T) =>
wenzelm@22567
   764
          if is_const_of_class thy (s, T) then
wenzelm@22567
   765
            (* axiomatic type classes: add "OFCLASS(?'a::c, c_class)" *)
wenzelm@22567
   766
            (* and the class definition                               *)
wenzelm@22567
   767
            let
wenzelm@33246
   768
              val class = Logic.class_of_const s
wenzelm@31943
   769
              val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]), class)
wenzelm@33246
   770
              val ax_in = SOME (specialize_type thy (s, T) of_class)
wenzelm@22567
   771
                (* type match may fail due to sort constraints *)
wenzelm@22567
   772
                handle Type.TYPE_MATCH => NONE
wenzelm@39049
   773
              val ax_1 = Option.map (fn ax => (Syntax.string_of_term ctxt ax, ax)) ax_in
wenzelm@33246
   774
              val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
wenzelm@22567
   775
            in
wenzelm@33246
   776
              collect_type_axioms T (fold collect_this_axiom (map_filter I [ax_1, ax_2]) axs)
wenzelm@22567
   777
            end
wenzelm@22567
   778
          else if is_IDT_constructor thy (s, T)
wenzelm@39049
   779
            orelse is_IDT_recursor thy (s, T)
wenzelm@39049
   780
          then
wenzelm@22567
   781
            (* only collect relevant type axioms *)
wenzelm@33246
   782
            collect_type_axioms T axs
wenzelm@22567
   783
          else
wenzelm@22567
   784
            (* other constants should have been unfolded, with some *)
wenzelm@22567
   785
            (* exceptions: e.g. Abs_xxx/Rep_xxx functions for       *)
wenzelm@22567
   786
            (* typedefs, or type-class related constants            *)
wenzelm@22567
   787
            (* only collect relevant type axioms *)
wenzelm@33246
   788
            collect_type_axioms T axs
wenzelm@33246
   789
      | Free (_, T) => collect_type_axioms T axs
wenzelm@33246
   790
      | Var (_, T) => collect_type_axioms T axs
wenzelm@33246
   791
      | Bound _ => axs
wenzelm@33246
   792
      | Abs (_, T, body) => collect_term_axioms body (collect_type_axioms T axs)
wenzelm@33246
   793
      | t1 $ t2 => collect_term_axioms t2 (collect_term_axioms t1 axs)
wenzelm@33246
   794
    val result = map close_form (collect_term_axioms t [])
wenzelm@32950
   795
    val _ = tracing " ...done."
wenzelm@22567
   796
  in
wenzelm@22567
   797
    result
wenzelm@22567
   798
  end;
webertj@14456
   799
wenzelm@56256
   800
end;
wenzelm@56256
   801
webertj@14456
   802
(* ------------------------------------------------------------------------- *)
webertj@14807
   803
(* ground_types: collects all ground types in a term (including argument     *)
webertj@14807
   804
(*               types of other types), suppressing duplicates.  Does not    *)
webertj@14807
   805
(*               return function types, set types, non-recursive IDTs, or    *)
webertj@14807
   806
(*               'propT'.  For IDTs, also the argument types of constructors *)
webertj@25014
   807
(*               and all mutually recursive IDTs are considered.             *)
webertj@14807
   808
(* ------------------------------------------------------------------------- *)
webertj@14807
   809
wenzelm@39049
   810
fun ground_types ctxt t =
wenzelm@22567
   811
  let
wenzelm@42361
   812
    val thy = Proof_Context.theory_of ctxt
wenzelm@29272
   813
    fun collect_types T acc =
webertj@25014
   814
      (case T of
wenzelm@56252
   815
        Type (@{type_name fun}, [T1, T2]) => collect_types T1 (collect_types T2 acc)
wenzelm@56252
   816
      | Type (@{type_name prop}, []) => acc
blanchet@46098
   817
      | Type (@{type_name set}, [T1]) => collect_types T1 acc
wenzelm@39046
   818
      | Type (s, Ts) =>
blanchet@58354
   819
          (case BNF_LFP_Compat.get_info thy [] s of
wenzelm@39046
   820
            SOME info =>  (* inductive datatype *)
wenzelm@39046
   821
              let
wenzelm@39046
   822
                val index = #index info
wenzelm@39046
   823
                val descr = #descr info
wenzelm@39046
   824
                val (_, typs, _) = the (AList.lookup (op =) descr index)
wenzelm@39046
   825
                val typ_assoc = typs ~~ Ts
wenzelm@39046
   826
                (* sanity check: every element in 'dtyps' must be a *)
wenzelm@39046
   827
                (* 'DtTFree'                                        *)
wenzelm@39046
   828
                val _ = if Library.exists (fn d =>
blanchet@58120
   829
                  case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) typs then
wenzelm@39046
   830
                  raise REFUTE ("ground_types", "datatype argument (for type "
wenzelm@39049
   831
                    ^ Syntax.string_of_typ ctxt T ^ ") is not a variable")
wenzelm@39046
   832
                else ()
wenzelm@39046
   833
                (* required for mutually recursive datatypes; those need to   *)
wenzelm@39046
   834
                (* be added even if they are an instance of an otherwise non- *)
wenzelm@39046
   835
                (* recursive datatype                                         *)
wenzelm@39046
   836
                fun collect_dtyp d acc =
webertj@25014
   837
                  let
wenzelm@39046
   838
                    val dT = typ_of_dtyp descr typ_assoc d
webertj@25014
   839
                  in
wenzelm@39046
   840
                    case d of
blanchet@58120
   841
                      Old_Datatype_Aux.DtTFree _ =>
wenzelm@39046
   842
                      collect_types dT acc
blanchet@58120
   843
                    | Old_Datatype_Aux.DtType (_, ds) =>
wenzelm@39046
   844
                      collect_types dT (fold_rev collect_dtyp ds acc)
blanchet@58120
   845
                    | Old_Datatype_Aux.DtRec i =>
wenzelm@39046
   846
                      if member (op =) acc dT then
wenzelm@39046
   847
                        acc  (* prevent infinite recursion *)
wenzelm@39046
   848
                      else
wenzelm@39046
   849
                        let
wenzelm@39046
   850
                          val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
wenzelm@39046
   851
                          (* if the current type is a recursive IDT (i.e. a depth *)
wenzelm@39046
   852
                          (* is required), add it to 'acc'                        *)
wenzelm@39046
   853
                          val acc_dT = if Library.exists (fn (_, ds) =>
blanchet@58120
   854
                            Library.exists Old_Datatype_Aux.is_rec_type ds) dconstrs then
wenzelm@39046
   855
                              insert (op =) dT acc
wenzelm@39046
   856
                            else acc
wenzelm@39046
   857
                          (* collect argument types *)
wenzelm@39046
   858
                          val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
wenzelm@39046
   859
                          (* collect constructor types *)
wenzelm@39046
   860
                          val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
wenzelm@39046
   861
                        in
wenzelm@39046
   862
                          acc_dconstrs
wenzelm@39046
   863
                        end
webertj@25014
   864
                  end
wenzelm@39046
   865
              in
wenzelm@39046
   866
                (* argument types 'Ts' could be added here, but they are also *)
wenzelm@39046
   867
                (* added by 'collect_dtyp' automatically                      *)
blanchet@58120
   868
                collect_dtyp (Old_Datatype_Aux.DtRec index) acc
wenzelm@39046
   869
              end
wenzelm@39046
   870
          | NONE =>
wenzelm@39046
   871
            (* not an inductive datatype, e.g. defined via "typedef" or *)
wenzelm@39046
   872
            (* "typedecl"                                               *)
wenzelm@39046
   873
            insert (op =) T (fold collect_types Ts acc))
wenzelm@39046
   874
      | TFree _ => insert (op =) T acc
wenzelm@39046
   875
      | TVar _ => insert (op =) T acc)
wenzelm@22567
   876
  in
wenzelm@29272
   877
    fold_types collect_types t []
wenzelm@22567
   878
  end;
webertj@14807
   879
webertj@14807
   880
(* ------------------------------------------------------------------------- *)
webertj@14807
   881
(* string_of_typ: (rather naive) conversion from types to strings, used to   *)
webertj@14807
   882
(*                look up the size of a type in 'sizes'.  Parameterized      *)
webertj@14807
   883
(*                types with different parameters (e.g. "'a list" vs. "bool  *)
webertj@14807
   884
(*                list") are identified.                                     *)
webertj@14807
   885
(* ------------------------------------------------------------------------- *)
webertj@14807
   886
wenzelm@39046
   887
fun string_of_typ (Type (s, _))     = s
wenzelm@39046
   888
  | string_of_typ (TFree (s, _))    = s
wenzelm@39046
   889
  | string_of_typ (TVar ((s,_), _)) = s;
webertj@14807
   890
webertj@14807
   891
(* ------------------------------------------------------------------------- *)
webertj@14807
   892
(* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
webertj@14807
   893
(*                 'minsize' to every type for which no size is specified in *)
webertj@14807
   894
(*                 'sizes'                                                   *)
webertj@14807
   895
(* ------------------------------------------------------------------------- *)
webertj@14807
   896
wenzelm@39046
   897
fun first_universe xs sizes minsize =
wenzelm@22567
   898
  let
wenzelm@22567
   899
    fun size_of_typ T =
wenzelm@22567
   900
      case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@22567
   901
        SOME n => n
wenzelm@33246
   902
      | NONE => minsize
wenzelm@22567
   903
  in
wenzelm@22567
   904
    map (fn T => (T, size_of_typ T)) xs
wenzelm@22567
   905
  end;
webertj@14807
   906
webertj@14807
   907
(* ------------------------------------------------------------------------- *)
webertj@14807
   908
(* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
webertj@14807
   909
(*                types), where the minimal size of a type is given by       *)
webertj@14807
   910
(*                'minsize', the maximal size is given by 'maxsize', and a   *)
webertj@14807
   911
(*                type may have a fixed size given in 'sizes'                *)
webertj@14456
   912
(* ------------------------------------------------------------------------- *)
webertj@14456
   913
wenzelm@39046
   914
fun next_universe xs sizes minsize maxsize =
wenzelm@22567
   915
  let
wenzelm@22567
   916
    (* creates the "first" list of length 'len', where the sum of all list *)
wenzelm@22567
   917
    (* elements is 'sum', and the length of the list is 'len'              *)
wenzelm@22567
   918
    fun make_first _ 0 sum =
wenzelm@39046
   919
          if sum = 0 then
wenzelm@39046
   920
            SOME []
wenzelm@39046
   921
          else
wenzelm@39046
   922
            NONE
wenzelm@22567
   923
      | make_first max len sum =
wenzelm@39046
   924
          if sum <= max orelse max < 0 then
wenzelm@39046
   925
            Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
wenzelm@39046
   926
          else
wenzelm@39046
   927
            Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
wenzelm@22567
   928
    (* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
wenzelm@22567
   929
    (* all list elements x (unless 'max'<0)                                *)
blanchet@46096
   930
    fun next _ _ _ [] =
wenzelm@39046
   931
          NONE
wenzelm@22567
   932
      | next max len sum [x] =
wenzelm@39046
   933
          (* we've reached the last list element, so there's no shift possible *)
wenzelm@39046
   934
          make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
wenzelm@22567
   935
      | next max len sum (x1::x2::xs) =
wenzelm@39046
   936
          if x1>0 andalso (x2<max orelse max<0) then
wenzelm@39046
   937
            (* we can shift *)
wenzelm@39046
   938
            SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
wenzelm@39046
   939
          else
wenzelm@39046
   940
            (* continue search *)
wenzelm@39046
   941
            next max (len+1) (sum+x1) (x2::xs)
wenzelm@22567
   942
    (* only consider those types for which the size is not fixed *)
wenzelm@33317
   943
    val mutables = filter_out (AList.defined (op =) sizes o string_of_typ o fst) xs
wenzelm@22567
   944
    (* subtract 'minsize' from every size (will be added again at the end) *)
wenzelm@22567
   945
    val diffs = map (fn (_, n) => n-minsize) mutables
wenzelm@22567
   946
  in
wenzelm@22567
   947
    case next (maxsize-minsize) 0 0 diffs of
wenzelm@22567
   948
      SOME diffs' =>
wenzelm@39046
   949
        (* merge with those types for which the size is fixed *)
wenzelm@39046
   950
        SOME (fst (fold_map (fn (T, _) => fn ds =>
wenzelm@39046
   951
          case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@39046
   952
          (* return the fixed size *)
wenzelm@39046
   953
            SOME n => ((T, n), ds)
wenzelm@39046
   954
          (* consume the head of 'ds', add 'minsize' *)
wenzelm@39046
   955
          | NONE   => ((T, minsize + hd ds), tl ds))
wenzelm@39046
   956
          xs diffs'))
wenzelm@39046
   957
    | NONE => NONE
wenzelm@22567
   958
  end;
webertj@14807
   959
webertj@14807
   960
(* ------------------------------------------------------------------------- *)
webertj@14807
   961
(* toTrue: converts the interpretation of a Boolean value to a propositional *)
webertj@14807
   962
(*         formula that is true iff the interpretation denotes "true"        *)
webertj@14807
   963
(* ------------------------------------------------------------------------- *)
webertj@14807
   964
wenzelm@39046
   965
fun toTrue (Leaf [fm, _]) = fm
wenzelm@39046
   966
  | toTrue _ = raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
webertj@14807
   967
webertj@14807
   968
(* ------------------------------------------------------------------------- *)
webertj@14807
   969
(* toFalse: converts the interpretation of a Boolean value to a              *)
webertj@14807
   970
(*          propositional formula that is true iff the interpretation        *)
webertj@14807
   971
(*          denotes "false"                                                  *)
webertj@14807
   972
(* ------------------------------------------------------------------------- *)
webertj@14807
   973
wenzelm@39046
   974
fun toFalse (Leaf [_, fm]) = fm
wenzelm@39046
   975
  | toFalse _ = raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
webertj@14807
   976
webertj@14807
   977
(* ------------------------------------------------------------------------- *)
webertj@14807
   978
(* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
webertj@14807
   979
(*             applies a SAT solver, and (in case a model is found) displays *)
webertj@14807
   980
(*             the model to the user by calling 'print_model'                *)
webertj@14807
   981
(* {...}     : parameters that control the translation/model generation      *)
blanchet@34120
   982
(* assm_ts   : assumptions to be considered unless "no_assms" is specified   *)
webertj@14807
   983
(* t         : term to be translated into a propositional formula            *)
webertj@14807
   984
(* negate    : if true, find a model that makes 't' false (rather than true) *)
webertj@14807
   985
(* ------------------------------------------------------------------------- *)
webertj@14807
   986
wenzelm@39049
   987
fun find_model ctxt
wenzelm@39046
   988
    {sizes, minsize, maxsize, maxvars, maxtime, satsolver, no_assms, expect}
wenzelm@39046
   989
    assm_ts t negate =
wenzelm@22567
   990
  let
wenzelm@42361
   991
    val thy = Proof_Context.theory_of ctxt
blanchet@33054
   992
    fun check_expect outcome_code =
blanchet@45387
   993
      if expect = "" orelse outcome_code = expect then outcome_code
blanchet@33054
   994
      else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
wenzelm@22567
   995
    fun wrapper () =
wenzelm@22567
   996
      let
wenzelm@39046
   997
        val timer = Timer.startRealTimer ()
wenzelm@39046
   998
        val t =
wenzelm@39046
   999
          if no_assms then t
wenzelm@39046
  1000
          else if negate then Logic.list_implies (assm_ts, t)
wenzelm@39046
  1001
          else Logic.mk_conjunction_list (t :: assm_ts)
wenzelm@39046
  1002
        val u = unfold_defs thy t
wenzelm@39049
  1003
        val _ = tracing ("Unfolded term: " ^ Syntax.string_of_term ctxt u)
wenzelm@39049
  1004
        val axioms = collect_axioms ctxt u
wenzelm@39049
  1005
        val types = fold (union (op =) o ground_types ctxt) (u :: axioms) []
wenzelm@39046
  1006
        val _ = tracing ("Ground types: "
wenzelm@39046
  1007
          ^ (if null types then "none."
wenzelm@39049
  1008
             else commas (map (Syntax.string_of_typ ctxt) types)))
wenzelm@39046
  1009
        (* we can only consider fragments of recursive IDTs, so we issue a  *)
wenzelm@39046
  1010
        (* warning if the formula contains a recursive IDT                  *)
wenzelm@39046
  1011
        (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
wenzelm@39046
  1012
        val maybe_spurious = Library.exists (fn
wenzelm@39046
  1013
            Type (s, _) =>
blanchet@58354
  1014
              (case BNF_LFP_Compat.get_info thy [] s of
wenzelm@39046
  1015
                SOME info =>  (* inductive datatype *)
wenzelm@39046
  1016
                  let
wenzelm@39046
  1017
                    val index           = #index info
wenzelm@39046
  1018
                    val descr           = #descr info
wenzelm@39046
  1019
                    val (_, _, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1020
                  in
wenzelm@39046
  1021
                    (* recursive datatype? *)
wenzelm@39046
  1022
                    Library.exists (fn (_, ds) =>
blanchet@58120
  1023
                      Library.exists Old_Datatype_Aux.is_rec_type ds) constrs
wenzelm@39046
  1024
                  end
wenzelm@39046
  1025
              | NONE => false)
wenzelm@39046
  1026
          | _ => false) types
wenzelm@39046
  1027
        val _ =
wenzelm@59352
  1028
          if maybe_spurious andalso Context_Position.is_visible ctxt then
wenzelm@59352
  1029
            warning "Term contains a recursive datatype; countermodel(s) may be spurious!"
wenzelm@59352
  1030
          else ()
wenzelm@39046
  1031
        fun find_model_loop universe =
wenzelm@22567
  1032
          let
wenzelm@39046
  1033
            val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
wenzelm@39046
  1034
            val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
wenzelm@39046
  1035
                    orelse raise TimeLimit.TimeOut
wenzelm@39046
  1036
            val init_model = (universe, [])
wenzelm@39046
  1037
            val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
wenzelm@39046
  1038
              bounds = [], wellformed = True}
wenzelm@39046
  1039
            val _ = tracing ("Translating term (sizes: "
wenzelm@39046
  1040
              ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
wenzelm@39046
  1041
            (* translate 'u' and all axioms *)
wenzelm@39046
  1042
            val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
wenzelm@39046
  1043
              let
wenzelm@39049
  1044
                val (i, m', a') = interpret ctxt m a t'
wenzelm@39046
  1045
              in
wenzelm@39046
  1046
                (* set 'def_eq' to 'true' *)
wenzelm@39046
  1047
                (i, (m', {maxvars = #maxvars a', def_eq = true,
wenzelm@39046
  1048
                  next_idx = #next_idx a', bounds = #bounds a',
wenzelm@39046
  1049
                  wellformed = #wellformed a'}))
wenzelm@39046
  1050
              end) (u :: axioms) (init_model, init_args)
wenzelm@39046
  1051
            (* make 'u' either true or false, and make all axioms true, and *)
wenzelm@39046
  1052
            (* add the well-formedness side condition                       *)
wenzelm@39046
  1053
            val fm_u = (if negate then toFalse else toTrue) (hd intrs)
wenzelm@41471
  1054
            val fm_ax = Prop_Logic.all (map toTrue (tl intrs))
wenzelm@41471
  1055
            val fm = Prop_Logic.all [#wellformed args, fm_ax, fm_u]
wenzelm@39046
  1056
            val _ =
wenzelm@59352
  1057
              (if member (op =) ["cdclite"] satsolver andalso Context_Position.is_visible ctxt then
wenzelm@39046
  1058
                warning ("Using SAT solver " ^ quote satsolver ^
wenzelm@39046
  1059
                         "; for better performance, consider installing an \
wenzelm@39046
  1060
                         \external solver.")
wenzelm@39046
  1061
               else ());
wenzelm@39046
  1062
            val solver =
blanchet@56853
  1063
              SAT_Solver.invoke_solver satsolver
wenzelm@39046
  1064
              handle Option.Option =>
wenzelm@39046
  1065
                     error ("Unknown SAT solver: " ^ quote satsolver ^
wenzelm@39046
  1066
                            ". Available solvers: " ^
blanchet@56853
  1067
                            commas (map (quote o fst) (SAT_Solver.get_solvers ())) ^ ".")
wenzelm@22567
  1068
          in
wenzelm@58843
  1069
            writeln "Invoking SAT solver...";
wenzelm@39046
  1070
            (case solver fm of
blanchet@56853
  1071
              SAT_Solver.SATISFIABLE assignment =>
wenzelm@58843
  1072
                (writeln ("Model found:\n" ^ print_model ctxt model
wenzelm@39046
  1073
                  (fn i => case assignment i of SOME b => b | NONE => true));
wenzelm@39046
  1074
                 if maybe_spurious then "potential" else "genuine")
blanchet@56853
  1075
            | SAT_Solver.UNSATISFIABLE _ =>
wenzelm@58843
  1076
                (writeln "No model exists.";
wenzelm@39046
  1077
                case next_universe universe sizes minsize maxsize of
wenzelm@39046
  1078
                  SOME universe' => find_model_loop universe'
wenzelm@58843
  1079
                | NONE => (writeln
wenzelm@40132
  1080
                    "Search terminated, no larger universe within the given limits.";
wenzelm@40132
  1081
                    "none"))
blanchet@56853
  1082
            | SAT_Solver.UNKNOWN =>
wenzelm@58843
  1083
                (writeln "No model found.";
wenzelm@39046
  1084
                case next_universe universe sizes minsize maxsize of
wenzelm@39046
  1085
                  SOME universe' => find_model_loop universe'
wenzelm@58843
  1086
                | NONE => (writeln
wenzelm@39046
  1087
                  "Search terminated, no larger universe within the given limits.";
blanchet@56853
  1088
                  "unknown"))) handle SAT_Solver.NOT_CONFIGURED =>
wenzelm@39046
  1089
              (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
wenzelm@39046
  1090
               "unknown")
wenzelm@39046
  1091
          end
wenzelm@39046
  1092
          handle MAXVARS_EXCEEDED =>
wenzelm@58843
  1093
            (writeln ("Search terminated, number of Boolean variables ("
wenzelm@39046
  1094
              ^ string_of_int maxvars ^ " allowed) exceeded.");
wenzelm@39046
  1095
              "unknown")
wenzelm@39046
  1096
blanchet@30314
  1097
        val outcome_code = find_model_loop (first_universe types sizes minsize)
wenzelm@22567
  1098
      in
blanchet@33054
  1099
        check_expect outcome_code
wenzelm@22567
  1100
      end
wenzelm@39046
  1101
  in
wenzelm@39046
  1102
    (* some parameter sanity checks *)
wenzelm@39046
  1103
    minsize>=1 orelse
wenzelm@39046
  1104
      error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
wenzelm@39046
  1105
    maxsize>=1 orelse
wenzelm@39046
  1106
      error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
wenzelm@39046
  1107
    maxsize>=minsize orelse
wenzelm@39046
  1108
      error ("\"maxsize\" (=" ^ string_of_int maxsize ^
wenzelm@39046
  1109
      ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
wenzelm@39046
  1110
    maxvars>=0 orelse
wenzelm@39046
  1111
      error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
wenzelm@39046
  1112
    maxtime>=0 orelse
wenzelm@39046
  1113
      error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
wenzelm@39046
  1114
    (* enter loop with or without time limit *)
wenzelm@58843
  1115
    writeln ("Trying to find a model that "
wenzelm@39046
  1116
      ^ (if negate then "refutes" else "satisfies") ^ ": "
wenzelm@39049
  1117
      ^ Syntax.string_of_term ctxt t);
wenzelm@39046
  1118
    if maxtime > 0 then (
wenzelm@39046
  1119
      TimeLimit.timeLimit (Time.fromSeconds maxtime)
wenzelm@22567
  1120
        wrapper ()
wenzelm@39046
  1121
      handle TimeLimit.TimeOut =>
wenzelm@58843
  1122
        (writeln ("Search terminated, time limit (" ^
wenzelm@39046
  1123
            string_of_int maxtime
wenzelm@39046
  1124
            ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
wenzelm@39046
  1125
         check_expect "unknown")
wenzelm@39046
  1126
    ) else wrapper ()
wenzelm@39046
  1127
  end;
webertj@14456
  1128
webertj@14456
  1129
webertj@14456
  1130
(* ------------------------------------------------------------------------- *)
webertj@14456
  1131
(* INTERFACE, PART 2: FINDING A MODEL                                        *)
webertj@14350
  1132
(* ------------------------------------------------------------------------- *)
webertj@14350
  1133
webertj@14350
  1134
(* ------------------------------------------------------------------------- *)
webertj@14456
  1135
(* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
webertj@14456
  1136
(* params      : list of '(name, value)' pairs used to override default      *)
webertj@14456
  1137
(*               parameters                                                  *)
webertj@14350
  1138
(* ------------------------------------------------------------------------- *)
webertj@14350
  1139
wenzelm@39049
  1140
fun satisfy_term ctxt params assm_ts t =
wenzelm@39049
  1141
  find_model ctxt (actual_params ctxt params) assm_ts t false;
webertj@14350
  1142
webertj@14350
  1143
(* ------------------------------------------------------------------------- *)
webertj@14456
  1144
(* refute_term: calls 'find_model' to find a model that refutes 't'          *)
webertj@14456
  1145
(* params     : list of '(name, value)' pairs used to override default       *)
webertj@14456
  1146
(*              parameters                                                   *)
webertj@14350
  1147
(* ------------------------------------------------------------------------- *)
webertj@14350
  1148
wenzelm@39049
  1149
fun refute_term ctxt params assm_ts t =
wenzelm@22567
  1150
  let
wenzelm@22567
  1151
    (* disallow schematic type variables, since we cannot properly negate  *)
wenzelm@22567
  1152
    (* terms containing them (their logical meaning is that there EXISTS a *)
wenzelm@22567
  1153
    (* type s.t. ...; to refute such a formula, we would have to show that *)
wenzelm@22567
  1154
    (* for ALL types, not ...)                                             *)
wenzelm@29272
  1155
    val _ = null (Term.add_tvars t []) orelse
wenzelm@22567
  1156
      error "Term to be refuted contains schematic type variables"
webertj@21556
  1157
wenzelm@22567
  1158
    (* existential closure over schematic variables *)
wenzelm@60924
  1159
    val vars = sort_by (fst o fst) (Term.add_vars t [])
wenzelm@22567
  1160
    (* Term.term *)
wenzelm@33246
  1161
    val ex_closure = fold (fn ((x, i), T) => fn t' =>
wenzelm@33246
  1162
      HOLogic.exists_const T $
wenzelm@33246
  1163
        Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
wenzelm@22567
  1164
    (* Note: If 't' is of type 'propT' (rather than 'boolT'), applying   *)
wenzelm@22567
  1165
    (* 'HOLogic.exists_const' is not type-correct.  However, this is not *)
wenzelm@22567
  1166
    (* really a problem as long as 'find_model' still interprets the     *)
wenzelm@22567
  1167
    (* resulting term correctly, without checking its type.              *)
webertj@21556
  1168
wenzelm@22567
  1169
    (* replace outermost universally quantified variables by Free's:     *)
wenzelm@22567
  1170
    (* refuting a term with Free's is generally faster than refuting a   *)
wenzelm@22567
  1171
    (* term with (nested) quantifiers, because quantifiers are expanded, *)
wenzelm@22567
  1172
    (* while the SAT solver searches for an interpretation for Free's.   *)
wenzelm@22567
  1173
    (* Also we get more information back that way, namely an             *)
wenzelm@22567
  1174
    (* interpretation which includes values for the (formerly)           *)
wenzelm@22567
  1175
    (* quantified variables.                                             *)
wenzelm@22567
  1176
    (* maps  !!x1...xn. !xk...xm. t   to   t  *)
wenzelm@56245
  1177
    fun strip_all_body (Const (@{const_name Pure.all}, _) $ Abs (_, _, t)) =
wenzelm@39046
  1178
          strip_all_body t
blanchet@29820
  1179
      | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@39046
  1180
          strip_all_body t
blanchet@29820
  1181
      | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
wenzelm@39046
  1182
          strip_all_body t
blanchet@29802
  1183
      | strip_all_body t = t
wenzelm@22567
  1184
    (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
wenzelm@56245
  1185
    fun strip_all_vars (Const (@{const_name Pure.all}, _) $ Abs (a, T, t)) =
wenzelm@39046
  1186
          (a, T) :: strip_all_vars t
blanchet@29802
  1187
      | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@39046
  1188
          strip_all_vars t
blanchet@29802
  1189
      | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
wenzelm@39046
  1190
          (a, T) :: strip_all_vars t
blanchet@46096
  1191
      | strip_all_vars _ = [] : (string * typ) list
wenzelm@22567
  1192
    val strip_t = strip_all_body ex_closure
wenzelm@39046
  1193
    val frees = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
wenzelm@22567
  1194
    val subst_t = Term.subst_bounds (map Free frees, strip_t)
wenzelm@22567
  1195
  in
wenzelm@39049
  1196
    find_model ctxt (actual_params ctxt params) assm_ts subst_t true
wenzelm@22567
  1197
  end;
webertj@14350
  1198
webertj@14350
  1199
(* ------------------------------------------------------------------------- *)
wenzelm@32857
  1200
(* refute_goal                                                               *)
webertj@14350
  1201
(* ------------------------------------------------------------------------- *)
webertj@14350
  1202
wenzelm@39046
  1203
fun refute_goal ctxt params th i =
blanchet@34120
  1204
  let
wenzelm@59582
  1205
    val t = th |> Thm.prop_of
blanchet@34120
  1206
  in
blanchet@34120
  1207
    if Logic.count_prems t = 0 then
wenzelm@58843
  1208
      (writeln "No subgoal!"; "none")
blanchet@34120
  1209
    else
blanchet@34120
  1210
      let
wenzelm@59582
  1211
        val assms = map Thm.term_of (Assumption.all_assms_of ctxt)
blanchet@34120
  1212
        val (t, frees) = Logic.goal_params t i
blanchet@34120
  1213
      in
wenzelm@39049
  1214
        refute_term ctxt params assms (subst_bounds (frees, t))
blanchet@34120
  1215
      end
blanchet@34120
  1216
  end
webertj@14350
  1217
webertj@14350
  1218
webertj@14350
  1219
(* ------------------------------------------------------------------------- *)
webertj@15292
  1220
(* INTERPRETERS: Auxiliary Functions                                         *)
webertj@14350
  1221
(* ------------------------------------------------------------------------- *)
webertj@14350
  1222
webertj@14350
  1223
(* ------------------------------------------------------------------------- *)
webertj@25014
  1224
(* make_constants: returns all interpretations for type 'T' that consist of  *)
webertj@25014
  1225
(*                 unit vectors with 'True'/'False' only (no Boolean         *)
webertj@25014
  1226
(*                 variables)                                                *)
webertj@14350
  1227
(* ------------------------------------------------------------------------- *)
webertj@14350
  1228
wenzelm@39049
  1229
fun make_constants ctxt model T =
wenzelm@22567
  1230
  let
wenzelm@22567
  1231
    (* returns a list with all unit vectors of length n *)
wenzelm@22567
  1232
    fun unit_vectors n =
wenzelm@39046
  1233
      let
wenzelm@39046
  1234
        (* returns the k-th unit vector of length n *)
wenzelm@39046
  1235
        fun unit_vector (k, n) =
wenzelm@39046
  1236
          Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
wenzelm@39046
  1237
        fun unit_vectors_loop k =
wenzelm@39046
  1238
          if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
wenzelm@39046
  1239
      in
wenzelm@39046
  1240
        unit_vectors_loop 1
wenzelm@39046
  1241
      end
wenzelm@22567
  1242
    (* returns a list of lists, each one consisting of n (possibly *)
wenzelm@22567
  1243
    (* identical) elements from 'xs'                               *)
wenzelm@39046
  1244
    fun pick_all 1 xs = map single xs
wenzelm@22567
  1245
      | pick_all n xs =
wenzelm@39046
  1246
          let val rec_pick = pick_all (n - 1) xs in
wenzelm@39046
  1247
            maps (fn x => map (cons x) rec_pick) xs
wenzelm@39046
  1248
          end
webertj@25014
  1249
    (* returns all constant interpretations that have the same tree *)
webertj@25014
  1250
    (* structure as the interpretation argument                     *)
webertj@25014
  1251
    fun make_constants_intr (Leaf xs) = unit_vectors (length xs)
webertj@25014
  1252
      | make_constants_intr (Node xs) = map Node (pick_all (length xs)
wenzelm@39046
  1253
          (make_constants_intr (hd xs)))
webertj@25014
  1254
    (* obtain the interpretation for a variable of type 'T' *)
wenzelm@39049
  1255
    val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1256
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1257
  in
webertj@25014
  1258
    make_constants_intr i
wenzelm@22567
  1259
  end;
webertj@14807
  1260
webertj@14807
  1261
(* ------------------------------------------------------------------------- *)
webertj@25014
  1262
(* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
webertj@25014
  1263
(*               (make_constants T)', but implemented more efficiently)      *)
webertj@14807
  1264
(* ------------------------------------------------------------------------- *)
webertj@14807
  1265
wenzelm@39046
  1266
(* returns 0 for an empty ground type or a function type with empty      *)
wenzelm@39046
  1267
(* codomain, but fails for a function type with empty domain --          *)
wenzelm@39046
  1268
(* admissibility of datatype constructor argument types (see "Inductive  *)
wenzelm@39046
  1269
(* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
wenzelm@39046
  1270
(* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
wenzelm@39046
  1271
(* never occur as the domain of a function type that is the type of a    *)
wenzelm@39046
  1272
(* constructor argument                                                  *)
webertj@25014
  1273
wenzelm@39049
  1274
fun size_of_type ctxt model T =
wenzelm@22567
  1275
  let
webertj@25014
  1276
    (* returns the number of elements that have the same tree structure as a *)
webertj@25014
  1277
    (* given interpretation                                                  *)
webertj@25014
  1278
    fun size_of_intr (Leaf xs) = length xs
wenzelm@39047
  1279
      | size_of_intr (Node xs) = Integer.pow (length xs) (size_of_intr (hd xs))
webertj@25014
  1280
    (* obtain the interpretation for a variable of type 'T' *)
wenzelm@39049
  1281
    val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1282
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1283
  in
webertj@25014
  1284
    size_of_intr i
wenzelm@22567
  1285
  end;
webertj@14807
  1286
webertj@14807
  1287
(* ------------------------------------------------------------------------- *)
webertj@14807
  1288
(* TT/FF: interpretations that denote "true" or "false", respectively        *)
webertj@14807
  1289
(* ------------------------------------------------------------------------- *)
webertj@14807
  1290
wenzelm@39046
  1291
val TT = Leaf [True, False];
webertj@14807
  1292
wenzelm@39046
  1293
val FF = Leaf [False, True];
webertj@14807
  1294
webertj@14807
  1295
(* ------------------------------------------------------------------------- *)
webertj@14807
  1296
(* make_equality: returns an interpretation that denotes (extensional)       *)
webertj@14807
  1297
(*                equality of two interpretations                            *)
webertj@15547
  1298
(* - two interpretations are 'equal' iff they are both defined and denote    *)
webertj@15547
  1299
(*   the same value                                                          *)
webertj@15547
  1300
(* - two interpretations are 'not_equal' iff they are both defined at least  *)
webertj@15547
  1301
(*   partially, and a defined part denotes different values                  *)
webertj@15547
  1302
(* - a completely undefined interpretation is neither 'equal' nor            *)
webertj@15547
  1303
(*   'not_equal' to another interpretation                                   *)
webertj@14807
  1304
(* ------------------------------------------------------------------------- *)
webertj@14807
  1305
wenzelm@39046
  1306
(* We could in principle represent '=' on a type T by a particular        *)
wenzelm@39046
  1307
(* interpretation.  However, the size of that interpretation is quadratic *)
wenzelm@39046
  1308
(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
wenzelm@39046
  1309
(* 'i2' directly is more efficient than constructing the interpretation   *)
wenzelm@39046
  1310
(* for equality on T first, and "applying" this interpretation to 'i1'    *)
wenzelm@39046
  1311
(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
webertj@14807
  1312
wenzelm@39046
  1313
fun make_equality (i1, i2) =
wenzelm@22567
  1314
  let
wenzelm@22567
  1315
    fun equal (i1, i2) =
wenzelm@22567
  1316
      (case i1 of
wenzelm@22567
  1317
        Leaf xs =>
wenzelm@39046
  1318
          (case i2 of
wenzelm@41471
  1319
            Leaf ys => Prop_Logic.dot_product (xs, ys)  (* defined and equal *)
wenzelm@39046
  1320
          | Node _  => raise REFUTE ("make_equality",
wenzelm@39046
  1321
            "second interpretation is higher"))
wenzelm@22567
  1322
      | Node xs =>
wenzelm@39046
  1323
          (case i2 of
wenzelm@39046
  1324
            Leaf _  => raise REFUTE ("make_equality",
wenzelm@39046
  1325
            "first interpretation is higher")
wenzelm@41471
  1326
          | Node ys => Prop_Logic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1327
    fun not_equal (i1, i2) =
wenzelm@22567
  1328
      (case i1 of
wenzelm@22567
  1329
        Leaf xs =>
wenzelm@39046
  1330
          (case i2 of
wenzelm@39046
  1331
            (* defined and not equal *)
wenzelm@41471
  1332
            Leaf ys => Prop_Logic.all ((Prop_Logic.exists xs)
wenzelm@41471
  1333
            :: (Prop_Logic.exists ys)
wenzelm@39046
  1334
            :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
wenzelm@39046
  1335
          | Node _  => raise REFUTE ("make_equality",
wenzelm@39046
  1336
            "second interpretation is higher"))
wenzelm@22567
  1337
      | Node xs =>
wenzelm@39046
  1338
          (case i2 of
wenzelm@39046
  1339
            Leaf _  => raise REFUTE ("make_equality",
wenzelm@39046
  1340
            "first interpretation is higher")
wenzelm@41471
  1341
          | Node ys => Prop_Logic.exists (map not_equal (xs ~~ ys))))
wenzelm@22567
  1342
  in
wenzelm@22567
  1343
    (* a value may be undefined; therefore 'not_equal' is not just the *)
wenzelm@22567
  1344
    (* negation of 'equal'                                             *)
wenzelm@22567
  1345
    Leaf [equal (i1, i2), not_equal (i1, i2)]
wenzelm@22567
  1346
  end;
webertj@14807
  1347
webertj@15292
  1348
(* ------------------------------------------------------------------------- *)
webertj@15547
  1349
(* make_def_equality: returns an interpretation that denotes (extensional)   *)
webertj@15547
  1350
(*                    equality of two interpretations                        *)
webertj@15547
  1351
(* This function treats undefined/partially defined interpretations          *)
webertj@15547
  1352
(* different from 'make_equality': two undefined interpretations are         *)
webertj@15547
  1353
(* considered equal, while a defined interpretation is considered not equal  *)
webertj@15547
  1354
(* to an undefined interpretation.                                           *)
webertj@15547
  1355
(* ------------------------------------------------------------------------- *)
webertj@15547
  1356
wenzelm@39046
  1357
fun make_def_equality (i1, i2) =
wenzelm@22567
  1358
  let
wenzelm@22567
  1359
    fun equal (i1, i2) =
wenzelm@22567
  1360
      (case i1 of
wenzelm@22567
  1361
        Leaf xs =>
wenzelm@39046
  1362
          (case i2 of
wenzelm@39046
  1363
            (* defined and equal, or both undefined *)
wenzelm@41471
  1364
            Leaf ys => SOr (Prop_Logic.dot_product (xs, ys),
wenzelm@41471
  1365
            SAnd (Prop_Logic.all (map SNot xs), Prop_Logic.all (map SNot ys)))
wenzelm@39046
  1366
          | Node _  => raise REFUTE ("make_def_equality",
wenzelm@39046
  1367
            "second interpretation is higher"))
wenzelm@22567
  1368
      | Node xs =>
wenzelm@39046
  1369
          (case i2 of
wenzelm@39046
  1370
            Leaf _  => raise REFUTE ("make_def_equality",
wenzelm@39046
  1371
            "first interpretation is higher")
wenzelm@41471
  1372
          | Node ys => Prop_Logic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1373
    val eq = equal (i1, i2)
wenzelm@22567
  1374
  in
wenzelm@22567
  1375
    Leaf [eq, SNot eq]
wenzelm@22567
  1376
  end;
webertj@15547
  1377
webertj@15547
  1378
(* ------------------------------------------------------------------------- *)
webertj@15547
  1379
(* interpretation_apply: returns an interpretation that denotes the result   *)
webertj@22092
  1380
(*                       of applying the function denoted by 'i1' to the     *)
webertj@15547
  1381
(*                       argument denoted by 'i2'                            *)
webertj@15547
  1382
(* ------------------------------------------------------------------------- *)
webertj@15547
  1383
wenzelm@39046
  1384
fun interpretation_apply (i1, i2) =
wenzelm@22567
  1385
  let
wenzelm@22567
  1386
    fun interpretation_disjunction (tr1,tr2) =
wenzelm@22567
  1387
      tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
wenzelm@22567
  1388
        (tree_pair (tr1,tr2))
wenzelm@22567
  1389
    fun prop_formula_times_interpretation (fm,tr) =
wenzelm@22567
  1390
      tree_map (map (fn x => SAnd (fm,x))) tr
wenzelm@22567
  1391
    fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
wenzelm@39046
  1392
          prop_formula_times_interpretation (fm,tr)
wenzelm@22567
  1393
      | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
wenzelm@39046
  1394
          interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
wenzelm@39046
  1395
            prop_formula_list_dot_product_interpretation_list (fms,trees))
wenzelm@22567
  1396
      | prop_formula_list_dot_product_interpretation_list (_,_) =
wenzelm@39046
  1397
          raise REFUTE ("interpretation_apply", "empty list (in dot product)")
wenzelm@22567
  1398
    (* returns a list of lists, each one consisting of one element from each *)
wenzelm@22567
  1399
    (* element of 'xss'                                                      *)
wenzelm@39046
  1400
    fun pick_all [xs] = map single xs
wenzelm@22567
  1401
      | pick_all (xs::xss) =
wenzelm@39046
  1402
          let val rec_pick = pick_all xss in
wenzelm@39046
  1403
            maps (fn x => map (cons x) rec_pick) xs
wenzelm@39046
  1404
          end
wenzelm@39046
  1405
      | pick_all _ = raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
wenzelm@39046
  1406
    fun interpretation_to_prop_formula_list (Leaf xs) = xs
wenzelm@22567
  1407
      | interpretation_to_prop_formula_list (Node trees) =
wenzelm@41471
  1408
          map Prop_Logic.all (pick_all
wenzelm@39046
  1409
            (map interpretation_to_prop_formula_list trees))
wenzelm@22567
  1410
  in
wenzelm@22567
  1411
    case i1 of
wenzelm@22567
  1412
      Leaf _ =>
wenzelm@39046
  1413
        raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
wenzelm@22567
  1414
    | Node xs =>
wenzelm@39046
  1415
        prop_formula_list_dot_product_interpretation_list
wenzelm@39046
  1416
          (interpretation_to_prop_formula_list i2, xs)
wenzelm@22567
  1417
  end;
webertj@15547
  1418
webertj@15547
  1419
(* ------------------------------------------------------------------------- *)
webertj@15292
  1420
(* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
webertj@15292
  1421
(* ------------------------------------------------------------------------- *)
webertj@15292
  1422
wenzelm@39046
  1423
fun eta_expand t i =
wenzelm@22567
  1424
  let
wenzelm@22567
  1425
    val Ts = Term.binder_types (Term.fastype_of t)
wenzelm@22567
  1426
    val t' = Term.incr_boundvars i t
wenzelm@22567
  1427
  in
wenzelm@33339
  1428
    fold_rev (fn T => fn term => Abs ("<eta_expand>", T, term))
wenzelm@33339
  1429
      (List.take (Ts, i))
wenzelm@33339
  1430
      (Term.list_comb (t', map Bound (i-1 downto 0)))
wenzelm@22567
  1431
  end;
webertj@15292
  1432
webertj@15335
  1433
(* ------------------------------------------------------------------------- *)
webertj@15547
  1434
(* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
webertj@15547
  1435
(*               is the sum (over its constructors) of the product (over     *)
webertj@15547
  1436
(*               their arguments) of the size of the argument types          *)
webertj@15335
  1437
(* ------------------------------------------------------------------------- *)
webertj@15335
  1438
wenzelm@39049
  1439
fun size_of_dtyp ctxt typ_sizes descr typ_assoc constructors =
wenzelm@39046
  1440
  Integer.sum (map (fn (_, dtyps) =>
wenzelm@39049
  1441
    Integer.prod (map (size_of_type ctxt (typ_sizes, []) o
wenzelm@39046
  1442
      (typ_of_dtyp descr typ_assoc)) dtyps))
wenzelm@39046
  1443
        constructors);
webertj@15335
  1444
webertj@15292
  1445
webertj@15292
  1446
(* ------------------------------------------------------------------------- *)
webertj@15292
  1447
(* INTERPRETERS: Actual Interpreters                                         *)
webertj@15292
  1448
(* ------------------------------------------------------------------------- *)
webertj@14807
  1449
wenzelm@39046
  1450
(* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
wenzelm@39046
  1451
(* variables, function types, and propT                                  *)
webertj@14807
  1452
wenzelm@39049
  1453
fun stlc_interpreter ctxt model args t =
wenzelm@22567
  1454
  let
wenzelm@39046
  1455
    val (typs, terms) = model
wenzelm@22567
  1456
    val {maxvars, def_eq, next_idx, bounds, wellformed} = args
wenzelm@22567
  1457
    fun interpret_groundterm T =
wenzelm@22567
  1458
      let
wenzelm@39046
  1459
        fun interpret_groundtype () =
wenzelm@39046
  1460
          let
wenzelm@39046
  1461
            (* the model must specify a size for ground types *)
wenzelm@39046
  1462
            val size =
wenzelm@39046
  1463
              if T = Term.propT then 2
wenzelm@39046
  1464
              else the (AList.lookup (op =) typs T)
wenzelm@39046
  1465
            val next = next_idx + size
wenzelm@39046
  1466
            (* check if 'maxvars' is large enough *)
wenzelm@39046
  1467
            val _ = (if next - 1 > maxvars andalso maxvars > 0 then
wenzelm@39046
  1468
              raise MAXVARS_EXCEEDED else ())
wenzelm@39046
  1469
            val fms  = map BoolVar (next_idx upto (next_idx + size - 1))
wenzelm@39046
  1470
            val intr = Leaf fms
wenzelm@39046
  1471
            fun one_of_two_false [] = True
wenzelm@41471
  1472
              | one_of_two_false (x::xs) = SAnd (Prop_Logic.all (map (fn x' =>
wenzelm@39046
  1473
                  SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@39046
  1474
            val wf = one_of_two_false fms
wenzelm@39046
  1475
          in
wenzelm@39046
  1476
            (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39046
  1477
            (* condition                                                  *)
wenzelm@39046
  1478
            SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@39046
  1479
              def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@39046
  1480
              wellformed = SAnd (wellformed, wf)})
wenzelm@39046
  1481
          end
wenzelm@22567
  1482
      in
wenzelm@39046
  1483
        case T of
wenzelm@39046
  1484
          Type ("fun", [T1, T2]) =>
wenzelm@39046
  1485
            let
wenzelm@39046
  1486
              (* we create 'size_of_type ... T1' different copies of the        *)
wenzelm@39046
  1487
              (* interpretation for 'T2', which are then combined into a single *)
wenzelm@39046
  1488
              (* new interpretation                                             *)
wenzelm@39046
  1489
              (* make fresh copies, with different variable indices *)
wenzelm@39046
  1490
              (* 'idx': next variable index                         *)
wenzelm@39046
  1491
              (* 'n'  : number of copies                            *)
wenzelm@39046
  1492
              fun make_copies idx 0 = (idx, [], True)
wenzelm@39046
  1493
                | make_copies idx n =
wenzelm@39046
  1494
                    let
wenzelm@39049
  1495
                      val (copy, _, new_args) = interpret ctxt (typs, [])
wenzelm@39046
  1496
                        {maxvars = maxvars, def_eq = false, next_idx = idx,
wenzelm@39046
  1497
                        bounds = [], wellformed = True} (Free ("dummy", T2))
wenzelm@39046
  1498
                      val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
wenzelm@39046
  1499
                    in
wenzelm@39046
  1500
                      (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
wenzelm@39046
  1501
                    end
wenzelm@39046
  1502
              val (next, copies, wf) = make_copies next_idx
wenzelm@39049
  1503
                (size_of_type ctxt model T1)
wenzelm@39046
  1504
              (* combine copies into a single interpretation *)
wenzelm@39046
  1505
              val intr = Node copies
wenzelm@39046
  1506
            in
wenzelm@39046
  1507
              (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39046
  1508
              (* condition                                                  *)
wenzelm@39046
  1509
              SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@39046
  1510
                def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@39046
  1511
                wellformed = SAnd (wellformed, wf)})
wenzelm@39046
  1512
            end
wenzelm@39046
  1513
        | Type _  => interpret_groundtype ()
wenzelm@39046
  1514
        | TFree _ => interpret_groundtype ()
wenzelm@39046
  1515
        | TVar  _ => interpret_groundtype ()
wenzelm@22567
  1516
      end
wenzelm@22567
  1517
  in
wenzelm@22567
  1518
    case AList.lookup (op =) terms t of
wenzelm@22567
  1519
      SOME intr =>
wenzelm@39046
  1520
        (* return an existing interpretation *)
wenzelm@39046
  1521
        SOME (intr, model, args)
wenzelm@22567
  1522
    | NONE =>
wenzelm@39046
  1523
        (case t of
wenzelm@39046
  1524
          Const (_, T) => interpret_groundterm T
wenzelm@39046
  1525
        | Free (_, T) => interpret_groundterm T
wenzelm@39046
  1526
        | Var (_, T) => interpret_groundterm T
wenzelm@42364
  1527
        | Bound i => SOME (nth (#bounds args) i, model, args)
blanchet@46096
  1528
        | Abs (_, T, body) =>
wenzelm@39046
  1529
            let
wenzelm@39046
  1530
              (* create all constants of type 'T' *)
wenzelm@39049
  1531
              val constants = make_constants ctxt model T
wenzelm@39046
  1532
              (* interpret the 'body' separately for each constant *)
wenzelm@39046
  1533
              val (bodies, (model', args')) = fold_map
wenzelm@39046
  1534
                (fn c => fn (m, a) =>
wenzelm@39046
  1535
                  let
wenzelm@39046
  1536
                    (* add 'c' to 'bounds' *)
wenzelm@39049
  1537
                    val (i', m', a') = interpret ctxt m {maxvars = #maxvars a,
wenzelm@39046
  1538
                      def_eq = #def_eq a, next_idx = #next_idx a,
wenzelm@39046
  1539
                      bounds = (c :: #bounds a), wellformed = #wellformed a} body
wenzelm@39046
  1540
                  in
wenzelm@39046
  1541
                    (* keep the new model m' and 'next_idx' and 'wellformed', *)
wenzelm@39046
  1542
                    (* but use old 'bounds'                                   *)
wenzelm@39046
  1543
                    (i', (m', {maxvars = maxvars, def_eq = def_eq,
wenzelm@39046
  1544
                      next_idx = #next_idx a', bounds = bounds,
wenzelm@39046
  1545
                      wellformed = #wellformed a'}))
wenzelm@39046
  1546
                  end)
wenzelm@39046
  1547
                constants (model, args)
wenzelm@39046
  1548
            in
wenzelm@39046
  1549
              SOME (Node bodies, model', args')
wenzelm@39046
  1550
            end
wenzelm@39046
  1551
        | t1 $ t2 =>
wenzelm@39046
  1552
            let
wenzelm@39046
  1553
              (* interpret 't1' and 't2' separately *)
wenzelm@39049
  1554
              val (intr1, model1, args1) = interpret ctxt model args t1
wenzelm@39049
  1555
              val (intr2, model2, args2) = interpret ctxt model1 args1 t2
wenzelm@39046
  1556
            in
wenzelm@39046
  1557
              SOME (interpretation_apply (intr1, intr2), model2, args2)
wenzelm@39046
  1558
            end)
wenzelm@22567
  1559
  end;
webertj@14807
  1560
wenzelm@39049
  1561
fun Pure_interpreter ctxt model args t =
wenzelm@39046
  1562
  case t of
wenzelm@56245
  1563
    Const (@{const_name Pure.all}, _) $ t1 =>
wenzelm@22567
  1564
      let
wenzelm@39049
  1565
        val (i, m, a) = interpret ctxt model args t1
wenzelm@22567
  1566
      in
wenzelm@22567
  1567
        case i of
wenzelm@22567
  1568
          Node xs =>
wenzelm@39046
  1569
            (* 3-valued logic *)
wenzelm@39046
  1570
            let
wenzelm@41471
  1571
              val fmTrue  = Prop_Logic.all (map toTrue xs)
wenzelm@41471
  1572
              val fmFalse = Prop_Logic.exists (map toFalse xs)
wenzelm@39046
  1573
            in
wenzelm@39046
  1574
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39046
  1575
            end
wenzelm@22567
  1576
        | _ =>
wenzelm@22567
  1577
          raise REFUTE ("Pure_interpreter",
wenzelm@56245
  1578
            "\"Pure.all\" is followed by a non-function")
wenzelm@22567
  1579
      end
wenzelm@56245
  1580
  | Const (@{const_name Pure.all}, _) =>
wenzelm@39049
  1581
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1582
  | Const (@{const_name Pure.eq}, _) $ t1 $ t2 =>
wenzelm@22567
  1583
      let
wenzelm@39049
  1584
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1585
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@22567
  1586
      in
wenzelm@22567
  1587
        (* we use either 'make_def_equality' or 'make_equality' *)
wenzelm@22567
  1588
        SOME ((if #def_eq args then make_def_equality else make_equality)
wenzelm@22567
  1589
          (i1, i2), m2, a2)
wenzelm@22567
  1590
      end
wenzelm@56245
  1591
  | Const (@{const_name Pure.eq}, _) $ _ =>
wenzelm@39049
  1592
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1593
  | Const (@{const_name Pure.eq}, _) =>
wenzelm@39049
  1594
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@56245
  1595
  | Const (@{const_name Pure.imp}, _) $ t1 $ t2 =>
wenzelm@22567
  1596
      (* 3-valued logic *)
wenzelm@22567
  1597
      let
wenzelm@39049
  1598
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1599
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1600
        val fmTrue = Prop_Logic.SOr (toFalse i1, toTrue i2)
wenzelm@41471
  1601
        val fmFalse = Prop_Logic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1602
      in
wenzelm@22567
  1603
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1604
      end
wenzelm@56245
  1605
  | Const (@{const_name Pure.imp}, _) $ _ =>
wenzelm@39049
  1606
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1607
  | Const (@{const_name Pure.imp}, _) =>
wenzelm@39049
  1608
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@39046
  1609
  | _ => NONE;
webertj@14807
  1610
wenzelm@39049
  1611
fun HOLogic_interpreter ctxt model args t =
wenzelm@39046
  1612
(* Providing interpretations directly is more efficient than unfolding the *)
wenzelm@39046
  1613
(* logical constants.  In HOL however, logical constants can themselves be *)
wenzelm@39046
  1614
(* arguments.  They are then translated using eta-expansion.               *)
wenzelm@39046
  1615
  case t of
wenzelm@39046
  1616
    Const (@{const_name Trueprop}, _) =>
wenzelm@22567
  1617
      SOME (Node [TT, FF], model, args)
wenzelm@39046
  1618
  | Const (@{const_name Not}, _) =>
wenzelm@22567
  1619
      SOME (Node [FF, TT], model, args)
wenzelm@39046
  1620
  (* redundant, since 'True' is also an IDT constructor *)
wenzelm@39046
  1621
  | Const (@{const_name True}, _) =>
wenzelm@22567
  1622
      SOME (TT, model, args)
wenzelm@39046
  1623
  (* redundant, since 'False' is also an IDT constructor *)
wenzelm@39046
  1624
  | Const (@{const_name False}, _) =>
wenzelm@22567
  1625
      SOME (FF, model, args)
wenzelm@56245
  1626
  | Const (@{const_name All}, _) $ t1 =>  (* similar to "Pure.all" *)
wenzelm@22567
  1627
      let
wenzelm@39049
  1628
        val (i, m, a) = interpret ctxt model args t1
wenzelm@22567
  1629
      in
wenzelm@22567
  1630
        case i of
wenzelm@22567
  1631
          Node xs =>
wenzelm@39046
  1632
            (* 3-valued logic *)
wenzelm@39046
  1633
            let
wenzelm@41471
  1634
              val fmTrue = Prop_Logic.all (map toTrue xs)
wenzelm@41471
  1635
              val fmFalse = Prop_Logic.exists (map toFalse xs)
wenzelm@39046
  1636
            in
wenzelm@39046
  1637
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39046
  1638
            end
wenzelm@22567
  1639
        | _ =>
wenzelm@22567
  1640
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1641
            "\"All\" is followed by a non-function")
wenzelm@22567
  1642
      end
wenzelm@39046
  1643
  | Const (@{const_name All}, _) =>
wenzelm@39049
  1644
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1645
  | Const (@{const_name Ex}, _) $ t1 =>
wenzelm@22567
  1646
      let
wenzelm@39049
  1647
        val (i, m, a) = interpret ctxt model args t1
wenzelm@22567
  1648
      in
wenzelm@22567
  1649
        case i of
wenzelm@22567
  1650
          Node xs =>
wenzelm@39046
  1651
            (* 3-valued logic *)
wenzelm@39046
  1652
            let
wenzelm@41471
  1653
              val fmTrue = Prop_Logic.exists (map toTrue xs)
wenzelm@41471
  1654
              val fmFalse = Prop_Logic.all (map toFalse xs)
wenzelm@39046
  1655
            in
wenzelm@39046
  1656
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39046
  1657
            end
wenzelm@22567
  1658
        | _ =>
wenzelm@22567
  1659
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1660
            "\"Ex\" is followed by a non-function")
wenzelm@22567
  1661
      end
wenzelm@39046
  1662
  | Const (@{const_name Ex}, _) =>
wenzelm@39049
  1663
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1664
  | Const (@{const_name HOL.eq}, _) $ t1 $ t2 =>  (* similar to Pure.eq *)
wenzelm@22567
  1665
      let
wenzelm@39049
  1666
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1667
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@22567
  1668
      in
wenzelm@22567
  1669
        SOME (make_equality (i1, i2), m2, a2)
wenzelm@22567
  1670
      end
blanchet@46096
  1671
  | Const (@{const_name HOL.eq}, _) $ _ =>
wenzelm@39049
  1672
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1673
  | Const (@{const_name HOL.eq}, _) =>
wenzelm@39049
  1674
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@39046
  1675
  | Const (@{const_name HOL.conj}, _) $ t1 $ t2 =>
wenzelm@22567
  1676
      (* 3-valued logic *)
wenzelm@22567
  1677
      let
wenzelm@39049
  1678
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1679
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1680
        val fmTrue = Prop_Logic.SAnd (toTrue i1, toTrue i2)
wenzelm@41471
  1681
        val fmFalse = Prop_Logic.SOr (toFalse i1, toFalse i2)
wenzelm@22567
  1682
      in
wenzelm@22567
  1683
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1684
      end
blanchet@46096
  1685
  | Const (@{const_name HOL.conj}, _) $ _ =>
wenzelm@39049
  1686
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1687
  | Const (@{const_name HOL.conj}, _) =>
wenzelm@39049
  1688
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@22567
  1689
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1690
      (* "False & undef":                                          *)
wenzelm@22567
  1691
      (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
wenzelm@39046
  1692
  | Const (@{const_name HOL.disj}, _) $ t1 $ t2 =>
wenzelm@22567
  1693
      (* 3-valued logic *)
wenzelm@22567
  1694
      let
wenzelm@39049
  1695
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1696
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1697
        val fmTrue = Prop_Logic.SOr (toTrue i1, toTrue i2)
wenzelm@41471
  1698
        val fmFalse = Prop_Logic.SAnd (toFalse i1, toFalse i2)
wenzelm@22567
  1699
      in
wenzelm@22567
  1700
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1701
      end
blanchet@46096
  1702
  | Const (@{const_name HOL.disj}, _) $ _ =>
wenzelm@39049
  1703
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1704
  | Const (@{const_name HOL.disj}, _) =>
wenzelm@39049
  1705
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@22567
  1706
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1707
      (* "True | undef":                                           *)
wenzelm@22567
  1708
      (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
wenzelm@56245
  1709
  | Const (@{const_name HOL.implies}, _) $ t1 $ t2 =>  (* similar to Pure.imp *)
wenzelm@22567
  1710
      (* 3-valued logic *)
wenzelm@22567
  1711
      let
wenzelm@39049
  1712
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1713
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1714
        val fmTrue = Prop_Logic.SOr (toFalse i1, toTrue i2)
wenzelm@41471
  1715
        val fmFalse = Prop_Logic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1716
      in
wenzelm@22567
  1717
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1718
      end
blanchet@46096
  1719
  | Const (@{const_name HOL.implies}, _) $ _ =>
wenzelm@39049
  1720
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1721
  | Const (@{const_name HOL.implies}, _) =>
wenzelm@39049
  1722
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@22567
  1723
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1724
      (* "False --> undef":                                        *)
wenzelm@22567
  1725
      (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
wenzelm@39046
  1726
  | _ => NONE;
webertj@14807
  1727
wenzelm@39046
  1728
(* interprets variables and constants whose type is an IDT (this is        *)
wenzelm@39046
  1729
(* relatively easy and merely requires us to compute the size of the IDT); *)
wenzelm@39046
  1730
(* constructors of IDTs however are properly interpreted by                *)
wenzelm@39046
  1731
(* 'IDT_constructor_interpreter'                                           *)
webertj@15547
  1732
wenzelm@39049
  1733
fun IDT_interpreter ctxt model args t =
wenzelm@22567
  1734
  let
wenzelm@42361
  1735
    val thy = Proof_Context.theory_of ctxt
wenzelm@22567
  1736
    val (typs, terms) = model
wenzelm@22567
  1737
    fun interpret_term (Type (s, Ts)) =
blanchet@58354
  1738
          (case BNF_LFP_Compat.get_info thy [] s of
wenzelm@39046
  1739
            SOME info =>  (* inductive datatype *)
wenzelm@39046
  1740
              let
wenzelm@55507
  1741
                (* only recursive IDTs have an associated depth *)
wenzelm@39046
  1742
                val depth = AList.lookup (op =) typs (Type (s, Ts))
wenzelm@39046
  1743
                (* sanity check: depth must be at least 0 *)
wenzelm@39046
  1744
                val _ =
wenzelm@39046
  1745
                  (case depth of SOME n =>
wenzelm@39046
  1746
                    if n < 0 then
wenzelm@39046
  1747
                      raise REFUTE ("IDT_interpreter", "negative depth")
wenzelm@39046
  1748
                    else ()
wenzelm@39046
  1749
                  | _ => ())
wenzelm@39046
  1750
              in
wenzelm@39046
  1751
                (* termination condition to avoid infinite recursion *)
wenzelm@39046
  1752
                if depth = (SOME 0) then
wenzelm@39046
  1753
                  (* return a leaf of size 0 *)
wenzelm@39046
  1754
                  SOME (Leaf [], model, args)
wenzelm@39046
  1755
                else
wenzelm@39046
  1756
                  let
wenzelm@39046
  1757
                    val index               = #index info
wenzelm@39046
  1758
                    val descr               = #descr info
wenzelm@39046
  1759
                    val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1760
                    val typ_assoc           = dtyps ~~ Ts
wenzelm@39046
  1761
                    (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39046
  1762
                    val _ =
wenzelm@39046
  1763
                      if Library.exists (fn d =>
blanchet@58120
  1764
                        case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39046
  1765
                      then
wenzelm@39046
  1766
                        raise REFUTE ("IDT_interpreter",
wenzelm@39046
  1767
                          "datatype argument (for type "
wenzelm@39049
  1768
                          ^ Syntax.string_of_typ ctxt (Type (s, Ts))
wenzelm@39046
  1769
                          ^ ") is not a variable")
wenzelm@39046
  1770
                      else ()
wenzelm@39046
  1771
                    (* if the model specifies a depth for the current type, *)
wenzelm@39046
  1772
                    (* decrement it to avoid infinite recursion             *)
wenzelm@39046
  1773
                    val typs' = case depth of NONE => typs | SOME n =>
wenzelm@39046
  1774
                      AList.update (op =) (Type (s, Ts), n-1) typs
wenzelm@39046
  1775
                    (* recursively compute the size of the datatype *)
wenzelm@39049
  1776
                    val size     = size_of_dtyp ctxt typs' descr typ_assoc constrs
wenzelm@39046
  1777
                    val next_idx = #next_idx args
wenzelm@39046
  1778
                    val next     = next_idx+size
wenzelm@39046
  1779
                    (* check if 'maxvars' is large enough *)
wenzelm@39046
  1780
                    val _        = (if next-1 > #maxvars args andalso
wenzelm@39046
  1781
                      #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
wenzelm@39046
  1782
                    val fms      = map BoolVar (next_idx upto (next_idx+size-1))
wenzelm@39046
  1783
                    val intr     = Leaf fms
wenzelm@39046
  1784
                    fun one_of_two_false [] = True
wenzelm@41471
  1785
                      | one_of_two_false (x::xs) = SAnd (Prop_Logic.all (map (fn x' =>
wenzelm@39046
  1786
                          SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@39046
  1787
                    val wf = one_of_two_false fms
wenzelm@39046
  1788
                  in
wenzelm@39046
  1789
                    (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39046
  1790
                    (* condition                                                  *)
wenzelm@39046
  1791
                    SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
wenzelm@39046
  1792
                      def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
wenzelm@39046
  1793
                      wellformed = SAnd (#wellformed args, wf)})
wenzelm@39046
  1794
                  end
wenzelm@39046
  1795
              end
wenzelm@39046
  1796
          | NONE =>  (* not an inductive datatype *)
wenzelm@39046
  1797
              NONE)
wenzelm@22567
  1798
      | interpret_term _ =  (* a (free or schematic) type variable *)
wenzelm@39046
  1799
          NONE
wenzelm@22567
  1800
  in
wenzelm@22567
  1801
    case AList.lookup (op =) terms t of
wenzelm@22567
  1802
      SOME intr =>
wenzelm@39046
  1803
        (* return an existing interpretation *)
wenzelm@39046
  1804
        SOME (intr, model, args)
wenzelm@22567
  1805
    | NONE =>
wenzelm@39046
  1806
        (case t of
wenzelm@39046
  1807
          Free (_, T) => interpret_term T
wenzelm@39046
  1808
        | Var (_, T) => interpret_term T
wenzelm@39046
  1809
        | Const (_, T) => interpret_term T
wenzelm@39046
  1810
        | _ => NONE)
wenzelm@22567
  1811
  end;
webertj@15547
  1812
wenzelm@39046
  1813
(* This function imposes an order on the elements of a datatype fragment  *)
wenzelm@39046
  1814
(* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
wenzelm@39046
  1815
(* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
wenzelm@39046
  1816
(* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
wenzelm@39046
  1817
(* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
wenzelm@39046
  1818
(* same for recursive datatypes, although the computation of indices gets *)
wenzelm@39046
  1819
(* a little tricky.                                                       *)
webertj@25014
  1820
wenzelm@39049
  1821
fun IDT_constructor_interpreter ctxt model args t =
wenzelm@22567
  1822
  let
wenzelm@42361
  1823
    val thy = Proof_Context.theory_of ctxt
webertj@25014
  1824
    (* returns a list of canonical representations for terms of the type 'T' *)
webertj@25014
  1825
    (* It would be nice if we could just use 'print' for this, but 'print'   *)
webertj@25014
  1826
    (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
webertj@25014
  1827
    (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
webertj@25014
  1828
    fun canonical_terms typs T =
wenzelm@39046
  1829
          (case T of
wenzelm@39046
  1830
            Type ("fun", [T1, T2]) =>
wenzelm@39046
  1831
            (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
wenzelm@39046
  1832
            (* least not for 'T2'                                               *)
wenzelm@39046
  1833
            let
wenzelm@39046
  1834
              (* returns a list of lists, each one consisting of n (possibly *)
wenzelm@39046
  1835
              (* identical) elements from 'xs'                               *)
wenzelm@39046
  1836
              fun pick_all 1 xs = map single xs
wenzelm@39046
  1837
                | pick_all n xs =
wenzelm@39046
  1838
                    let val rec_pick = pick_all (n-1) xs in
wenzelm@39046
  1839
                      maps (fn x => map (cons x) rec_pick) xs
wenzelm@39046
  1840
                    end
wenzelm@39046
  1841
              (* ["x1", ..., "xn"] *)
wenzelm@39046
  1842
              val terms1 = canonical_terms typs T1
wenzelm@39046
  1843
              (* ["y1", ..., "ym"] *)
wenzelm@39046
  1844
              val terms2 = canonical_terms typs T2
wenzelm@39046
  1845
              (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
wenzelm@39046
  1846
              (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
wenzelm@39046
  1847
              val functions = map (curry (op ~~) terms1)
wenzelm@39046
  1848
                (pick_all (length terms1) terms2)
wenzelm@39046
  1849
              (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
wenzelm@39046
  1850
              (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
wenzelm@39046
  1851
              val pairss = map (map HOLogic.mk_prod) functions
wenzelm@39046
  1852
              val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
wenzelm@39046
  1853
              val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
wenzelm@39046
  1854
              val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
wenzelm@39046
  1855
              val HOLogic_insert    =
wenzelm@39046
  1856
                Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
wenzelm@39046
  1857
            in
wenzelm@39046
  1858
              (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
wenzelm@39046
  1859
              map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
wenzelm@39046
  1860
                HOLogic_empty_set) pairss
webertj@25014
  1861
            end
webertj@25014
  1862
      | Type (s, Ts) =>
blanchet@58354
  1863
          (case BNF_LFP_Compat.get_info thy [] s of
wenzelm@39046
  1864
            SOME info =>
wenzelm@39046
  1865
              (case AList.lookup (op =) typs T of
wenzelm@39046
  1866
                SOME 0 =>
wenzelm@39046
  1867
                  (* termination condition to avoid infinite recursion *)
wenzelm@39046
  1868
                  []  (* at depth 0, every IDT is empty *)
wenzelm@39046
  1869
              | _ =>
webertj@25014
  1870
                let
wenzelm@39046
  1871
                  val index = #index info
wenzelm@39046
  1872
                  val descr = #descr info
wenzelm@39046
  1873
                  val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1874
                  val typ_assoc = dtyps ~~ Ts
wenzelm@39046
  1875
                  (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39046
  1876
                  val _ =
wenzelm@39046
  1877
                    if Library.exists (fn d =>
blanchet@58120
  1878
                      case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39046
  1879
                    then
wenzelm@39046
  1880
                      raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1881
                        "datatype argument (for type "
wenzelm@39049
  1882
                        ^ Syntax.string_of_typ ctxt T
wenzelm@39046
  1883
                        ^ ") is not a variable")
wenzelm@39046
  1884
                    else ()
wenzelm@39046
  1885
                  (* decrement depth for the IDT 'T' *)
wenzelm@39046
  1886
                  val typs' =
wenzelm@39046
  1887
                    (case AList.lookup (op =) typs T of NONE => typs
wenzelm@39046
  1888
                    | SOME n => AList.update (op =) (T, n-1) typs)
wenzelm@39046
  1889
                  fun constructor_terms terms [] = terms
wenzelm@39046
  1890
                    | constructor_terms terms (d::ds) =
wenzelm@39046
  1891
                        let
wenzelm@39046
  1892
                          val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39046
  1893
                          val d_terms = canonical_terms typs' dT
wenzelm@39046
  1894
                        in
wenzelm@39046
  1895
                          (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
wenzelm@39046
  1896
                          (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
wenzelm@39046
  1897
                          constructor_terms
wenzelm@39046
  1898
                            (map_product (curry op $) terms d_terms) ds
wenzelm@39046
  1899
                        end
webertj@25014
  1900
                in
wenzelm@39046
  1901
                  (* C_i ... < C_j ... if i < j *)
wenzelm@39046
  1902
                  maps (fn (cname, ctyps) =>
wenzelm@39046
  1903
                    let
wenzelm@39046
  1904
                      val cTerm = Const (cname,
wenzelm@39046
  1905
                        map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
wenzelm@39046
  1906
                    in
wenzelm@39046
  1907
                      constructor_terms [cTerm] ctyps
wenzelm@39046
  1908
                    end) constrs
wenzelm@39046
  1909
                end)
wenzelm@39046
  1910
          | NONE =>
wenzelm@39046
  1911
              (* not an inductive datatype; in this case the argument types in *)
wenzelm@39046
  1912
              (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
wenzelm@39049
  1913
              map (fn intr => print ctxt (typs, []) T intr (K false))
wenzelm@39049
  1914
                (make_constants ctxt (typs, []) T))
wenzelm@39046
  1915
      | _ =>  (* TFree ..., TVar ... *)
wenzelm@39049
  1916
          map (fn intr => print ctxt (typs, []) T intr (K false))
wenzelm@39049
  1917
            (make_constants ctxt (typs, []) T))
wenzelm@22567
  1918
    val (typs, terms) = model
wenzelm@22567
  1919
  in
wenzelm@22567
  1920
    case AList.lookup (op =) terms t of
wenzelm@22567
  1921
      SOME intr =>
wenzelm@39046
  1922
        (* return an existing interpretation *)
wenzelm@39046
  1923
        SOME (intr, model, args)
wenzelm@22567
  1924
    | NONE =>
wenzelm@39046
  1925
        (case t of
wenzelm@39046
  1926
          Const (s, T) =>
wenzelm@39046
  1927
            (case body_type T of
wenzelm@39046
  1928
              Type (s', Ts') =>
blanchet@58354
  1929
                (case BNF_LFP_Compat.get_info thy [] s' of
wenzelm@39046
  1930
                  SOME info =>  (* body type is an inductive datatype *)
wenzelm@22567
  1931
                    let
wenzelm@39046
  1932
                      val index               = #index info
wenzelm@39046
  1933
                      val descr               = #descr info
wenzelm@39046
  1934
                      val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1935
                      val typ_assoc           = dtyps ~~ Ts'
wenzelm@39046
  1936
                      (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39046
  1937
                      val _ = if Library.exists (fn d =>
blanchet@58120
  1938
                          case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
webertj@25014
  1939
                        then
webertj@25014
  1940
                          raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1941
                            "datatype argument (for type "
wenzelm@39049
  1942
                            ^ Syntax.string_of_typ ctxt (Type (s', Ts'))
wenzelm@39046
  1943
                            ^ ") is not a variable")
wenzelm@22567
  1944
                        else ()
blanchet@58322
  1945
                      (* split the constructors into those occurring before/after *)
wenzelm@39046
  1946
                      (* 'Const (s, T)'                                          *)
wenzelm@39046
  1947
                      val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
wenzelm@39046
  1948
                        not (cname = s andalso Sign.typ_instance thy (T,
wenzelm@39046
  1949
                          map (typ_of_dtyp descr typ_assoc) ctypes
wenzelm@39046
  1950
                            ---> Type (s', Ts')))) constrs
wenzelm@39046
  1951
                    in
wenzelm@39046
  1952
                      case constrs2 of
wenzelm@39046
  1953
                        [] =>
wenzelm@39046
  1954
                          (* 'Const (s, T)' is not a constructor of this datatype *)
wenzelm@39046
  1955
                          NONE
blanchet@46096
  1956
                      | (_, ctypes)::_ =>
wenzelm@39046
  1957
                          let
wenzelm@55507
  1958
                            (* only /recursive/ IDTs have an associated depth *)
wenzelm@39046
  1959
                            val depth = AList.lookup (op =) typs (Type (s', Ts'))
wenzelm@39046
  1960
                            (* this should never happen: at depth 0, this IDT fragment *)
wenzelm@39046
  1961
                            (* is definitely empty, and in this case we don't need to  *)
wenzelm@39046
  1962
                            (* interpret its constructors                              *)
wenzelm@39046
  1963
                            val _ = (case depth of SOME 0 =>
wenzelm@39046
  1964
                                raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1965
                                  "depth is 0")
wenzelm@39046
  1966
                              | _ => ())
wenzelm@39046
  1967
                            val typs' = (case depth of NONE => typs | SOME n =>
wenzelm@39046
  1968
                              AList.update (op =) (Type (s', Ts'), n-1) typs)
wenzelm@39046
  1969
                            (* elements of the datatype come before elements generated *)
wenzelm@39046
  1970
                            (* by 'Const (s, T)' iff they are generated by a           *)
wenzelm@39046
  1971
                            (* constructor in constrs1                                 *)
wenzelm@39049
  1972
                            val offset = size_of_dtyp ctxt typs' descr typ_assoc constrs1
wenzelm@39046
  1973
                            (* compute the total (current) size of the datatype *)
wenzelm@39046
  1974
                            val total = offset +
wenzelm@39049
  1975
                              size_of_dtyp ctxt typs' descr typ_assoc constrs2
wenzelm@39046
  1976
                            (* sanity check *)
wenzelm@39049
  1977
                            val _ = if total <> size_of_type ctxt (typs, [])
wenzelm@39046
  1978
                              (Type (s', Ts')) then
wenzelm@33246
  1979
                                raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1980
                                  "total is not equal to current size")
wenzelm@39046
  1981
                              else ()
wenzelm@39046
  1982
                            (* returns an interpretation where everything is mapped to *)
wenzelm@39046
  1983
                            (* an "undefined" element of the datatype                  *)
wenzelm@39046
  1984
                            fun make_undef [] = Leaf (replicate total False)
wenzelm@39046
  1985
                              | make_undef (d::ds) =
wenzelm@39046
  1986
                                  let
wenzelm@39046
  1987
                                    (* compute the current size of the type 'd' *)
wenzelm@39046
  1988
                                    val dT   = typ_of_dtyp descr typ_assoc d
wenzelm@39049
  1989
                                    val size = size_of_type ctxt (typs, []) dT
wenzelm@39046
  1990
                                  in
wenzelm@39046
  1991
                                    Node (replicate size (make_undef ds))
wenzelm@39046
  1992
                                  end
wenzelm@39046
  1993
                            (* returns the interpretation for a constructor *)
wenzelm@39046
  1994
                            fun make_constr [] offset =
wenzelm@39046
  1995
                                  if offset < total then
wenzelm@39046
  1996
                                    (Leaf (replicate offset False @ True ::
wenzelm@39046
  1997
                                      (replicate (total - offset - 1) False)), offset + 1)
wenzelm@39046
  1998
                                  else
wenzelm@39046
  1999
                                    raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2000
                                      "offset >= total")
wenzelm@39046
  2001
                              | make_constr (d::ds) offset =
wenzelm@39046
  2002
                                  let
wenzelm@39046
  2003
                                    val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39046
  2004
                                    (* compute canonical term representations for all   *)
wenzelm@39046
  2005
                                    (* elements of the type 'd' (with the reduced depth *)
wenzelm@39046
  2006
                                    (* for the IDT)                                     *)
wenzelm@39046
  2007
                                    val terms' = canonical_terms typs' dT
wenzelm@39046
  2008
                                    (* sanity check *)
wenzelm@39046
  2009
                                    val _ =
wenzelm@39049
  2010
                                      if length terms' <> size_of_type ctxt (typs', []) dT
wenzelm@39046
  2011
                                      then
wenzelm@39046
  2012
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2013
                                          "length of terms' is not equal to old size")
wenzelm@39046
  2014
                                      else ()
wenzelm@39046
  2015
                                    (* compute canonical term representations for all   *)
wenzelm@39046
  2016
                                    (* elements of the type 'd' (with the current depth *)
wenzelm@39046
  2017
                                    (* for the IDT)                                     *)
wenzelm@39046
  2018
                                    val terms = canonical_terms typs dT
wenzelm@39046
  2019
                                    (* sanity check *)
wenzelm@39046
  2020
                                    val _ =
wenzelm@39049
  2021
                                      if length terms <> size_of_type ctxt (typs, []) dT
wenzelm@39046
  2022
                                      then
wenzelm@39046
  2023
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2024
                                          "length of terms is not equal to current size")
wenzelm@39046
  2025
                                      else ()
wenzelm@39046
  2026
                                    (* sanity check *)
wenzelm@39046
  2027
                                    val _ =
wenzelm@39046
  2028
                                      if length terms < length terms' then
wenzelm@39046
  2029
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2030
                                          "current size is less than old size")
wenzelm@39046
  2031
                                      else ()
wenzelm@39046
  2032
                                    (* sanity check: every element of terms' must also be *)
wenzelm@39046
  2033
                                    (*               present in terms                     *)
wenzelm@39046
  2034
                                    val _ =
wenzelm@39046
  2035
                                      if forall (member (op =) terms) terms' then ()
wenzelm@39046
  2036
                                      else
wenzelm@39046
  2037
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2038
                                          "element has disappeared")
wenzelm@39046
  2039
                                    (* sanity check: the order on elements of terms' is    *)
wenzelm@39046
  2040
                                    (*               the same in terms, for those elements *)
wenzelm@39046
  2041
                                    val _ =
wenzelm@39046
  2042
                                      let
wenzelm@39046
  2043
                                        fun search (x::xs) (y::ys) =
wenzelm@39046
  2044
                                              if x = y then search xs ys else search (x::xs) ys
blanchet@46096
  2045
                                          | search (_::_) [] =
wenzelm@39046
  2046
                                              raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2047
                                                "element order not preserved")
wenzelm@39046
  2048
                                          | search [] _ = ()
wenzelm@39046
  2049
                                      in search terms' terms end
wenzelm@39046
  2050
                                    val (intrs, new_offset) =
wenzelm@39046
  2051
                                      fold_map (fn t_elem => fn off =>
wenzelm@39046
  2052
                                        (* if 't_elem' existed at the previous depth,    *)
wenzelm@39046
  2053
                                        (* proceed recursively, otherwise map the entire *)
wenzelm@39046
  2054
                                        (* subtree to "undefined"                        *)
wenzelm@39046
  2055
                                        if member (op =) terms' t_elem then
wenzelm@39046
  2056
                                          make_constr ds off
wenzelm@39046
  2057
                                        else
wenzelm@39046
  2058
                                          (make_undef ds, off))
wenzelm@39046
  2059
                                      terms offset
wenzelm@39046
  2060
                                  in
wenzelm@39046
  2061
                                    (Node intrs, new_offset)
wenzelm@39046
  2062
                                  end
wenzelm@39046
  2063
                          in
wenzelm@39046
  2064
                            SOME (fst (make_constr ctypes offset), model, args)
wenzelm@39046
  2065
                          end
wenzelm@22567
  2066
                    end
wenzelm@39046
  2067
                | NONE =>  (* body type is not an inductive datatype *)
wenzelm@39046
  2068
                    NONE)
wenzelm@39046
  2069
            | _ =>  (* body type is a (free or schematic) type variable *)
wenzelm@39046
  2070
              NONE)
wenzelm@39046
  2071
        | _ =>  (* term is not a constant *)
wenzelm@22567
  2072
          NONE)
wenzelm@22567
  2073
  end;
webertj@14807
  2074
wenzelm@39046
  2075
(* Difficult code ahead.  Make sure you understand the                *)
wenzelm@39046
  2076
(* 'IDT_constructor_interpreter' and the order in which it enumerates *)
wenzelm@39046
  2077
(* elements of an IDT before you try to understand this function.     *)
webertj@15547
  2078
wenzelm@39049
  2079
fun IDT_recursion_interpreter ctxt model args t =
wenzelm@39049
  2080
  let
wenzelm@42361
  2081
    val thy = Proof_Context.theory_of ctxt
wenzelm@39049
  2082
  in
wenzelm@39049
  2083
    (* careful: here we descend arbitrarily deep into 't', possibly before *)
wenzelm@39049
  2084
    (* any other interpreter for atomic terms has had a chance to look at  *)
wenzelm@39049
  2085
    (* 't'                                                                 *)
wenzelm@39049
  2086
    case strip_comb t of
wenzelm@39049
  2087
      (Const (s, T), params) =>
wenzelm@39049
  2088
        (* iterate over all datatypes in 'thy' *)
wenzelm@39049
  2089
        Symtab.fold (fn (_, info) => fn result =>
wenzelm@39049
  2090
          case result of
wenzelm@39049
  2091
            SOME _ =>
wenzelm@39049
  2092
              result  (* just keep 'result' *)
wenzelm@39049
  2093
          | NONE =>
wenzelm@39049
  2094
              if member (op =) (#rec_names info) s then
wenzelm@39049
  2095
                (* we do have a recursion operator of one of the (mutually *)
wenzelm@39049
  2096
                (* recursive) datatypes given by 'info'                    *)
wenzelm@39049
  2097
                let
wenzelm@39049
  2098
                  (* number of all constructors, including those of different  *)
wenzelm@39049
  2099
                  (* (mutually recursive) datatypes within the same descriptor *)
wenzelm@39049
  2100
                  val mconstrs_count =
wenzelm@39049
  2101
                    Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
wenzelm@39049
  2102
                in
wenzelm@39049
  2103
                  if mconstrs_count < length params then
wenzelm@39049
  2104
                    (* too many actual parameters; for now we'll use the *)
wenzelm@39049
  2105
                    (* 'stlc_interpreter' to strip off one application   *)
wenzelm@39049
  2106
                    NONE
wenzelm@39049
  2107
                  else if mconstrs_count > length params then
wenzelm@39049
  2108
                    (* too few actual parameters; we use eta expansion          *)
wenzelm@39049
  2109
                    (* Note that the resulting expansion of lambda abstractions *)
wenzelm@39049
  2110
                    (* by the 'stlc_interpreter' may be rather slow (depending  *)
wenzelm@39049
  2111
                    (* on the argument types and the size of the IDT, of        *)
wenzelm@39049
  2112
                    (* course).                                                 *)
wenzelm@39049
  2113
                    SOME (interpret ctxt model args (eta_expand t
wenzelm@39049
  2114
                      (mconstrs_count - length params)))
wenzelm@39049
  2115
                  else  (* mconstrs_count = length params *)
wenzelm@39049
  2116
                    let
wenzelm@39049
  2117
                      (* interpret each parameter separately *)
wenzelm@39049
  2118
                      val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
wenzelm@39049
  2119
                        let
wenzelm@39049
  2120
                          val (i, m', a') = interpret ctxt m a p
wenzelm@39049
  2121
                        in
wenzelm@39049
  2122
                          (i, (m', a'))
wenzelm@39049
  2123
                        end) params (model, args)
wenzelm@39049
  2124
                      val (typs, _) = model'
wenzelm@39049
  2125
                      (* 'index' is /not/ necessarily the index of the IDT that *)
wenzelm@39049
  2126
                      (* the recursion operator is associated with, but merely  *)
wenzelm@39049
  2127
                      (* the index of some mutually recursive IDT               *)
wenzelm@39049
  2128
                      val index         = #index info
wenzelm@39049
  2129
                      val descr         = #descr info
wenzelm@39049
  2130
                      val (_, dtyps, _) = the (AList.lookup (op =) descr index)
wenzelm@39049
  2131
                      (* sanity check: we assume that the order of constructors *)
wenzelm@39049
  2132
                      (*               in 'descr' is the same as the order of   *)
wenzelm@39049
  2133
                      (*               corresponding parameters, otherwise the  *)
wenzelm@39049
  2134
                      (*               association code below won't match the   *)
wenzelm@39049
  2135
                      (*               right constructors/parameters; we also   *)
wenzelm@39049
  2136
                      (*               assume that the order of recursion       *)
wenzelm@39049
  2137
                      (*               operators in '#rec_names info' is the    *)
wenzelm@39049
  2138
                      (*               same as the order of corresponding       *)
wenzelm@39049
  2139
                      (*               datatypes in 'descr'                     *)
wenzelm@39049
  2140
                      val _ = if map fst descr <> (0 upto (length descr - 1)) then
wenzelm@39049
  2141
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2142
                            "order of constructors and corresponding parameters/" ^
wenzelm@39049
  2143
                              "recursion operators and corresponding datatypes " ^
wenzelm@39049
  2144
                              "different?")
wenzelm@39049
  2145
                        else ()
wenzelm@39049
  2146
                      (* sanity check: every element in 'dtyps' must be a *)
wenzelm@39049
  2147
                      (*               'DtTFree'                          *)
wenzelm@39049
  2148
                      val _ =
wenzelm@39049
  2149
                        if Library.exists (fn d =>
blanchet@58120
  2150
                          case d of Old_Datatype_Aux.DtTFree _ => false
wenzelm@39049
  2151
                                  | _ => true) dtyps
wenzelm@39049
  2152
                        then
wenzelm@39049
  2153
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2154
                            "datatype argument is not a variable")
wenzelm@39049
  2155
                        else ()
wenzelm@39049
  2156
                      (* the type of a recursion operator is *)
wenzelm@39049
  2157
                      (* [T1, ..., Tn, IDT] ---> Tresult     *)
wenzelm@42364
  2158
                      val IDT = nth (binder_types T) mconstrs_count
wenzelm@39049
  2159
                      (* by our assumption on the order of recursion operators *)
wenzelm@39049
  2160
                      (* and datatypes, this is the index of the datatype      *)
wenzelm@39049
  2161
                      (* corresponding to the given recursion operator         *)
wenzelm@39049
  2162
                      val idt_index = find_index (fn s' => s' = s) (#rec_names info)
wenzelm@39049
  2163
                      (* mutually recursive types must have the same type   *)
wenzelm@39049
  2164
                      (* parameters, unless the mutual recursion comes from *)
wenzelm@39049
  2165
                      (* indirect recursion                                 *)
wenzelm@39049
  2166
                      fun rec_typ_assoc acc [] = acc
wenzelm@39049
  2167
                        | rec_typ_assoc acc ((d, T)::xs) =
wenzelm@39049
  2168
                            (case AList.lookup op= acc d of
wenzelm@39049
  2169
                              NONE =>
wenzelm@39049
  2170
                                (case d of
blanchet@58120
  2171
                                  Old_Datatype_Aux.DtTFree _ =>
wenzelm@39049
  2172
                                  (* add the association, proceed *)
wenzelm@39049
  2173
                                  rec_typ_assoc ((d, T)::acc) xs
blanchet@58120
  2174
                                | Old_Datatype_Aux.DtType (s, ds) =>
wenzelm@39049
  2175
                                    let
wenzelm@39049
  2176
                                      val (s', Ts) = dest_Type T
wenzelm@39049
  2177
                                    in
wenzelm@39049
  2178
                                      if s=s' then
wenzelm@39049
  2179
                                        rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
wenzelm@39049
  2180
                                      else
wenzelm@39049
  2181
                                        raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2182
                                          "DtType/Type mismatch")
wenzelm@39049
  2183
                                    end
blanchet@58120
  2184
                                | Old_Datatype_Aux.DtRec i =>
wenzelm@39049
  2185
                                    let
wenzelm@39049
  2186
                                      val (_, ds, _) = the (AList.lookup (op =) descr i)
wenzelm@39049
  2187
                                      val (_, Ts)    = dest_Type T
wenzelm@39049
  2188
                                    in
wenzelm@39046
  2189
                                      rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
wenzelm@39049
  2190
                                    end)
wenzelm@39049
  2191
                            | SOME T' =>
wenzelm@39049
  2192
                                if T=T' then
wenzelm@39049
  2193
                                  (* ignore the association since it's already *)
wenzelm@39049
  2194
                                  (* present, proceed                          *)
wenzelm@39049
  2195
                                  rec_typ_assoc acc xs
wenzelm@39049
  2196
                                else
wenzelm@39049
  2197
                                  raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2198
                                    "different type associations for the same dtyp"))
wenzelm@39049
  2199
                      val typ_assoc = filter
blanchet@58120
  2200
                        (fn (Old_Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
wenzelm@39049
  2201
                        (rec_typ_assoc []
wenzelm@39049
  2202
                          (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
wenzelm@39049
  2203
                      (* sanity check: typ_assoc must associate types to the   *)
wenzelm@39049
  2204
                      (*               elements of 'dtyps' (and only to those) *)
wenzelm@39049
  2205
                      val _ =
wenzelm@39049
  2206
                        if not (eq_set (op =) (dtyps, map fst typ_assoc))
wenzelm@39049
  2207
                        then
wenzelm@39049
  2208
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2209
                            "type association has extra/missing elements")
wenzelm@39049
  2210
                        else ()
wenzelm@39049
  2211
                      (* interpret each constructor in the descriptor (including *)
wenzelm@39049
  2212
                      (* those of mutually recursive datatypes)                  *)
wenzelm@39049
  2213
                      (* (int * interpretation list) list *)
wenzelm@39049
  2214
                      val mc_intrs = map (fn (idx, (_, _, cs)) =>
wenzelm@39046
  2215
                        let
wenzelm@39049
  2216
                          val c_return_typ = typ_of_dtyp descr typ_assoc
blanchet@58120
  2217
                            (Old_Datatype_Aux.DtRec idx)
wenzelm@39046
  2218
                        in
wenzelm@39049
  2219
                          (idx, map (fn (cname, cargs) =>
wenzelm@39049
  2220
                            (#1 o interpret ctxt (typs, []) {maxvars=0,
wenzelm@39049
  2221
                              def_eq=false, next_idx=1, bounds=[],
wenzelm@39049
  2222
                              wellformed=True}) (Const (cname, map (typ_of_dtyp
wenzelm@39049
  2223
                              descr typ_assoc) cargs ---> c_return_typ))) cs)
wenzelm@39049
  2224
                        end) descr
wenzelm@39049
  2225
                      (* associate constructors with corresponding parameters *)
wenzelm@39049
  2226
                      (* (int * (interpretation * interpretation) list) list *)
wenzelm@39049
  2227
                      val (mc_p_intrs, p_intrs') = fold_map
wenzelm@39049
  2228
                        (fn (idx, c_intrs) => fn p_intrs' =>
wenzelm@39046
  2229
                          let
wenzelm@39049
  2230
                            val len = length c_intrs
wenzelm@39046
  2231
                          in
wenzelm@39049
  2232
                            ((idx, c_intrs ~~ List.take (p_intrs', len)),
wenzelm@39049
  2233
                              List.drop (p_intrs', len))
wenzelm@39049
  2234
                          end) mc_intrs p_intrs
wenzelm@39049
  2235
                      (* sanity check: no 'p_intr' may be left afterwards *)
wenzelm@39049
  2236
                      val _ =
wenzelm@39049
  2237
                        if p_intrs' <> [] then
webertj@25014
  2238
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2239
                            "more parameter than constructor interpretations")
wenzelm@39046
  2240
                        else ()
wenzelm@39049
  2241
                      (* The recursion operator, applied to 'mconstrs_count'     *)
wenzelm@39049
  2242
                      (* arguments, is a function that maps every element of the *)
wenzelm@39049
  2243
                      (* inductive datatype to an element of some result type.   *)
wenzelm@39049
  2244
                      (* Recursion operators for mutually recursive IDTs are     *)
wenzelm@39049
  2245
                      (* translated simultaneously.                              *)
wenzelm@39049
  2246
                      (* Since the order on datatype elements is given by an     *)
wenzelm@39049
  2247
                      (* order on constructors (and then by the order on         *)
wenzelm@39049
  2248
                      (* argument tuples), we can simply copy corresponding      *)
wenzelm@39049
  2249
                      (* subtrees from 'p_intrs', in the order in which they are *)
wenzelm@39049
  2250
                      (* given.                                                  *)
wenzelm@39049
  2251
                      fun ci_pi (Leaf xs, pi) =
wenzelm@39049
  2252
                            (* if the constructor does not match the arguments to a *)
wenzelm@39049
  2253
                            (* defined element of the IDT, the corresponding value  *)
wenzelm@39049
  2254
                            (* of the parameter must be ignored                     *)
wenzelm@39049
  2255
                            if List.exists (equal True) xs then [pi] else []
wenzelm@39049
  2256
                        | ci_pi (Node xs, Node ys) = maps ci_pi (xs ~~ ys)
wenzelm@39049
  2257
                        | ci_pi (Node _, Leaf _) =
wenzelm@39049
  2258
                            raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2259
                              "constructor takes more arguments than the " ^
wenzelm@39049
  2260
                                "associated parameter")
wenzelm@39049
  2261
                      val rec_operators = map (fn (idx, c_p_intrs) =>
wenzelm@39049
  2262
                        (idx, maps ci_pi c_p_intrs)) mc_p_intrs
wenzelm@39049
  2263
                      (* sanity check: every recursion operator must provide as  *)
wenzelm@39049
  2264
                      (*               many values as the corresponding datatype *)
wenzelm@39049
  2265
                      (*               has elements                              *)
wenzelm@39049
  2266
                      val _ = map (fn (idx, intrs) =>
wenzelm@39049
  2267
                        let
wenzelm@39049
  2268
                          val T = typ_of_dtyp descr typ_assoc
blanchet@58120
  2269
                            (Old_Datatype_Aux.DtRec idx)
wenzelm@39049
  2270
                        in
wenzelm@39049
  2271
                          if length intrs <> size_of_type ctxt (typs, []) T then
wenzelm@39049
  2272
                            raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2273
                              "wrong number of interpretations for rec. operator")
wenzelm@39049
  2274
                          else ()