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