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