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