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