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