src/HOL/Library/refute.ML
author blanchet
Mon Sep 01 17:34:03 2014 +0200 (2014-09-01)
changeset 58129 3ec65a7f2b50
parent 58120 a14b8d77b15a
child 58322 f13f6e27d68e
permissions -rw-r--r--
ported Refute to use new datatypes when possible
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@58120
   370
fun typ_of_dtyp _ typ_assoc (Old_Datatype_Aux.DtTFree a) =
blanchet@58120
   371
    the (AList.lookup (op =) typ_assoc (Old_Datatype_Aux.DtTFree a))
blanchet@58120
   372
  | typ_of_dtyp descr typ_assoc (Old_Datatype_Aux.DtType (s, Us)) =
blanchet@55891
   373
    Type (s, map (typ_of_dtyp descr typ_assoc) Us)
blanchet@58120
   374
  | typ_of_dtyp descr typ_assoc (Old_Datatype_Aux.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', _) =>
blanchet@58129
   405
      (case BNF_LFP_Compat.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)
blanchet@58129
   420
      (BNF_LFP_Compat.get_all thy BNF_LFP_Compat.Unfold_Nesting) []
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@29820
   578
      | Const (@{const_name fst}, _) => t
blanchet@29820
   579
      | Const (@{const_name snd}, _) => t
wenzelm@22567
   580
      (* simply-typed lambda calculus *)
wenzelm@22567
   581
      | Const (s, T) =>
wenzelm@39046
   582
          (if is_IDT_constructor thy (s, T)
wenzelm@39046
   583
            orelse is_IDT_recursor thy (s, T) then
wenzelm@39046
   584
            t  (* do not unfold IDT constructors/recursors *)
wenzelm@39046
   585
          (* unfold the constant if there is a defining equation *)
wenzelm@39046
   586
          else
wenzelm@39046
   587
            case get_def thy (s, T) of
blanchet@46096
   588
              SOME ((*axname*) _, rhs) =>
wenzelm@39046
   589
              (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
wenzelm@39046
   590
              (* occurs on the right-hand side of the equation, i.e. in  *)
wenzelm@39046
   591
              (* 'rhs', we must not use this equation to unfold, because *)
wenzelm@39046
   592
              (* that would loop.  Here would be the right place to      *)
wenzelm@39046
   593
              (* check this.  However, getting this really right seems   *)
wenzelm@39046
   594
              (* difficult because the user may state arbitrary axioms,  *)
wenzelm@39046
   595
              (* which could interact with overloading to create loops.  *)
wenzelm@39046
   596
              ((*tracing (" unfolding: " ^ axname);*)
wenzelm@39046
   597
               unfold_loop rhs)
wenzelm@39046
   598
            | NONE => t)
wenzelm@39046
   599
      | Free _ => t
wenzelm@39046
   600
      | Var _ => t
wenzelm@39046
   601
      | Bound _ => t
wenzelm@22567
   602
      | Abs (s, T, body) => Abs (s, T, unfold_loop body)
wenzelm@39046
   603
      | t1 $ t2 => (unfold_loop t1) $ (unfold_loop t2)
wenzelm@22567
   604
    val result = Envir.beta_eta_contract (unfold_loop t)
wenzelm@22567
   605
  in
wenzelm@22567
   606
    result
wenzelm@22567
   607
  end;
webertj@21985
   608
webertj@21985
   609
(* ------------------------------------------------------------------------- *)
webertj@21985
   610
(* collect_axioms: collects (monomorphic, universally quantified, unfolded   *)
webertj@21985
   611
(*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
webertj@14807
   612
(* ------------------------------------------------------------------------- *)
webertj@14807
   613
wenzelm@39046
   614
(* Note: to make the collection of axioms more easily extensible, this    *)
wenzelm@39046
   615
(*       function could be based on user-supplied "axiom collectors",     *)
wenzelm@39046
   616
(*       similar to 'interpret'/interpreters or 'print'/printers          *)
webertj@14807
   617
wenzelm@39046
   618
(* Note: currently we use "inverse" functions to the definitional         *)
wenzelm@39046
   619
(*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
wenzelm@39046
   620
(*       "typedef", "definition".  A more general approach could consider *)
wenzelm@39046
   621
(*       *every* axiom of the theory and collect it if it has a constant/ *)
wenzelm@39046
   622
(*       type/typeclass in common with the term 't'.                      *)
webertj@21985
   623
wenzelm@39046
   624
(* Which axioms are "relevant" for a particular term/type goes hand in    *)
wenzelm@39046
   625
(* hand with the interpretation of that term/type by its interpreter (see *)
wenzelm@39046
   626
(* way below): if the interpretation respects an axiom anyway, the axiom  *)
wenzelm@39046
   627
(* does not need to be added as a constraint here.                        *)
webertj@14807
   628
wenzelm@39046
   629
(* To avoid collecting the same axiom multiple times, we use an           *)
wenzelm@39046
   630
(* accumulator 'axs' which contains all axioms collected so far.          *)
webertj@14807
   631
wenzelm@56256
   632
local
wenzelm@56256
   633
wenzelm@56256
   634
fun get_axiom thy xname =
wenzelm@56256
   635
  Name_Space.check (Context.Theory thy) (Theory.axiom_table thy) (xname, Position.none);
wenzelm@56256
   636
wenzelm@56256
   637
val the_eq_trivial = get_axiom @{theory HOL} "the_eq_trivial";
wenzelm@56256
   638
val someI = get_axiom @{theory Hilbert_Choice} "someI";
wenzelm@56256
   639
wenzelm@56256
   640
in
wenzelm@56256
   641
wenzelm@39049
   642
fun collect_axioms ctxt t =
wenzelm@22567
   643
  let
wenzelm@42361
   644
    val thy = Proof_Context.theory_of ctxt
wenzelm@32950
   645
    val _ = tracing "Adding axioms..."
wenzelm@22567
   646
    fun collect_this_axiom (axname, ax) axs =
wenzelm@33246
   647
      let
wenzelm@33246
   648
        val ax' = unfold_defs thy ax
wenzelm@33246
   649
      in
wenzelm@33246
   650
        if member (op aconv) axs ax' then axs
wenzelm@33246
   651
        else (tracing axname; collect_term_axioms ax' (ax' :: axs))
wenzelm@33246
   652
      end
wenzelm@33246
   653
    and collect_sort_axioms T axs =
wenzelm@33246
   654
      let
wenzelm@33246
   655
        val sort =
wenzelm@33246
   656
          (case T of
wenzelm@33246
   657
            TFree (_, sort) => sort
wenzelm@33246
   658
          | TVar (_, sort)  => sort
wenzelm@33246
   659
          | _ => raise REFUTE ("collect_axioms",
wenzelm@39049
   660
              "type " ^ Syntax.string_of_typ ctxt T ^ " is not a variable"))
wenzelm@33246
   661
        (* obtain axioms for all superclasses *)
wenzelm@33246
   662
        val superclasses = sort @ maps (Sign.super_classes thy) sort
wenzelm@33246
   663
        (* merely an optimization, because 'collect_this_axiom' disallows *)
wenzelm@33246
   664
        (* duplicate axioms anyway:                                       *)
wenzelm@33246
   665
        val superclasses = distinct (op =) superclasses
wenzelm@33246
   666
        val class_axioms = maps (fn class => map (fn ax =>
wenzelm@33246
   667
          ("<" ^ class ^ ">", Thm.prop_of ax))
wenzelm@51685
   668
          (#axioms (Axclass.get_info thy class) handle ERROR _ => []))
wenzelm@33246
   669
          superclasses
wenzelm@33246
   670
        (* replace the (at most one) schematic type variable in each axiom *)
wenzelm@33246
   671
        (* by the actual type 'T'                                          *)
wenzelm@33246
   672
        val monomorphic_class_axioms = map (fn (axname, ax) =>
wenzelm@33246
   673
          (case Term.add_tvars ax [] of
wenzelm@33246
   674
            [] => (axname, ax)
wenzelm@33246
   675
          | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
wenzelm@33246
   676
          | _ =>
wenzelm@33246
   677
            raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
wenzelm@39049
   678
              Syntax.string_of_term ctxt ax ^
wenzelm@33246
   679
              ") contains more than one type variable")))
wenzelm@33246
   680
          class_axioms
wenzelm@33246
   681
      in
wenzelm@33246
   682
        fold collect_this_axiom monomorphic_class_axioms axs
wenzelm@33246
   683
      end
wenzelm@33246
   684
    and collect_type_axioms T axs =
wenzelm@22567
   685
      case T of
wenzelm@22567
   686
      (* simple types *)
wenzelm@56252
   687
        Type (@{type_name prop}, []) => axs
wenzelm@56252
   688
      | Type (@{type_name fun}, [T1, T2]) => collect_type_axioms T2 (collect_type_axioms T1 axs)
blanchet@46098
   689
      | Type (@{type_name set}, [T1]) => collect_type_axioms T1 axs
wenzelm@22567
   690
      (* axiomatic type classes *)
wenzelm@56252
   691
      | Type (@{type_name itself}, [T1]) => collect_type_axioms T1 axs
wenzelm@33246
   692
      | Type (s, Ts) =>
blanchet@58129
   693
        (case BNF_LFP_Compat.get_info thy BNF_LFP_Compat.Unfold_Nesting s of
blanchet@46096
   694
          SOME _ =>  (* inductive datatype *)
wenzelm@22567
   695
            (* only collect relevant type axioms for the argument types *)
wenzelm@33246
   696
            fold collect_type_axioms Ts axs
wenzelm@22567
   697
        | NONE =>
wenzelm@22567
   698
          (case get_typedef thy T of
wenzelm@22567
   699
            SOME (axname, ax) =>
wenzelm@39046
   700
              collect_this_axiom (axname, ax) axs
wenzelm@22567
   701
          | NONE =>
wenzelm@22567
   702
            (* unspecified type, perhaps introduced with "typedecl" *)
wenzelm@22567
   703
            (* at least collect relevant type axioms for the argument types *)
wenzelm@33246
   704
            fold collect_type_axioms Ts axs))
wenzelm@22567
   705
      (* axiomatic type classes *)
wenzelm@33246
   706
      | TFree _ => collect_sort_axioms T axs
wenzelm@33246
   707
      (* axiomatic type classes *)
wenzelm@33246
   708
      | TVar _ => collect_sort_axioms T axs
wenzelm@33246
   709
    and collect_term_axioms t axs =
wenzelm@22567
   710
      case t of
wenzelm@22567
   711
      (* Pure *)
wenzelm@56245
   712
        Const (@{const_name Pure.all}, _) => axs
wenzelm@56245
   713
      | Const (@{const_name Pure.eq}, _) => axs
wenzelm@56245
   714
      | Const (@{const_name Pure.imp}, _) => axs
wenzelm@22567
   715
      (* axiomatic type classes *)
wenzelm@56243
   716
      | Const (@{const_name Pure.type}, T) => collect_type_axioms T axs
wenzelm@22567
   717
      (* HOL *)
blanchet@29802
   718
      | Const (@{const_name Trueprop}, _) => axs
blanchet@29802
   719
      | Const (@{const_name Not}, _) => axs
wenzelm@22567
   720
      (* redundant, since 'True' is also an IDT constructor *)
blanchet@29802
   721
      | Const (@{const_name True}, _) => axs
wenzelm@22567
   722
      (* redundant, since 'False' is also an IDT constructor *)
blanchet@29802
   723
      | Const (@{const_name False}, _) => axs
wenzelm@33246
   724
      | Const (@{const_name undefined}, T) => collect_type_axioms T axs
blanchet@29802
   725
      | Const (@{const_name The}, T) =>
wenzelm@39046
   726
          let
wenzelm@56256
   727
            val ax = specialize_type thy (@{const_name The}, T) (#2 the_eq_trivial)
wenzelm@39046
   728
          in
wenzelm@56256
   729
            collect_this_axiom (#1 the_eq_trivial, ax) axs
wenzelm@39046
   730
          end
blanchet@29820
   731
      | Const (@{const_name Hilbert_Choice.Eps}, T) =>
wenzelm@39046
   732
          let
wenzelm@56256
   733
            val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T) (#2 someI)
wenzelm@39046
   734
          in
wenzelm@56256
   735
            collect_this_axiom (#1 someI, ax) axs
wenzelm@39046
   736
          end
wenzelm@33246
   737
      | Const (@{const_name All}, T) => collect_type_axioms T axs
wenzelm@33246
   738
      | Const (@{const_name Ex}, T) => collect_type_axioms T axs
haftmann@38864
   739
      | Const (@{const_name HOL.eq}, T) => collect_type_axioms T axs
haftmann@38795
   740
      | Const (@{const_name HOL.conj}, _) => axs
haftmann@38795
   741
      | Const (@{const_name HOL.disj}, _) => axs
haftmann@38786
   742
      | Const (@{const_name HOL.implies}, _) => axs
wenzelm@22567
   743
      (* sets *)
wenzelm@33246
   744
      | Const (@{const_name Collect}, T) => collect_type_axioms T axs
haftmann@37677
   745
      | Const (@{const_name Set.member}, T) => collect_type_axioms T axs
wenzelm@22567
   746
      (* other optimizations *)
wenzelm@33246
   747
      | Const (@{const_name Finite_Set.card}, T) => collect_type_axioms T axs
blanchet@29820
   748
      | Const (@{const_name Finite_Set.finite}, T) =>
wenzelm@33246
   749
        collect_type_axioms T axs
haftmann@37388
   750
      | Const (@{const_name Orderings.less}, T as Type ("fun", [@{typ nat},
haftmann@38553
   751
        Type ("fun", [@{typ nat}, @{typ bool}])])) =>
wenzelm@33246
   752
          collect_type_axioms T axs
haftmann@37388
   753
      | Const (@{const_name Groups.plus}, T as Type ("fun", [@{typ nat},
haftmann@37388
   754
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33246
   755
          collect_type_axioms T axs
haftmann@37388
   756
      | Const (@{const_name Groups.minus}, T as Type ("fun", [@{typ nat},
haftmann@37388
   757
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33246
   758
          collect_type_axioms T axs
haftmann@37388
   759
      | Const (@{const_name Groups.times}, T as Type ("fun", [@{typ nat},
haftmann@37388
   760
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33246
   761
          collect_type_axioms T axs
wenzelm@56252
   762
      | Const (@{const_name append}, T) => collect_type_axioms T axs
wenzelm@33246
   763
      | Const (@{const_name fst}, T) => collect_type_axioms T axs
wenzelm@33246
   764
      | Const (@{const_name snd}, T) => collect_type_axioms T axs
wenzelm@22567
   765
      (* simply-typed lambda calculus *)
blanchet@29802
   766
      | Const (s, T) =>
wenzelm@22567
   767
          if is_const_of_class thy (s, T) then
wenzelm@22567
   768
            (* axiomatic type classes: add "OFCLASS(?'a::c, c_class)" *)
wenzelm@22567
   769
            (* and the class definition                               *)
wenzelm@22567
   770
            let
wenzelm@33246
   771
              val class = Logic.class_of_const s
wenzelm@31943
   772
              val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]), class)
wenzelm@33246
   773
              val ax_in = SOME (specialize_type thy (s, T) of_class)
wenzelm@22567
   774
                (* type match may fail due to sort constraints *)
wenzelm@22567
   775
                handle Type.TYPE_MATCH => NONE
wenzelm@39049
   776
              val ax_1 = Option.map (fn ax => (Syntax.string_of_term ctxt ax, ax)) ax_in
wenzelm@33246
   777
              val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
wenzelm@22567
   778
            in
wenzelm@33246
   779
              collect_type_axioms T (fold collect_this_axiom (map_filter I [ax_1, ax_2]) axs)
wenzelm@22567
   780
            end
wenzelm@22567
   781
          else if is_IDT_constructor thy (s, T)
wenzelm@39049
   782
            orelse is_IDT_recursor thy (s, T)
wenzelm@39049
   783
          then
wenzelm@22567
   784
            (* only collect relevant type axioms *)
wenzelm@33246
   785
            collect_type_axioms T axs
wenzelm@22567
   786
          else
wenzelm@22567
   787
            (* other constants should have been unfolded, with some *)
wenzelm@22567
   788
            (* exceptions: e.g. Abs_xxx/Rep_xxx functions for       *)
wenzelm@22567
   789
            (* typedefs, or type-class related constants            *)
wenzelm@22567
   790
            (* only collect relevant type axioms *)
wenzelm@33246
   791
            collect_type_axioms T axs
wenzelm@33246
   792
      | Free (_, T) => collect_type_axioms T axs
wenzelm@33246
   793
      | Var (_, T) => collect_type_axioms T axs
wenzelm@33246
   794
      | Bound _ => axs
wenzelm@33246
   795
      | Abs (_, T, body) => collect_term_axioms body (collect_type_axioms T axs)
wenzelm@33246
   796
      | t1 $ t2 => collect_term_axioms t2 (collect_term_axioms t1 axs)
wenzelm@33246
   797
    val result = map close_form (collect_term_axioms t [])
wenzelm@32950
   798
    val _ = tracing " ...done."
wenzelm@22567
   799
  in
wenzelm@22567
   800
    result
wenzelm@22567
   801
  end;
webertj@14456
   802
wenzelm@56256
   803
end;
wenzelm@56256
   804
webertj@14456
   805
(* ------------------------------------------------------------------------- *)
webertj@14807
   806
(* ground_types: collects all ground types in a term (including argument     *)
webertj@14807
   807
(*               types of other types), suppressing duplicates.  Does not    *)
webertj@14807
   808
(*               return function types, set types, non-recursive IDTs, or    *)
webertj@14807
   809
(*               'propT'.  For IDTs, also the argument types of constructors *)
webertj@25014
   810
(*               and all mutually recursive IDTs are considered.             *)
webertj@14807
   811
(* ------------------------------------------------------------------------- *)
webertj@14807
   812
wenzelm@39049
   813
fun ground_types ctxt t =
wenzelm@22567
   814
  let
wenzelm@42361
   815
    val thy = Proof_Context.theory_of ctxt
wenzelm@29272
   816
    fun collect_types T acc =
webertj@25014
   817
      (case T of
wenzelm@56252
   818
        Type (@{type_name fun}, [T1, T2]) => collect_types T1 (collect_types T2 acc)
wenzelm@56252
   819
      | Type (@{type_name prop}, []) => acc
blanchet@46098
   820
      | Type (@{type_name set}, [T1]) => collect_types T1 acc
wenzelm@39046
   821
      | Type (s, Ts) =>
blanchet@58129
   822
          (case BNF_LFP_Compat.get_info thy BNF_LFP_Compat.Unfold_Nesting s of
wenzelm@39046
   823
            SOME info =>  (* inductive datatype *)
wenzelm@39046
   824
              let
wenzelm@39046
   825
                val index = #index info
wenzelm@39046
   826
                val descr = #descr info
wenzelm@39046
   827
                val (_, typs, _) = the (AList.lookup (op =) descr index)
wenzelm@39046
   828
                val typ_assoc = typs ~~ Ts
wenzelm@39046
   829
                (* sanity check: every element in 'dtyps' must be a *)
wenzelm@39046
   830
                (* 'DtTFree'                                        *)
wenzelm@39046
   831
                val _ = if Library.exists (fn d =>
blanchet@58120
   832
                  case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) typs then
wenzelm@39046
   833
                  raise REFUTE ("ground_types", "datatype argument (for type "
wenzelm@39049
   834
                    ^ Syntax.string_of_typ ctxt T ^ ") is not a variable")
wenzelm@39046
   835
                else ()
wenzelm@39046
   836
                (* required for mutually recursive datatypes; those need to   *)
wenzelm@39046
   837
                (* be added even if they are an instance of an otherwise non- *)
wenzelm@39046
   838
                (* recursive datatype                                         *)
wenzelm@39046
   839
                fun collect_dtyp d acc =
webertj@25014
   840
                  let
wenzelm@39046
   841
                    val dT = typ_of_dtyp descr typ_assoc d
webertj@25014
   842
                  in
wenzelm@39046
   843
                    case d of
blanchet@58120
   844
                      Old_Datatype_Aux.DtTFree _ =>
wenzelm@39046
   845
                      collect_types dT acc
blanchet@58120
   846
                    | Old_Datatype_Aux.DtType (_, ds) =>
wenzelm@39046
   847
                      collect_types dT (fold_rev collect_dtyp ds acc)
blanchet@58120
   848
                    | Old_Datatype_Aux.DtRec i =>
wenzelm@39046
   849
                      if member (op =) acc dT then
wenzelm@39046
   850
                        acc  (* prevent infinite recursion *)
wenzelm@39046
   851
                      else
wenzelm@39046
   852
                        let
wenzelm@39046
   853
                          val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
wenzelm@39046
   854
                          (* if the current type is a recursive IDT (i.e. a depth *)
wenzelm@39046
   855
                          (* is required), add it to 'acc'                        *)
wenzelm@39046
   856
                          val acc_dT = if Library.exists (fn (_, ds) =>
blanchet@58120
   857
                            Library.exists Old_Datatype_Aux.is_rec_type ds) dconstrs then
wenzelm@39046
   858
                              insert (op =) dT acc
wenzelm@39046
   859
                            else acc
wenzelm@39046
   860
                          (* collect argument types *)
wenzelm@39046
   861
                          val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
wenzelm@39046
   862
                          (* collect constructor types *)
wenzelm@39046
   863
                          val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
wenzelm@39046
   864
                        in
wenzelm@39046
   865
                          acc_dconstrs
wenzelm@39046
   866
                        end
webertj@25014
   867
                  end
wenzelm@39046
   868
              in
wenzelm@39046
   869
                (* argument types 'Ts' could be added here, but they are also *)
wenzelm@39046
   870
                (* added by 'collect_dtyp' automatically                      *)
blanchet@58120
   871
                collect_dtyp (Old_Datatype_Aux.DtRec index) acc
wenzelm@39046
   872
              end
wenzelm@39046
   873
          | NONE =>
wenzelm@39046
   874
            (* not an inductive datatype, e.g. defined via "typedef" or *)
wenzelm@39046
   875
            (* "typedecl"                                               *)
wenzelm@39046
   876
            insert (op =) T (fold collect_types Ts acc))
wenzelm@39046
   877
      | TFree _ => insert (op =) T acc
wenzelm@39046
   878
      | TVar _ => insert (op =) T acc)
wenzelm@22567
   879
  in
wenzelm@29272
   880
    fold_types collect_types t []
wenzelm@22567
   881
  end;
webertj@14807
   882
webertj@14807
   883
(* ------------------------------------------------------------------------- *)
webertj@14807
   884
(* string_of_typ: (rather naive) conversion from types to strings, used to   *)
webertj@14807
   885
(*                look up the size of a type in 'sizes'.  Parameterized      *)
webertj@14807
   886
(*                types with different parameters (e.g. "'a list" vs. "bool  *)
webertj@14807
   887
(*                list") are identified.                                     *)
webertj@14807
   888
(* ------------------------------------------------------------------------- *)
webertj@14807
   889
wenzelm@39046
   890
fun string_of_typ (Type (s, _))     = s
wenzelm@39046
   891
  | string_of_typ (TFree (s, _))    = s
wenzelm@39046
   892
  | string_of_typ (TVar ((s,_), _)) = s;
webertj@14807
   893
webertj@14807
   894
(* ------------------------------------------------------------------------- *)
webertj@14807
   895
(* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
webertj@14807
   896
(*                 'minsize' to every type for which no size is specified in *)
webertj@14807
   897
(*                 'sizes'                                                   *)
webertj@14807
   898
(* ------------------------------------------------------------------------- *)
webertj@14807
   899
wenzelm@39046
   900
fun first_universe xs sizes minsize =
wenzelm@22567
   901
  let
wenzelm@22567
   902
    fun size_of_typ T =
wenzelm@22567
   903
      case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@22567
   904
        SOME n => n
wenzelm@33246
   905
      | NONE => minsize
wenzelm@22567
   906
  in
wenzelm@22567
   907
    map (fn T => (T, size_of_typ T)) xs
wenzelm@22567
   908
  end;
webertj@14807
   909
webertj@14807
   910
(* ------------------------------------------------------------------------- *)
webertj@14807
   911
(* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
webertj@14807
   912
(*                types), where the minimal size of a type is given by       *)
webertj@14807
   913
(*                'minsize', the maximal size is given by 'maxsize', and a   *)
webertj@14807
   914
(*                type may have a fixed size given in 'sizes'                *)
webertj@14456
   915
(* ------------------------------------------------------------------------- *)
webertj@14456
   916
wenzelm@39046
   917
fun next_universe xs sizes minsize maxsize =
wenzelm@22567
   918
  let
wenzelm@22567
   919
    (* creates the "first" list of length 'len', where the sum of all list *)
wenzelm@22567
   920
    (* elements is 'sum', and the length of the list is 'len'              *)
wenzelm@22567
   921
    fun make_first _ 0 sum =
wenzelm@39046
   922
          if sum = 0 then
wenzelm@39046
   923
            SOME []
wenzelm@39046
   924
          else
wenzelm@39046
   925
            NONE
wenzelm@22567
   926
      | make_first max len sum =
wenzelm@39046
   927
          if sum <= max orelse max < 0 then
wenzelm@39046
   928
            Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
wenzelm@39046
   929
          else
wenzelm@39046
   930
            Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
wenzelm@22567
   931
    (* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
wenzelm@22567
   932
    (* all list elements x (unless 'max'<0)                                *)
blanchet@46096
   933
    fun next _ _ _ [] =
wenzelm@39046
   934
          NONE
wenzelm@22567
   935
      | next max len sum [x] =
wenzelm@39046
   936
          (* we've reached the last list element, so there's no shift possible *)
wenzelm@39046
   937
          make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
wenzelm@22567
   938
      | next max len sum (x1::x2::xs) =
wenzelm@39046
   939
          if x1>0 andalso (x2<max orelse max<0) then
wenzelm@39046
   940
            (* we can shift *)
wenzelm@39046
   941
            SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
wenzelm@39046
   942
          else
wenzelm@39046
   943
            (* continue search *)
wenzelm@39046
   944
            next max (len+1) (sum+x1) (x2::xs)
wenzelm@22567
   945
    (* only consider those types for which the size is not fixed *)
wenzelm@33317
   946
    val mutables = filter_out (AList.defined (op =) sizes o string_of_typ o fst) xs
wenzelm@22567
   947
    (* subtract 'minsize' from every size (will be added again at the end) *)
wenzelm@22567
   948
    val diffs = map (fn (_, n) => n-minsize) mutables
wenzelm@22567
   949
  in
wenzelm@22567
   950
    case next (maxsize-minsize) 0 0 diffs of
wenzelm@22567
   951
      SOME diffs' =>
wenzelm@39046
   952
        (* merge with those types for which the size is fixed *)
wenzelm@39046
   953
        SOME (fst (fold_map (fn (T, _) => fn ds =>
wenzelm@39046
   954
          case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@39046
   955
          (* return the fixed size *)
wenzelm@39046
   956
            SOME n => ((T, n), ds)
wenzelm@39046
   957
          (* consume the head of 'ds', add 'minsize' *)
wenzelm@39046
   958
          | NONE   => ((T, minsize + hd ds), tl ds))
wenzelm@39046
   959
          xs diffs'))
wenzelm@39046
   960
    | NONE => NONE
wenzelm@22567
   961
  end;
webertj@14807
   962
webertj@14807
   963
(* ------------------------------------------------------------------------- *)
webertj@14807
   964
(* toTrue: converts the interpretation of a Boolean value to a propositional *)
webertj@14807
   965
(*         formula that is true iff the interpretation denotes "true"        *)
webertj@14807
   966
(* ------------------------------------------------------------------------- *)
webertj@14807
   967
wenzelm@39046
   968
fun toTrue (Leaf [fm, _]) = fm
wenzelm@39046
   969
  | toTrue _ = raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
webertj@14807
   970
webertj@14807
   971
(* ------------------------------------------------------------------------- *)
webertj@14807
   972
(* toFalse: converts the interpretation of a Boolean value to a              *)
webertj@14807
   973
(*          propositional formula that is true iff the interpretation        *)
webertj@14807
   974
(*          denotes "false"                                                  *)
webertj@14807
   975
(* ------------------------------------------------------------------------- *)
webertj@14807
   976
wenzelm@39046
   977
fun toFalse (Leaf [_, fm]) = fm
wenzelm@39046
   978
  | toFalse _ = raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
webertj@14807
   979
webertj@14807
   980
(* ------------------------------------------------------------------------- *)
webertj@14807
   981
(* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
webertj@14807
   982
(*             applies a SAT solver, and (in case a model is found) displays *)
webertj@14807
   983
(*             the model to the user by calling 'print_model'                *)
webertj@14807
   984
(* {...}     : parameters that control the translation/model generation      *)
blanchet@34120
   985
(* assm_ts   : assumptions to be considered unless "no_assms" is specified   *)
webertj@14807
   986
(* t         : term to be translated into a propositional formula            *)
webertj@14807
   987
(* negate    : if true, find a model that makes 't' false (rather than true) *)
webertj@14807
   988
(* ------------------------------------------------------------------------- *)
webertj@14807
   989
wenzelm@39049
   990
fun find_model ctxt
wenzelm@39046
   991
    {sizes, minsize, maxsize, maxvars, maxtime, satsolver, no_assms, expect}
wenzelm@39046
   992
    assm_ts t negate =
wenzelm@22567
   993
  let
wenzelm@42361
   994
    val thy = Proof_Context.theory_of ctxt
blanchet@33054
   995
    fun check_expect outcome_code =
blanchet@45387
   996
      if expect = "" orelse outcome_code = expect then outcome_code
blanchet@33054
   997
      else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
wenzelm@22567
   998
    fun wrapper () =
wenzelm@22567
   999
      let
wenzelm@39046
  1000
        val timer = Timer.startRealTimer ()
wenzelm@39046
  1001
        val t =
wenzelm@39046
  1002
          if no_assms then t
wenzelm@39046
  1003
          else if negate then Logic.list_implies (assm_ts, t)
wenzelm@39046
  1004
          else Logic.mk_conjunction_list (t :: assm_ts)
wenzelm@39046
  1005
        val u = unfold_defs thy t
wenzelm@39049
  1006
        val _ = tracing ("Unfolded term: " ^ Syntax.string_of_term ctxt u)
wenzelm@39049
  1007
        val axioms = collect_axioms ctxt u
wenzelm@39049
  1008
        val types = fold (union (op =) o ground_types ctxt) (u :: axioms) []
wenzelm@39046
  1009
        val _ = tracing ("Ground types: "
wenzelm@39046
  1010
          ^ (if null types then "none."
wenzelm@39049
  1011
             else commas (map (Syntax.string_of_typ ctxt) types)))
wenzelm@39046
  1012
        (* we can only consider fragments of recursive IDTs, so we issue a  *)
wenzelm@39046
  1013
        (* warning if the formula contains a recursive IDT                  *)
wenzelm@39046
  1014
        (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
wenzelm@39046
  1015
        val maybe_spurious = Library.exists (fn
wenzelm@39046
  1016
            Type (s, _) =>
blanchet@58129
  1017
              (case BNF_LFP_Compat.get_info thy BNF_LFP_Compat.Unfold_Nesting s of
wenzelm@39046
  1018
                SOME info =>  (* inductive datatype *)
wenzelm@39046
  1019
                  let
wenzelm@39046
  1020
                    val index           = #index info
wenzelm@39046
  1021
                    val descr           = #descr info
wenzelm@39046
  1022
                    val (_, _, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1023
                  in
wenzelm@39046
  1024
                    (* recursive datatype? *)
wenzelm@39046
  1025
                    Library.exists (fn (_, ds) =>
blanchet@58120
  1026
                      Library.exists Old_Datatype_Aux.is_rec_type ds) constrs
wenzelm@39046
  1027
                  end
wenzelm@39046
  1028
              | NONE => false)
wenzelm@39046
  1029
          | _ => false) types
wenzelm@39046
  1030
        val _ =
wenzelm@39046
  1031
          if maybe_spurious then
wenzelm@39046
  1032
            warning ("Term contains a recursive datatype; "
wenzelm@39046
  1033
              ^ "countermodel(s) may be spurious!")
wenzelm@39046
  1034
          else
wenzelm@39046
  1035
            ()
wenzelm@39046
  1036
        fun find_model_loop universe =
wenzelm@22567
  1037
          let
wenzelm@39046
  1038
            val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
wenzelm@39046
  1039
            val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
wenzelm@39046
  1040
                    orelse raise TimeLimit.TimeOut
wenzelm@39046
  1041
            val init_model = (universe, [])
wenzelm@39046
  1042
            val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
wenzelm@39046
  1043
              bounds = [], wellformed = True}
wenzelm@39046
  1044
            val _ = tracing ("Translating term (sizes: "
wenzelm@39046
  1045
              ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
wenzelm@39046
  1046
            (* translate 'u' and all axioms *)
wenzelm@39046
  1047
            val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
wenzelm@39046
  1048
              let
wenzelm@39049
  1049
                val (i, m', a') = interpret ctxt m a t'
wenzelm@39046
  1050
              in
wenzelm@39046
  1051
                (* set 'def_eq' to 'true' *)
wenzelm@39046
  1052
                (i, (m', {maxvars = #maxvars a', def_eq = true,
wenzelm@39046
  1053
                  next_idx = #next_idx a', bounds = #bounds a',
wenzelm@39046
  1054
                  wellformed = #wellformed a'}))
wenzelm@39046
  1055
              end) (u :: axioms) (init_model, init_args)
wenzelm@39046
  1056
            (* make 'u' either true or false, and make all axioms true, and *)
wenzelm@39046
  1057
            (* add the well-formedness side condition                       *)
wenzelm@39046
  1058
            val fm_u = (if negate then toFalse else toTrue) (hd intrs)
wenzelm@41471
  1059
            val fm_ax = Prop_Logic.all (map toTrue (tl intrs))
wenzelm@41471
  1060
            val fm = Prop_Logic.all [#wellformed args, fm_ax, fm_u]
wenzelm@39046
  1061
            val _ =
blanchet@56851
  1062
              (if member (op =) ["cdclite"] satsolver then
wenzelm@39046
  1063
                warning ("Using SAT solver " ^ quote satsolver ^
wenzelm@39046
  1064
                         "; for better performance, consider installing an \
wenzelm@39046
  1065
                         \external solver.")
wenzelm@39046
  1066
               else ());
wenzelm@39046
  1067
            val solver =
blanchet@56853
  1068
              SAT_Solver.invoke_solver satsolver
wenzelm@39046
  1069
              handle Option.Option =>
wenzelm@39046
  1070
                     error ("Unknown SAT solver: " ^ quote satsolver ^
wenzelm@39046
  1071
                            ". Available solvers: " ^
blanchet@56853
  1072
                            commas (map (quote o fst) (SAT_Solver.get_solvers ())) ^ ".")
wenzelm@22567
  1073
          in
wenzelm@40132
  1074
            Output.urgent_message "Invoking SAT solver...";
wenzelm@39046
  1075
            (case solver fm of
blanchet@56853
  1076
              SAT_Solver.SATISFIABLE assignment =>
krauss@42137
  1077
                (Output.urgent_message ("Model found:\n" ^ print_model ctxt model
wenzelm@39046
  1078
                  (fn i => case assignment i of SOME b => b | NONE => true));
wenzelm@39046
  1079
                 if maybe_spurious then "potential" else "genuine")
blanchet@56853
  1080
            | SAT_Solver.UNSATISFIABLE _ =>
wenzelm@40132
  1081
                (Output.urgent_message "No model exists.";
wenzelm@39046
  1082
                case next_universe universe sizes minsize maxsize of
wenzelm@39046
  1083
                  SOME universe' => find_model_loop universe'
wenzelm@40132
  1084
                | NONE => (Output.urgent_message
wenzelm@40132
  1085
                    "Search terminated, no larger universe within the given limits.";
wenzelm@40132
  1086
                    "none"))
blanchet@56853
  1087
            | SAT_Solver.UNKNOWN =>
wenzelm@40132
  1088
                (Output.urgent_message "No model found.";
wenzelm@39046
  1089
                case next_universe universe sizes minsize maxsize of
wenzelm@39046
  1090
                  SOME universe' => find_model_loop universe'
wenzelm@40132
  1091
                | NONE => (Output.urgent_message
wenzelm@39046
  1092
                  "Search terminated, no larger universe within the given limits.";
blanchet@56853
  1093
                  "unknown"))) handle SAT_Solver.NOT_CONFIGURED =>
wenzelm@39046
  1094
              (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
wenzelm@39046
  1095
               "unknown")
wenzelm@39046
  1096
          end
wenzelm@39046
  1097
          handle MAXVARS_EXCEEDED =>
wenzelm@40132
  1098
            (Output.urgent_message ("Search terminated, number of Boolean variables ("
wenzelm@39046
  1099
              ^ string_of_int maxvars ^ " allowed) exceeded.");
wenzelm@39046
  1100
              "unknown")
wenzelm@39046
  1101
blanchet@30314
  1102
        val outcome_code = find_model_loop (first_universe types sizes minsize)
wenzelm@22567
  1103
      in
blanchet@33054
  1104
        check_expect outcome_code
wenzelm@22567
  1105
      end
wenzelm@39046
  1106
  in
wenzelm@39046
  1107
    (* some parameter sanity checks *)
wenzelm@39046
  1108
    minsize>=1 orelse
wenzelm@39046
  1109
      error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
wenzelm@39046
  1110
    maxsize>=1 orelse
wenzelm@39046
  1111
      error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
wenzelm@39046
  1112
    maxsize>=minsize orelse
wenzelm@39046
  1113
      error ("\"maxsize\" (=" ^ string_of_int maxsize ^
wenzelm@39046
  1114
      ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
wenzelm@39046
  1115
    maxvars>=0 orelse
wenzelm@39046
  1116
      error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
wenzelm@39046
  1117
    maxtime>=0 orelse
wenzelm@39046
  1118
      error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
wenzelm@39046
  1119
    (* enter loop with or without time limit *)
wenzelm@40132
  1120
    Output.urgent_message ("Trying to find a model that "
wenzelm@39046
  1121
      ^ (if negate then "refutes" else "satisfies") ^ ": "
wenzelm@39049
  1122
      ^ Syntax.string_of_term ctxt t);
wenzelm@39046
  1123
    if maxtime > 0 then (
wenzelm@39046
  1124
      TimeLimit.timeLimit (Time.fromSeconds maxtime)
wenzelm@22567
  1125
        wrapper ()
wenzelm@39046
  1126
      handle TimeLimit.TimeOut =>
wenzelm@40132
  1127
        (Output.urgent_message ("Search terminated, time limit (" ^
wenzelm@39046
  1128
            string_of_int maxtime
wenzelm@39046
  1129
            ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
wenzelm@39046
  1130
         check_expect "unknown")
wenzelm@39046
  1131
    ) else wrapper ()
wenzelm@39046
  1132
  end;
webertj@14456
  1133
webertj@14456
  1134
webertj@14456
  1135
(* ------------------------------------------------------------------------- *)
webertj@14456
  1136
(* INTERFACE, PART 2: FINDING A MODEL                                        *)
webertj@14350
  1137
(* ------------------------------------------------------------------------- *)
webertj@14350
  1138
webertj@14350
  1139
(* ------------------------------------------------------------------------- *)
webertj@14456
  1140
(* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
webertj@14456
  1141
(* params      : list of '(name, value)' pairs used to override default      *)
webertj@14456
  1142
(*               parameters                                                  *)
webertj@14350
  1143
(* ------------------------------------------------------------------------- *)
webertj@14350
  1144
wenzelm@39049
  1145
fun satisfy_term ctxt params assm_ts t =
wenzelm@39049
  1146
  find_model ctxt (actual_params ctxt params) assm_ts t false;
webertj@14350
  1147
webertj@14350
  1148
(* ------------------------------------------------------------------------- *)
webertj@14456
  1149
(* refute_term: calls 'find_model' to find a model that refutes '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 refute_term ctxt params assm_ts t =
wenzelm@22567
  1155
  let
wenzelm@22567
  1156
    (* disallow schematic type variables, since we cannot properly negate  *)
wenzelm@22567
  1157
    (* terms containing them (their logical meaning is that there EXISTS a *)
wenzelm@22567
  1158
    (* type s.t. ...; to refute such a formula, we would have to show that *)
wenzelm@22567
  1159
    (* for ALL types, not ...)                                             *)
wenzelm@29272
  1160
    val _ = null (Term.add_tvars t []) orelse
wenzelm@22567
  1161
      error "Term to be refuted contains schematic type variables"
webertj@21556
  1162
wenzelm@22567
  1163
    (* existential closure over schematic variables *)
wenzelm@45741
  1164
    val vars = sort_wrt (fst o fst) (Term.add_vars t [])
wenzelm@22567
  1165
    (* Term.term *)
wenzelm@33246
  1166
    val ex_closure = fold (fn ((x, i), T) => fn t' =>
wenzelm@33246
  1167
      HOLogic.exists_const T $
wenzelm@33246
  1168
        Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
wenzelm@22567
  1169
    (* Note: If 't' is of type 'propT' (rather than 'boolT'), applying   *)
wenzelm@22567
  1170
    (* 'HOLogic.exists_const' is not type-correct.  However, this is not *)
wenzelm@22567
  1171
    (* really a problem as long as 'find_model' still interprets the     *)
wenzelm@22567
  1172
    (* resulting term correctly, without checking its type.              *)
webertj@21556
  1173
wenzelm@22567
  1174
    (* replace outermost universally quantified variables by Free's:     *)
wenzelm@22567
  1175
    (* refuting a term with Free's is generally faster than refuting a   *)
wenzelm@22567
  1176
    (* term with (nested) quantifiers, because quantifiers are expanded, *)
wenzelm@22567
  1177
    (* while the SAT solver searches for an interpretation for Free's.   *)
wenzelm@22567
  1178
    (* Also we get more information back that way, namely an             *)
wenzelm@22567
  1179
    (* interpretation which includes values for the (formerly)           *)
wenzelm@22567
  1180
    (* quantified variables.                                             *)
wenzelm@22567
  1181
    (* maps  !!x1...xn. !xk...xm. t   to   t  *)
wenzelm@56245
  1182
    fun strip_all_body (Const (@{const_name Pure.all}, _) $ Abs (_, _, t)) =
wenzelm@39046
  1183
          strip_all_body t
blanchet@29820
  1184
      | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@39046
  1185
          strip_all_body t
blanchet@29820
  1186
      | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
wenzelm@39046
  1187
          strip_all_body t
blanchet@29802
  1188
      | strip_all_body t = t
wenzelm@22567
  1189
    (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
wenzelm@56245
  1190
    fun strip_all_vars (Const (@{const_name Pure.all}, _) $ Abs (a, T, t)) =
wenzelm@39046
  1191
          (a, T) :: strip_all_vars t
blanchet@29802
  1192
      | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@39046
  1193
          strip_all_vars t
blanchet@29802
  1194
      | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
wenzelm@39046
  1195
          (a, T) :: strip_all_vars t
blanchet@46096
  1196
      | strip_all_vars _ = [] : (string * typ) list
wenzelm@22567
  1197
    val strip_t = strip_all_body ex_closure
wenzelm@39046
  1198
    val frees = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
wenzelm@22567
  1199
    val subst_t = Term.subst_bounds (map Free frees, strip_t)
wenzelm@22567
  1200
  in
wenzelm@39049
  1201
    find_model ctxt (actual_params ctxt params) assm_ts subst_t true
wenzelm@22567
  1202
  end;
webertj@14350
  1203
webertj@14350
  1204
(* ------------------------------------------------------------------------- *)
wenzelm@32857
  1205
(* refute_goal                                                               *)
webertj@14350
  1206
(* ------------------------------------------------------------------------- *)
webertj@14350
  1207
wenzelm@39046
  1208
fun refute_goal ctxt params th i =
blanchet@34120
  1209
  let
blanchet@34120
  1210
    val t = th |> prop_of
blanchet@34120
  1211
  in
blanchet@34120
  1212
    if Logic.count_prems t = 0 then
blanchet@45387
  1213
      (Output.urgent_message "No subgoal!"; "none")
blanchet@34120
  1214
    else
blanchet@34120
  1215
      let
blanchet@34120
  1216
        val assms = map term_of (Assumption.all_assms_of ctxt)
blanchet@34120
  1217
        val (t, frees) = Logic.goal_params t i
blanchet@34120
  1218
      in
wenzelm@39049
  1219
        refute_term ctxt params assms (subst_bounds (frees, t))
blanchet@34120
  1220
      end
blanchet@34120
  1221
  end
webertj@14350
  1222
webertj@14350
  1223
webertj@14350
  1224
(* ------------------------------------------------------------------------- *)
webertj@15292
  1225
(* INTERPRETERS: Auxiliary Functions                                         *)
webertj@14350
  1226
(* ------------------------------------------------------------------------- *)
webertj@14350
  1227
webertj@14350
  1228
(* ------------------------------------------------------------------------- *)
webertj@25014
  1229
(* make_constants: returns all interpretations for type 'T' that consist of  *)
webertj@25014
  1230
(*                 unit vectors with 'True'/'False' only (no Boolean         *)
webertj@25014
  1231
(*                 variables)                                                *)
webertj@14350
  1232
(* ------------------------------------------------------------------------- *)
webertj@14350
  1233
wenzelm@39049
  1234
fun make_constants ctxt model T =
wenzelm@22567
  1235
  let
wenzelm@22567
  1236
    (* returns a list with all unit vectors of length n *)
wenzelm@22567
  1237
    fun unit_vectors n =
wenzelm@39046
  1238
      let
wenzelm@39046
  1239
        (* returns the k-th unit vector of length n *)
wenzelm@39046
  1240
        fun unit_vector (k, n) =
wenzelm@39046
  1241
          Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
wenzelm@39046
  1242
        fun unit_vectors_loop k =
wenzelm@39046
  1243
          if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
wenzelm@39046
  1244
      in
wenzelm@39046
  1245
        unit_vectors_loop 1
wenzelm@39046
  1246
      end
wenzelm@22567
  1247
    (* returns a list of lists, each one consisting of n (possibly *)
wenzelm@22567
  1248
    (* identical) elements from 'xs'                               *)
wenzelm@39046
  1249
    fun pick_all 1 xs = map single xs
wenzelm@22567
  1250
      | pick_all n xs =
wenzelm@39046
  1251
          let val rec_pick = pick_all (n - 1) xs in
wenzelm@39046
  1252
            maps (fn x => map (cons x) rec_pick) xs
wenzelm@39046
  1253
          end
webertj@25014
  1254
    (* returns all constant interpretations that have the same tree *)
webertj@25014
  1255
    (* structure as the interpretation argument                     *)
webertj@25014
  1256
    fun make_constants_intr (Leaf xs) = unit_vectors (length xs)
webertj@25014
  1257
      | make_constants_intr (Node xs) = map Node (pick_all (length xs)
wenzelm@39046
  1258
          (make_constants_intr (hd xs)))
webertj@25014
  1259
    (* obtain the interpretation for a variable of type 'T' *)
wenzelm@39049
  1260
    val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1261
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1262
  in
webertj@25014
  1263
    make_constants_intr i
wenzelm@22567
  1264
  end;
webertj@14807
  1265
webertj@14807
  1266
(* ------------------------------------------------------------------------- *)
webertj@25014
  1267
(* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
webertj@25014
  1268
(*               (make_constants T)', but implemented more efficiently)      *)
webertj@14807
  1269
(* ------------------------------------------------------------------------- *)
webertj@14807
  1270
wenzelm@39046
  1271
(* returns 0 for an empty ground type or a function type with empty      *)
wenzelm@39046
  1272
(* codomain, but fails for a function type with empty domain --          *)
wenzelm@39046
  1273
(* admissibility of datatype constructor argument types (see "Inductive  *)
wenzelm@39046
  1274
(* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
wenzelm@39046
  1275
(* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
wenzelm@39046
  1276
(* never occur as the domain of a function type that is the type of a    *)
wenzelm@39046
  1277
(* constructor argument                                                  *)
webertj@25014
  1278
wenzelm@39049
  1279
fun size_of_type ctxt model T =
wenzelm@22567
  1280
  let
webertj@25014
  1281
    (* returns the number of elements that have the same tree structure as a *)
webertj@25014
  1282
    (* given interpretation                                                  *)
webertj@25014
  1283
    fun size_of_intr (Leaf xs) = length xs
wenzelm@39047
  1284
      | size_of_intr (Node xs) = Integer.pow (length xs) (size_of_intr (hd xs))
webertj@25014
  1285
    (* obtain the interpretation for a variable of type 'T' *)
wenzelm@39049
  1286
    val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1287
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1288
  in
webertj@25014
  1289
    size_of_intr i
wenzelm@22567
  1290
  end;
webertj@14807
  1291
webertj@14807
  1292
(* ------------------------------------------------------------------------- *)
webertj@14807
  1293
(* TT/FF: interpretations that denote "true" or "false", respectively        *)
webertj@14807
  1294
(* ------------------------------------------------------------------------- *)
webertj@14807
  1295
wenzelm@39046
  1296
val TT = Leaf [True, False];
webertj@14807
  1297
wenzelm@39046
  1298
val FF = Leaf [False, True];
webertj@14807
  1299
webertj@14807
  1300
(* ------------------------------------------------------------------------- *)
webertj@14807
  1301
(* make_equality: returns an interpretation that denotes (extensional)       *)
webertj@14807
  1302
(*                equality of two interpretations                            *)
webertj@15547
  1303
(* - two interpretations are 'equal' iff they are both defined and denote    *)
webertj@15547
  1304
(*   the same value                                                          *)
webertj@15547
  1305
(* - two interpretations are 'not_equal' iff they are both defined at least  *)
webertj@15547
  1306
(*   partially, and a defined part denotes different values                  *)
webertj@15547
  1307
(* - a completely undefined interpretation is neither 'equal' nor            *)
webertj@15547
  1308
(*   'not_equal' to another interpretation                                   *)
webertj@14807
  1309
(* ------------------------------------------------------------------------- *)
webertj@14807
  1310
wenzelm@39046
  1311
(* We could in principle represent '=' on a type T by a particular        *)
wenzelm@39046
  1312
(* interpretation.  However, the size of that interpretation is quadratic *)
wenzelm@39046
  1313
(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
wenzelm@39046
  1314
(* 'i2' directly is more efficient than constructing the interpretation   *)
wenzelm@39046
  1315
(* for equality on T first, and "applying" this interpretation to 'i1'    *)
wenzelm@39046
  1316
(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
webertj@14807
  1317
wenzelm@39046
  1318
fun make_equality (i1, i2) =
wenzelm@22567
  1319
  let
wenzelm@22567
  1320
    fun equal (i1, i2) =
wenzelm@22567
  1321
      (case i1 of
wenzelm@22567
  1322
        Leaf xs =>
wenzelm@39046
  1323
          (case i2 of
wenzelm@41471
  1324
            Leaf ys => Prop_Logic.dot_product (xs, ys)  (* defined and equal *)
wenzelm@39046
  1325
          | Node _  => raise REFUTE ("make_equality",
wenzelm@39046
  1326
            "second interpretation is higher"))
wenzelm@22567
  1327
      | Node xs =>
wenzelm@39046
  1328
          (case i2 of
wenzelm@39046
  1329
            Leaf _  => raise REFUTE ("make_equality",
wenzelm@39046
  1330
            "first interpretation is higher")
wenzelm@41471
  1331
          | Node ys => Prop_Logic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1332
    fun not_equal (i1, i2) =
wenzelm@22567
  1333
      (case i1 of
wenzelm@22567
  1334
        Leaf xs =>
wenzelm@39046
  1335
          (case i2 of
wenzelm@39046
  1336
            (* defined and not equal *)
wenzelm@41471
  1337
            Leaf ys => Prop_Logic.all ((Prop_Logic.exists xs)
wenzelm@41471
  1338
            :: (Prop_Logic.exists ys)
wenzelm@39046
  1339
            :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
wenzelm@39046
  1340
          | Node _  => raise REFUTE ("make_equality",
wenzelm@39046
  1341
            "second interpretation is higher"))
wenzelm@22567
  1342
      | Node xs =>
wenzelm@39046
  1343
          (case i2 of
wenzelm@39046
  1344
            Leaf _  => raise REFUTE ("make_equality",
wenzelm@39046
  1345
            "first interpretation is higher")
wenzelm@41471
  1346
          | Node ys => Prop_Logic.exists (map not_equal (xs ~~ ys))))
wenzelm@22567
  1347
  in
wenzelm@22567
  1348
    (* a value may be undefined; therefore 'not_equal' is not just the *)
wenzelm@22567
  1349
    (* negation of 'equal'                                             *)
wenzelm@22567
  1350
    Leaf [equal (i1, i2), not_equal (i1, i2)]
wenzelm@22567
  1351
  end;
webertj@14807
  1352
webertj@15292
  1353
(* ------------------------------------------------------------------------- *)
webertj@15547
  1354
(* make_def_equality: returns an interpretation that denotes (extensional)   *)
webertj@15547
  1355
(*                    equality of two interpretations                        *)
webertj@15547
  1356
(* This function treats undefined/partially defined interpretations          *)
webertj@15547
  1357
(* different from 'make_equality': two undefined interpretations are         *)
webertj@15547
  1358
(* considered equal, while a defined interpretation is considered not equal  *)
webertj@15547
  1359
(* to an undefined interpretation.                                           *)
webertj@15547
  1360
(* ------------------------------------------------------------------------- *)
webertj@15547
  1361
wenzelm@39046
  1362
fun make_def_equality (i1, i2) =
wenzelm@22567
  1363
  let
wenzelm@22567
  1364
    fun equal (i1, i2) =
wenzelm@22567
  1365
      (case i1 of
wenzelm@22567
  1366
        Leaf xs =>
wenzelm@39046
  1367
          (case i2 of
wenzelm@39046
  1368
            (* defined and equal, or both undefined *)
wenzelm@41471
  1369
            Leaf ys => SOr (Prop_Logic.dot_product (xs, ys),
wenzelm@41471
  1370
            SAnd (Prop_Logic.all (map SNot xs), Prop_Logic.all (map SNot ys)))
wenzelm@39046
  1371
          | Node _  => raise REFUTE ("make_def_equality",
wenzelm@39046
  1372
            "second interpretation is higher"))
wenzelm@22567
  1373
      | Node xs =>
wenzelm@39046
  1374
          (case i2 of
wenzelm@39046
  1375
            Leaf _  => raise REFUTE ("make_def_equality",
wenzelm@39046
  1376
            "first interpretation is higher")
wenzelm@41471
  1377
          | Node ys => Prop_Logic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1378
    val eq = equal (i1, i2)
wenzelm@22567
  1379
  in
wenzelm@22567
  1380
    Leaf [eq, SNot eq]
wenzelm@22567
  1381
  end;
webertj@15547
  1382
webertj@15547
  1383
(* ------------------------------------------------------------------------- *)
webertj@15547
  1384
(* interpretation_apply: returns an interpretation that denotes the result   *)
webertj@22092
  1385
(*                       of applying the function denoted by 'i1' to the     *)
webertj@15547
  1386
(*                       argument denoted by 'i2'                            *)
webertj@15547
  1387
(* ------------------------------------------------------------------------- *)
webertj@15547
  1388
wenzelm@39046
  1389
fun interpretation_apply (i1, i2) =
wenzelm@22567
  1390
  let
wenzelm@22567
  1391
    fun interpretation_disjunction (tr1,tr2) =
wenzelm@22567
  1392
      tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
wenzelm@22567
  1393
        (tree_pair (tr1,tr2))
wenzelm@22567
  1394
    fun prop_formula_times_interpretation (fm,tr) =
wenzelm@22567
  1395
      tree_map (map (fn x => SAnd (fm,x))) tr
wenzelm@22567
  1396
    fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
wenzelm@39046
  1397
          prop_formula_times_interpretation (fm,tr)
wenzelm@22567
  1398
      | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
wenzelm@39046
  1399
          interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
wenzelm@39046
  1400
            prop_formula_list_dot_product_interpretation_list (fms,trees))
wenzelm@22567
  1401
      | prop_formula_list_dot_product_interpretation_list (_,_) =
wenzelm@39046
  1402
          raise REFUTE ("interpretation_apply", "empty list (in dot product)")
wenzelm@22567
  1403
    (* returns a list of lists, each one consisting of one element from each *)
wenzelm@22567
  1404
    (* element of 'xss'                                                      *)
wenzelm@39046
  1405
    fun pick_all [xs] = map single xs
wenzelm@22567
  1406
      | pick_all (xs::xss) =
wenzelm@39046
  1407
          let val rec_pick = pick_all xss in
wenzelm@39046
  1408
            maps (fn x => map (cons x) rec_pick) xs
wenzelm@39046
  1409
          end
wenzelm@39046
  1410
      | pick_all _ = raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
wenzelm@39046
  1411
    fun interpretation_to_prop_formula_list (Leaf xs) = xs
wenzelm@22567
  1412
      | interpretation_to_prop_formula_list (Node trees) =
wenzelm@41471
  1413
          map Prop_Logic.all (pick_all
wenzelm@39046
  1414
            (map interpretation_to_prop_formula_list trees))
wenzelm@22567
  1415
  in
wenzelm@22567
  1416
    case i1 of
wenzelm@22567
  1417
      Leaf _ =>
wenzelm@39046
  1418
        raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
wenzelm@22567
  1419
    | Node xs =>
wenzelm@39046
  1420
        prop_formula_list_dot_product_interpretation_list
wenzelm@39046
  1421
          (interpretation_to_prop_formula_list i2, xs)
wenzelm@22567
  1422
  end;
webertj@15547
  1423
webertj@15547
  1424
(* ------------------------------------------------------------------------- *)
webertj@15292
  1425
(* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
webertj@15292
  1426
(* ------------------------------------------------------------------------- *)
webertj@15292
  1427
wenzelm@39046
  1428
fun eta_expand t i =
wenzelm@22567
  1429
  let
wenzelm@22567
  1430
    val Ts = Term.binder_types (Term.fastype_of t)
wenzelm@22567
  1431
    val t' = Term.incr_boundvars i t
wenzelm@22567
  1432
  in
wenzelm@33339
  1433
    fold_rev (fn T => fn term => Abs ("<eta_expand>", T, term))
wenzelm@33339
  1434
      (List.take (Ts, i))
wenzelm@33339
  1435
      (Term.list_comb (t', map Bound (i-1 downto 0)))
wenzelm@22567
  1436
  end;
webertj@15292
  1437
webertj@15335
  1438
(* ------------------------------------------------------------------------- *)
webertj@15547
  1439
(* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
webertj@15547
  1440
(*               is the sum (over its constructors) of the product (over     *)
webertj@15547
  1441
(*               their arguments) of the size of the argument types          *)
webertj@15335
  1442
(* ------------------------------------------------------------------------- *)
webertj@15335
  1443
wenzelm@39049
  1444
fun size_of_dtyp ctxt typ_sizes descr typ_assoc constructors =
wenzelm@39046
  1445
  Integer.sum (map (fn (_, dtyps) =>
wenzelm@39049
  1446
    Integer.prod (map (size_of_type ctxt (typ_sizes, []) o
wenzelm@39046
  1447
      (typ_of_dtyp descr typ_assoc)) dtyps))
wenzelm@39046
  1448
        constructors);
webertj@15335
  1449
webertj@15292
  1450
webertj@15292
  1451
(* ------------------------------------------------------------------------- *)
webertj@15292
  1452
(* INTERPRETERS: Actual Interpreters                                         *)
webertj@15292
  1453
(* ------------------------------------------------------------------------- *)
webertj@14807
  1454
wenzelm@39046
  1455
(* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
wenzelm@39046
  1456
(* variables, function types, and propT                                  *)
webertj@14807
  1457
wenzelm@39049
  1458
fun stlc_interpreter ctxt model args t =
wenzelm@22567
  1459
  let
wenzelm@39046
  1460
    val (typs, terms) = model
wenzelm@22567
  1461
    val {maxvars, def_eq, next_idx, bounds, wellformed} = args
wenzelm@22567
  1462
    fun interpret_groundterm T =
wenzelm@22567
  1463
      let
wenzelm@39046
  1464
        fun interpret_groundtype () =
wenzelm@39046
  1465
          let
wenzelm@39046
  1466
            (* the model must specify a size for ground types *)
wenzelm@39046
  1467
            val size =
wenzelm@39046
  1468
              if T = Term.propT then 2
wenzelm@39046
  1469
              else the (AList.lookup (op =) typs T)
wenzelm@39046
  1470
            val next = next_idx + size
wenzelm@39046
  1471
            (* check if 'maxvars' is large enough *)
wenzelm@39046
  1472
            val _ = (if next - 1 > maxvars andalso maxvars > 0 then
wenzelm@39046
  1473
              raise MAXVARS_EXCEEDED else ())
wenzelm@39046
  1474
            val fms  = map BoolVar (next_idx upto (next_idx + size - 1))
wenzelm@39046
  1475
            val intr = Leaf fms
wenzelm@39046
  1476
            fun one_of_two_false [] = True
wenzelm@41471
  1477
              | one_of_two_false (x::xs) = SAnd (Prop_Logic.all (map (fn x' =>
wenzelm@39046
  1478
                  SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@39046
  1479
            val wf = one_of_two_false fms
wenzelm@39046
  1480
          in
wenzelm@39046
  1481
            (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39046
  1482
            (* condition                                                  *)
wenzelm@39046
  1483
            SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@39046
  1484
              def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@39046
  1485
              wellformed = SAnd (wellformed, wf)})
wenzelm@39046
  1486
          end
wenzelm@22567
  1487
      in
wenzelm@39046
  1488
        case T of
wenzelm@39046
  1489
          Type ("fun", [T1, T2]) =>
wenzelm@39046
  1490
            let
wenzelm@39046
  1491
              (* we create 'size_of_type ... T1' different copies of the        *)
wenzelm@39046
  1492
              (* interpretation for 'T2', which are then combined into a single *)
wenzelm@39046
  1493
              (* new interpretation                                             *)
wenzelm@39046
  1494
              (* make fresh copies, with different variable indices *)
wenzelm@39046
  1495
              (* 'idx': next variable index                         *)
wenzelm@39046
  1496
              (* 'n'  : number of copies                            *)
wenzelm@39046
  1497
              fun make_copies idx 0 = (idx, [], True)
wenzelm@39046
  1498
                | make_copies idx n =
wenzelm@39046
  1499
                    let
wenzelm@39049
  1500
                      val (copy, _, new_args) = interpret ctxt (typs, [])
wenzelm@39046
  1501
                        {maxvars = maxvars, def_eq = false, next_idx = idx,
wenzelm@39046
  1502
                        bounds = [], wellformed = True} (Free ("dummy", T2))
wenzelm@39046
  1503
                      val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
wenzelm@39046
  1504
                    in
wenzelm@39046
  1505
                      (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
wenzelm@39046
  1506
                    end
wenzelm@39046
  1507
              val (next, copies, wf) = make_copies next_idx
wenzelm@39049
  1508
                (size_of_type ctxt model T1)
wenzelm@39046
  1509
              (* combine copies into a single interpretation *)
wenzelm@39046
  1510
              val intr = Node copies
wenzelm@39046
  1511
            in
wenzelm@39046
  1512
              (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39046
  1513
              (* condition                                                  *)
wenzelm@39046
  1514
              SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@39046
  1515
                def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@39046
  1516
                wellformed = SAnd (wellformed, wf)})
wenzelm@39046
  1517
            end
wenzelm@39046
  1518
        | Type _  => interpret_groundtype ()
wenzelm@39046
  1519
        | TFree _ => interpret_groundtype ()
wenzelm@39046
  1520
        | TVar  _ => interpret_groundtype ()
wenzelm@22567
  1521
      end
wenzelm@22567
  1522
  in
wenzelm@22567
  1523
    case AList.lookup (op =) terms t of
wenzelm@22567
  1524
      SOME intr =>
wenzelm@39046
  1525
        (* return an existing interpretation *)
wenzelm@39046
  1526
        SOME (intr, model, args)
wenzelm@22567
  1527
    | NONE =>
wenzelm@39046
  1528
        (case t of
wenzelm@39046
  1529
          Const (_, T) => interpret_groundterm T
wenzelm@39046
  1530
        | Free (_, T) => interpret_groundterm T
wenzelm@39046
  1531
        | Var (_, T) => interpret_groundterm T
wenzelm@42364
  1532
        | Bound i => SOME (nth (#bounds args) i, model, args)
blanchet@46096
  1533
        | Abs (_, T, body) =>
wenzelm@39046
  1534
            let
wenzelm@39046
  1535
              (* create all constants of type 'T' *)
wenzelm@39049
  1536
              val constants = make_constants ctxt model T
wenzelm@39046
  1537
              (* interpret the 'body' separately for each constant *)
wenzelm@39046
  1538
              val (bodies, (model', args')) = fold_map
wenzelm@39046
  1539
                (fn c => fn (m, a) =>
wenzelm@39046
  1540
                  let
wenzelm@39046
  1541
                    (* add 'c' to 'bounds' *)
wenzelm@39049
  1542
                    val (i', m', a') = interpret ctxt m {maxvars = #maxvars a,
wenzelm@39046
  1543
                      def_eq = #def_eq a, next_idx = #next_idx a,
wenzelm@39046
  1544
                      bounds = (c :: #bounds a), wellformed = #wellformed a} body
wenzelm@39046
  1545
                  in
wenzelm@39046
  1546
                    (* keep the new model m' and 'next_idx' and 'wellformed', *)
wenzelm@39046
  1547
                    (* but use old 'bounds'                                   *)
wenzelm@39046
  1548
                    (i', (m', {maxvars = maxvars, def_eq = def_eq,
wenzelm@39046
  1549
                      next_idx = #next_idx a', bounds = bounds,
wenzelm@39046
  1550
                      wellformed = #wellformed a'}))
wenzelm@39046
  1551
                  end)
wenzelm@39046
  1552
                constants (model, args)
wenzelm@39046
  1553
            in
wenzelm@39046
  1554
              SOME (Node bodies, model', args')
wenzelm@39046
  1555
            end
wenzelm@39046
  1556
        | t1 $ t2 =>
wenzelm@39046
  1557
            let
wenzelm@39046
  1558
              (* interpret 't1' and 't2' separately *)
wenzelm@39049
  1559
              val (intr1, model1, args1) = interpret ctxt model args t1
wenzelm@39049
  1560
              val (intr2, model2, args2) = interpret ctxt model1 args1 t2
wenzelm@39046
  1561
            in
wenzelm@39046
  1562
              SOME (interpretation_apply (intr1, intr2), model2, args2)
wenzelm@39046
  1563
            end)
wenzelm@22567
  1564
  end;
webertj@14807
  1565
wenzelm@39049
  1566
fun Pure_interpreter ctxt model args t =
wenzelm@39046
  1567
  case t of
wenzelm@56245
  1568
    Const (@{const_name Pure.all}, _) $ t1 =>
wenzelm@22567
  1569
      let
wenzelm@39049
  1570
        val (i, m, a) = interpret ctxt model args t1
wenzelm@22567
  1571
      in
wenzelm@22567
  1572
        case i of
wenzelm@22567
  1573
          Node xs =>
wenzelm@39046
  1574
            (* 3-valued logic *)
wenzelm@39046
  1575
            let
wenzelm@41471
  1576
              val fmTrue  = Prop_Logic.all (map toTrue xs)
wenzelm@41471
  1577
              val fmFalse = Prop_Logic.exists (map toFalse xs)
wenzelm@39046
  1578
            in
wenzelm@39046
  1579
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39046
  1580
            end
wenzelm@22567
  1581
        | _ =>
wenzelm@22567
  1582
          raise REFUTE ("Pure_interpreter",
wenzelm@56245
  1583
            "\"Pure.all\" is followed by a non-function")
wenzelm@22567
  1584
      end
wenzelm@56245
  1585
  | Const (@{const_name Pure.all}, _) =>
wenzelm@39049
  1586
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1587
  | Const (@{const_name Pure.eq}, _) $ t1 $ t2 =>
wenzelm@22567
  1588
      let
wenzelm@39049
  1589
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1590
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@22567
  1591
      in
wenzelm@22567
  1592
        (* we use either 'make_def_equality' or 'make_equality' *)
wenzelm@22567
  1593
        SOME ((if #def_eq args then make_def_equality else make_equality)
wenzelm@22567
  1594
          (i1, i2), m2, a2)
wenzelm@22567
  1595
      end
wenzelm@56245
  1596
  | Const (@{const_name Pure.eq}, _) $ _ =>
wenzelm@39049
  1597
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1598
  | Const (@{const_name Pure.eq}, _) =>
wenzelm@39049
  1599
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@56245
  1600
  | Const (@{const_name Pure.imp}, _) $ t1 $ t2 =>
wenzelm@22567
  1601
      (* 3-valued logic *)
wenzelm@22567
  1602
      let
wenzelm@39049
  1603
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1604
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1605
        val fmTrue = Prop_Logic.SOr (toFalse i1, toTrue i2)
wenzelm@41471
  1606
        val fmFalse = Prop_Logic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1607
      in
wenzelm@22567
  1608
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1609
      end
wenzelm@56245
  1610
  | Const (@{const_name Pure.imp}, _) $ _ =>
wenzelm@39049
  1611
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1612
  | Const (@{const_name Pure.imp}, _) =>
wenzelm@39049
  1613
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@39046
  1614
  | _ => NONE;
webertj@14807
  1615
wenzelm@39049
  1616
fun HOLogic_interpreter ctxt model args t =
wenzelm@39046
  1617
(* Providing interpretations directly is more efficient than unfolding the *)
wenzelm@39046
  1618
(* logical constants.  In HOL however, logical constants can themselves be *)
wenzelm@39046
  1619
(* arguments.  They are then translated using eta-expansion.               *)
wenzelm@39046
  1620
  case t of
wenzelm@39046
  1621
    Const (@{const_name Trueprop}, _) =>
wenzelm@22567
  1622
      SOME (Node [TT, FF], model, args)
wenzelm@39046
  1623
  | Const (@{const_name Not}, _) =>
wenzelm@22567
  1624
      SOME (Node [FF, TT], model, args)
wenzelm@39046
  1625
  (* redundant, since 'True' is also an IDT constructor *)
wenzelm@39046
  1626
  | Const (@{const_name True}, _) =>
wenzelm@22567
  1627
      SOME (TT, model, args)
wenzelm@39046
  1628
  (* redundant, since 'False' is also an IDT constructor *)
wenzelm@39046
  1629
  | Const (@{const_name False}, _) =>
wenzelm@22567
  1630
      SOME (FF, model, args)
wenzelm@56245
  1631
  | Const (@{const_name All}, _) $ t1 =>  (* similar to "Pure.all" *)
wenzelm@22567
  1632
      let
wenzelm@39049
  1633
        val (i, m, a) = interpret ctxt model args t1
wenzelm@22567
  1634
      in
wenzelm@22567
  1635
        case i of
wenzelm@22567
  1636
          Node xs =>
wenzelm@39046
  1637
            (* 3-valued logic *)
wenzelm@39046
  1638
            let
wenzelm@41471
  1639
              val fmTrue = Prop_Logic.all (map toTrue xs)
wenzelm@41471
  1640
              val fmFalse = Prop_Logic.exists (map toFalse xs)
wenzelm@39046
  1641
            in
wenzelm@39046
  1642
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39046
  1643
            end
wenzelm@22567
  1644
        | _ =>
wenzelm@22567
  1645
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1646
            "\"All\" is followed by a non-function")
wenzelm@22567
  1647
      end
wenzelm@39046
  1648
  | Const (@{const_name All}, _) =>
wenzelm@39049
  1649
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1650
  | Const (@{const_name Ex}, _) $ t1 =>
wenzelm@22567
  1651
      let
wenzelm@39049
  1652
        val (i, m, a) = interpret ctxt model args t1
wenzelm@22567
  1653
      in
wenzelm@22567
  1654
        case i of
wenzelm@22567
  1655
          Node xs =>
wenzelm@39046
  1656
            (* 3-valued logic *)
wenzelm@39046
  1657
            let
wenzelm@41471
  1658
              val fmTrue = Prop_Logic.exists (map toTrue xs)
wenzelm@41471
  1659
              val fmFalse = Prop_Logic.all (map toFalse xs)
wenzelm@39046
  1660
            in
wenzelm@39046
  1661
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39046
  1662
            end
wenzelm@22567
  1663
        | _ =>
wenzelm@22567
  1664
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1665
            "\"Ex\" is followed by a non-function")
wenzelm@22567
  1666
      end
wenzelm@39046
  1667
  | Const (@{const_name Ex}, _) =>
wenzelm@39049
  1668
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@56245
  1669
  | Const (@{const_name HOL.eq}, _) $ t1 $ t2 =>  (* similar to Pure.eq *)
wenzelm@22567
  1670
      let
wenzelm@39049
  1671
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1672
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@22567
  1673
      in
wenzelm@22567
  1674
        SOME (make_equality (i1, i2), m2, a2)
wenzelm@22567
  1675
      end
blanchet@46096
  1676
  | Const (@{const_name HOL.eq}, _) $ _ =>
wenzelm@39049
  1677
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1678
  | Const (@{const_name HOL.eq}, _) =>
wenzelm@39049
  1679
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@39046
  1680
  | Const (@{const_name HOL.conj}, _) $ t1 $ t2 =>
wenzelm@22567
  1681
      (* 3-valued logic *)
wenzelm@22567
  1682
      let
wenzelm@39049
  1683
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1684
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1685
        val fmTrue = Prop_Logic.SAnd (toTrue i1, toTrue i2)
wenzelm@41471
  1686
        val fmFalse = Prop_Logic.SOr (toFalse i1, toFalse i2)
wenzelm@22567
  1687
      in
wenzelm@22567
  1688
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1689
      end
blanchet@46096
  1690
  | Const (@{const_name HOL.conj}, _) $ _ =>
wenzelm@39049
  1691
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1692
  | Const (@{const_name HOL.conj}, _) =>
wenzelm@39049
  1693
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@22567
  1694
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1695
      (* "False & undef":                                          *)
wenzelm@22567
  1696
      (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
wenzelm@39046
  1697
  | Const (@{const_name HOL.disj}, _) $ t1 $ t2 =>
wenzelm@22567
  1698
      (* 3-valued logic *)
wenzelm@22567
  1699
      let
wenzelm@39049
  1700
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1701
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1702
        val fmTrue = Prop_Logic.SOr (toTrue i1, toTrue i2)
wenzelm@41471
  1703
        val fmFalse = Prop_Logic.SAnd (toFalse i1, toFalse i2)
wenzelm@22567
  1704
      in
wenzelm@22567
  1705
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1706
      end
blanchet@46096
  1707
  | Const (@{const_name HOL.disj}, _) $ _ =>
wenzelm@39049
  1708
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1709
  | Const (@{const_name HOL.disj}, _) =>
wenzelm@39049
  1710
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@22567
  1711
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1712
      (* "True | undef":                                           *)
wenzelm@22567
  1713
      (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
wenzelm@56245
  1714
  | Const (@{const_name HOL.implies}, _) $ t1 $ t2 =>  (* similar to Pure.imp *)
wenzelm@22567
  1715
      (* 3-valued logic *)
wenzelm@22567
  1716
      let
wenzelm@39049
  1717
        val (i1, m1, a1) = interpret ctxt model args t1
wenzelm@39049
  1718
        val (i2, m2, a2) = interpret ctxt m1 a1 t2
wenzelm@41471
  1719
        val fmTrue = Prop_Logic.SOr (toFalse i1, toTrue i2)
wenzelm@41471
  1720
        val fmFalse = Prop_Logic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1721
      in
wenzelm@22567
  1722
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1723
      end
blanchet@46096
  1724
  | Const (@{const_name HOL.implies}, _) $ _ =>
wenzelm@39049
  1725
      SOME (interpret ctxt model args (eta_expand t 1))
wenzelm@39046
  1726
  | Const (@{const_name HOL.implies}, _) =>
wenzelm@39049
  1727
      SOME (interpret ctxt model args (eta_expand t 2))
wenzelm@22567
  1728
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1729
      (* "False --> undef":                                        *)
wenzelm@22567
  1730
      (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
wenzelm@39046
  1731
  | _ => NONE;
webertj@14807
  1732
wenzelm@39046
  1733
(* interprets variables and constants whose type is an IDT (this is        *)
wenzelm@39046
  1734
(* relatively easy and merely requires us to compute the size of the IDT); *)
wenzelm@39046
  1735
(* constructors of IDTs however are properly interpreted by                *)
wenzelm@39046
  1736
(* 'IDT_constructor_interpreter'                                           *)
webertj@15547
  1737
wenzelm@39049
  1738
fun IDT_interpreter ctxt model args t =
wenzelm@22567
  1739
  let
wenzelm@42361
  1740
    val thy = Proof_Context.theory_of ctxt
wenzelm@22567
  1741
    val (typs, terms) = model
wenzelm@22567
  1742
    fun interpret_term (Type (s, Ts)) =
blanchet@58129
  1743
          (case BNF_LFP_Compat.get_info thy BNF_LFP_Compat.Unfold_Nesting s of
wenzelm@39046
  1744
            SOME info =>  (* inductive datatype *)
wenzelm@39046
  1745
              let
wenzelm@55507
  1746
                (* only recursive IDTs have an associated depth *)
wenzelm@39046
  1747
                val depth = AList.lookup (op =) typs (Type (s, Ts))
wenzelm@39046
  1748
                (* sanity check: depth must be at least 0 *)
wenzelm@39046
  1749
                val _ =
wenzelm@39046
  1750
                  (case depth of SOME n =>
wenzelm@39046
  1751
                    if n < 0 then
wenzelm@39046
  1752
                      raise REFUTE ("IDT_interpreter", "negative depth")
wenzelm@39046
  1753
                    else ()
wenzelm@39046
  1754
                  | _ => ())
wenzelm@39046
  1755
              in
wenzelm@39046
  1756
                (* termination condition to avoid infinite recursion *)
wenzelm@39046
  1757
                if depth = (SOME 0) then
wenzelm@39046
  1758
                  (* return a leaf of size 0 *)
wenzelm@39046
  1759
                  SOME (Leaf [], model, args)
wenzelm@39046
  1760
                else
wenzelm@39046
  1761
                  let
wenzelm@39046
  1762
                    val index               = #index info
wenzelm@39046
  1763
                    val descr               = #descr info
wenzelm@39046
  1764
                    val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1765
                    val typ_assoc           = dtyps ~~ Ts
wenzelm@39046
  1766
                    (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39046
  1767
                    val _ =
wenzelm@39046
  1768
                      if Library.exists (fn d =>
blanchet@58120
  1769
                        case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39046
  1770
                      then
wenzelm@39046
  1771
                        raise REFUTE ("IDT_interpreter",
wenzelm@39046
  1772
                          "datatype argument (for type "
wenzelm@39049
  1773
                          ^ Syntax.string_of_typ ctxt (Type (s, Ts))
wenzelm@39046
  1774
                          ^ ") is not a variable")
wenzelm@39046
  1775
                      else ()
wenzelm@39046
  1776
                    (* if the model specifies a depth for the current type, *)
wenzelm@39046
  1777
                    (* decrement it to avoid infinite recursion             *)
wenzelm@39046
  1778
                    val typs' = case depth of NONE => typs | SOME n =>
wenzelm@39046
  1779
                      AList.update (op =) (Type (s, Ts), n-1) typs
wenzelm@39046
  1780
                    (* recursively compute the size of the datatype *)
wenzelm@39049
  1781
                    val size     = size_of_dtyp ctxt typs' descr typ_assoc constrs
wenzelm@39046
  1782
                    val next_idx = #next_idx args
wenzelm@39046
  1783
                    val next     = next_idx+size
wenzelm@39046
  1784
                    (* check if 'maxvars' is large enough *)
wenzelm@39046
  1785
                    val _        = (if next-1 > #maxvars args andalso
wenzelm@39046
  1786
                      #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
wenzelm@39046
  1787
                    val fms      = map BoolVar (next_idx upto (next_idx+size-1))
wenzelm@39046
  1788
                    val intr     = Leaf fms
wenzelm@39046
  1789
                    fun one_of_two_false [] = True
wenzelm@41471
  1790
                      | one_of_two_false (x::xs) = SAnd (Prop_Logic.all (map (fn x' =>
wenzelm@39046
  1791
                          SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@39046
  1792
                    val wf = one_of_two_false fms
wenzelm@39046
  1793
                  in
wenzelm@39046
  1794
                    (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39046
  1795
                    (* condition                                                  *)
wenzelm@39046
  1796
                    SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
wenzelm@39046
  1797
                      def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
wenzelm@39046
  1798
                      wellformed = SAnd (#wellformed args, wf)})
wenzelm@39046
  1799
                  end
wenzelm@39046
  1800
              end
wenzelm@39046
  1801
          | NONE =>  (* not an inductive datatype *)
wenzelm@39046
  1802
              NONE)
wenzelm@22567
  1803
      | interpret_term _ =  (* a (free or schematic) type variable *)
wenzelm@39046
  1804
          NONE
wenzelm@22567
  1805
  in
wenzelm@22567
  1806
    case AList.lookup (op =) terms t of
wenzelm@22567
  1807
      SOME intr =>
wenzelm@39046
  1808
        (* return an existing interpretation *)
wenzelm@39046
  1809
        SOME (intr, model, args)
wenzelm@22567
  1810
    | NONE =>
wenzelm@39046
  1811
        (case t of
wenzelm@39046
  1812
          Free (_, T) => interpret_term T
wenzelm@39046
  1813
        | Var (_, T) => interpret_term T
wenzelm@39046
  1814
        | Const (_, T) => interpret_term T
wenzelm@39046
  1815
        | _ => NONE)
wenzelm@22567
  1816
  end;
webertj@15547
  1817
wenzelm@39046
  1818
(* This function imposes an order on the elements of a datatype fragment  *)
wenzelm@39046
  1819
(* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
wenzelm@39046
  1820
(* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
wenzelm@39046
  1821
(* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
wenzelm@39046
  1822
(* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
wenzelm@39046
  1823
(* same for recursive datatypes, although the computation of indices gets *)
wenzelm@39046
  1824
(* a little tricky.                                                       *)
webertj@25014
  1825
wenzelm@39049
  1826
fun IDT_constructor_interpreter ctxt model args t =
wenzelm@22567
  1827
  let
wenzelm@42361
  1828
    val thy = Proof_Context.theory_of ctxt
webertj@25014
  1829
    (* returns a list of canonical representations for terms of the type 'T' *)
webertj@25014
  1830
    (* It would be nice if we could just use 'print' for this, but 'print'   *)
webertj@25014
  1831
    (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
webertj@25014
  1832
    (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
webertj@25014
  1833
    fun canonical_terms typs T =
wenzelm@39046
  1834
          (case T of
wenzelm@39046
  1835
            Type ("fun", [T1, T2]) =>
wenzelm@39046
  1836
            (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
wenzelm@39046
  1837
            (* least not for 'T2'                                               *)
wenzelm@39046
  1838
            let
wenzelm@39046
  1839
              (* returns a list of lists, each one consisting of n (possibly *)
wenzelm@39046
  1840
              (* identical) elements from 'xs'                               *)
wenzelm@39046
  1841
              fun pick_all 1 xs = map single xs
wenzelm@39046
  1842
                | pick_all n xs =
wenzelm@39046
  1843
                    let val rec_pick = pick_all (n-1) xs in
wenzelm@39046
  1844
                      maps (fn x => map (cons x) rec_pick) xs
wenzelm@39046
  1845
                    end
wenzelm@39046
  1846
              (* ["x1", ..., "xn"] *)
wenzelm@39046
  1847
              val terms1 = canonical_terms typs T1
wenzelm@39046
  1848
              (* ["y1", ..., "ym"] *)
wenzelm@39046
  1849
              val terms2 = canonical_terms typs T2
wenzelm@39046
  1850
              (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
wenzelm@39046
  1851
              (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
wenzelm@39046
  1852
              val functions = map (curry (op ~~) terms1)
wenzelm@39046
  1853
                (pick_all (length terms1) terms2)
wenzelm@39046
  1854
              (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
wenzelm@39046
  1855
              (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
wenzelm@39046
  1856
              val pairss = map (map HOLogic.mk_prod) functions
wenzelm@39046
  1857
              val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
wenzelm@39046
  1858
              val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
wenzelm@39046
  1859
              val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
wenzelm@39046
  1860
              val HOLogic_insert    =
wenzelm@39046
  1861
                Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
wenzelm@39046
  1862
            in
wenzelm@39046
  1863
              (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
wenzelm@39046
  1864
              map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
wenzelm@39046
  1865
                HOLogic_empty_set) pairss
webertj@25014
  1866
            end
webertj@25014
  1867
      | Type (s, Ts) =>
blanchet@58129
  1868
          (case BNF_LFP_Compat.get_info thy BNF_LFP_Compat.Unfold_Nesting s of
wenzelm@39046
  1869
            SOME info =>
wenzelm@39046
  1870
              (case AList.lookup (op =) typs T of
wenzelm@39046
  1871
                SOME 0 =>
wenzelm@39046
  1872
                  (* termination condition to avoid infinite recursion *)
wenzelm@39046
  1873
                  []  (* at depth 0, every IDT is empty *)
wenzelm@39046
  1874
              | _ =>
webertj@25014
  1875
                let
wenzelm@39046
  1876
                  val index = #index info
wenzelm@39046
  1877
                  val descr = #descr info
wenzelm@39046
  1878
                  val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1879
                  val typ_assoc = dtyps ~~ Ts
wenzelm@39046
  1880
                  (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39046
  1881
                  val _ =
wenzelm@39046
  1882
                    if Library.exists (fn d =>
blanchet@58120
  1883
                      case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39046
  1884
                    then
wenzelm@39046
  1885
                      raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1886
                        "datatype argument (for type "
wenzelm@39049
  1887
                        ^ Syntax.string_of_typ ctxt T
wenzelm@39046
  1888
                        ^ ") is not a variable")
wenzelm@39046
  1889
                    else ()
wenzelm@39046
  1890
                  (* decrement depth for the IDT 'T' *)
wenzelm@39046
  1891
                  val typs' =
wenzelm@39046
  1892
                    (case AList.lookup (op =) typs T of NONE => typs
wenzelm@39046
  1893
                    | SOME n => AList.update (op =) (T, n-1) typs)
wenzelm@39046
  1894
                  fun constructor_terms terms [] = terms
wenzelm@39046
  1895
                    | constructor_terms terms (d::ds) =
wenzelm@39046
  1896
                        let
wenzelm@39046
  1897
                          val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39046
  1898
                          val d_terms = canonical_terms typs' dT
wenzelm@39046
  1899
                        in
wenzelm@39046
  1900
                          (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
wenzelm@39046
  1901
                          (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
wenzelm@39046
  1902
                          constructor_terms
wenzelm@39046
  1903
                            (map_product (curry op $) terms d_terms) ds
wenzelm@39046
  1904
                        end
webertj@25014
  1905
                in
wenzelm@39046
  1906
                  (* C_i ... < C_j ... if i < j *)
wenzelm@39046
  1907
                  maps (fn (cname, ctyps) =>
wenzelm@39046
  1908
                    let
wenzelm@39046
  1909
                      val cTerm = Const (cname,
wenzelm@39046
  1910
                        map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
wenzelm@39046
  1911
                    in
wenzelm@39046
  1912
                      constructor_terms [cTerm] ctyps
wenzelm@39046
  1913
                    end) constrs
wenzelm@39046
  1914
                end)
wenzelm@39046
  1915
          | NONE =>
wenzelm@39046
  1916
              (* not an inductive datatype; in this case the argument types in *)
wenzelm@39046
  1917
              (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
wenzelm@39049
  1918
              map (fn intr => print ctxt (typs, []) T intr (K false))
wenzelm@39049
  1919
                (make_constants ctxt (typs, []) T))
wenzelm@39046
  1920
      | _ =>  (* TFree ..., TVar ... *)
wenzelm@39049
  1921
          map (fn intr => print ctxt (typs, []) T intr (K false))
wenzelm@39049
  1922
            (make_constants ctxt (typs, []) T))
wenzelm@22567
  1923
    val (typs, terms) = model
wenzelm@22567
  1924
  in
wenzelm@22567
  1925
    case AList.lookup (op =) terms t of
wenzelm@22567
  1926
      SOME intr =>
wenzelm@39046
  1927
        (* return an existing interpretation *)
wenzelm@39046
  1928
        SOME (intr, model, args)
wenzelm@22567
  1929
    | NONE =>
wenzelm@39046
  1930
        (case t of
wenzelm@39046
  1931
          Const (s, T) =>
wenzelm@39046
  1932
            (case body_type T of
wenzelm@39046
  1933
              Type (s', Ts') =>
blanchet@58129
  1934
                (case BNF_LFP_Compat.get_info thy BNF_LFP_Compat.Unfold_Nesting s' of
wenzelm@39046
  1935
                  SOME info =>  (* body type is an inductive datatype *)
wenzelm@22567
  1936
                    let
wenzelm@39046
  1937
                      val index               = #index info
wenzelm@39046
  1938
                      val descr               = #descr info
wenzelm@39046
  1939
                      val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39046
  1940
                      val typ_assoc           = dtyps ~~ Ts'
wenzelm@39046
  1941
                      (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39046
  1942
                      val _ = if Library.exists (fn d =>
blanchet@58120
  1943
                          case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
webertj@25014
  1944
                        then
webertj@25014
  1945
                          raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1946
                            "datatype argument (for type "
wenzelm@39049
  1947
                            ^ Syntax.string_of_typ ctxt (Type (s', Ts'))
wenzelm@39046
  1948
                            ^ ") is not a variable")
wenzelm@22567
  1949
                        else ()
wenzelm@39046
  1950
                      (* split the constructors into those occuring before/after *)
wenzelm@39046
  1951
                      (* 'Const (s, T)'                                          *)
wenzelm@39046
  1952
                      val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
wenzelm@39046
  1953
                        not (cname = s andalso Sign.typ_instance thy (T,
wenzelm@39046
  1954
                          map (typ_of_dtyp descr typ_assoc) ctypes
wenzelm@39046
  1955
                            ---> Type (s', Ts')))) constrs
wenzelm@39046
  1956
                    in
wenzelm@39046
  1957
                      case constrs2 of
wenzelm@39046
  1958
                        [] =>
wenzelm@39046
  1959
                          (* 'Const (s, T)' is not a constructor of this datatype *)
wenzelm@39046
  1960
                          NONE
blanchet@46096
  1961
                      | (_, ctypes)::_ =>
wenzelm@39046
  1962
                          let
wenzelm@55507
  1963
                            (* only /recursive/ IDTs have an associated depth *)
wenzelm@39046
  1964
                            val depth = AList.lookup (op =) typs (Type (s', Ts'))
wenzelm@39046
  1965
                            (* this should never happen: at depth 0, this IDT fragment *)
wenzelm@39046
  1966
                            (* is definitely empty, and in this case we don't need to  *)
wenzelm@39046
  1967
                            (* interpret its constructors                              *)
wenzelm@39046
  1968
                            val _ = (case depth of SOME 0 =>
wenzelm@39046
  1969
                                raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1970
                                  "depth is 0")
wenzelm@39046
  1971
                              | _ => ())
wenzelm@39046
  1972
                            val typs' = (case depth of NONE => typs | SOME n =>
wenzelm@39046
  1973
                              AList.update (op =) (Type (s', Ts'), n-1) typs)
wenzelm@39046
  1974
                            (* elements of the datatype come before elements generated *)
wenzelm@39046
  1975
                            (* by 'Const (s, T)' iff they are generated by a           *)
wenzelm@39046
  1976
                            (* constructor in constrs1                                 *)
wenzelm@39049
  1977
                            val offset = size_of_dtyp ctxt typs' descr typ_assoc constrs1
wenzelm@39046
  1978
                            (* compute the total (current) size of the datatype *)
wenzelm@39046
  1979
                            val total = offset +
wenzelm@39049
  1980
                              size_of_dtyp ctxt typs' descr typ_assoc constrs2
wenzelm@39046
  1981
                            (* sanity check *)
wenzelm@39049
  1982
                            val _ = if total <> size_of_type ctxt (typs, [])
wenzelm@39046
  1983
                              (Type (s', Ts')) then
wenzelm@33246
  1984
                                raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  1985
                                  "total is not equal to current size")
wenzelm@39046
  1986
                              else ()
wenzelm@39046
  1987
                            (* returns an interpretation where everything is mapped to *)
wenzelm@39046
  1988
                            (* an "undefined" element of the datatype                  *)
wenzelm@39046
  1989
                            fun make_undef [] = Leaf (replicate total False)
wenzelm@39046
  1990
                              | make_undef (d::ds) =
wenzelm@39046
  1991
                                  let
wenzelm@39046
  1992
                                    (* compute the current size of the type 'd' *)
wenzelm@39046
  1993
                                    val dT   = typ_of_dtyp descr typ_assoc d
wenzelm@39049
  1994
                                    val size = size_of_type ctxt (typs, []) dT
wenzelm@39046
  1995
                                  in
wenzelm@39046
  1996
                                    Node (replicate size (make_undef ds))
wenzelm@39046
  1997
                                  end
wenzelm@39046
  1998
                            (* returns the interpretation for a constructor *)
wenzelm@39046
  1999
                            fun make_constr [] offset =
wenzelm@39046
  2000
                                  if offset < total then
wenzelm@39046
  2001
                                    (Leaf (replicate offset False @ True ::
wenzelm@39046
  2002
                                      (replicate (total - offset - 1) False)), offset + 1)
wenzelm@39046
  2003
                                  else
wenzelm@39046
  2004
                                    raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2005
                                      "offset >= total")
wenzelm@39046
  2006
                              | make_constr (d::ds) offset =
wenzelm@39046
  2007
                                  let
wenzelm@39046
  2008
                                    val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39046
  2009
                                    (* compute canonical term representations for all   *)
wenzelm@39046
  2010
                                    (* elements of the type 'd' (with the reduced depth *)
wenzelm@39046
  2011
                                    (* for the IDT)                                     *)
wenzelm@39046
  2012
                                    val terms' = canonical_terms typs' dT
wenzelm@39046
  2013
                                    (* sanity check *)
wenzelm@39046
  2014
                                    val _ =
wenzelm@39049
  2015
                                      if length terms' <> size_of_type ctxt (typs', []) dT
wenzelm@39046
  2016
                                      then
wenzelm@39046
  2017
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2018
                                          "length of terms' is not equal to old size")
wenzelm@39046
  2019
                                      else ()
wenzelm@39046
  2020
                                    (* compute canonical term representations for all   *)
wenzelm@39046
  2021
                                    (* elements of the type 'd' (with the current depth *)
wenzelm@39046
  2022
                                    (* for the IDT)                                     *)
wenzelm@39046
  2023
                                    val terms = canonical_terms typs dT
wenzelm@39046
  2024
                                    (* sanity check *)
wenzelm@39046
  2025
                                    val _ =
wenzelm@39049
  2026
                                      if length terms <> size_of_type ctxt (typs, []) dT
wenzelm@39046
  2027
                                      then
wenzelm@39046
  2028
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2029
                                          "length of terms is not equal to current size")
wenzelm@39046
  2030
                                      else ()
wenzelm@39046
  2031
                                    (* sanity check *)
wenzelm@39046
  2032
                                    val _ =
wenzelm@39046
  2033
                                      if length terms < length terms' then
wenzelm@39046
  2034
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2035
                                          "current size is less than old size")
wenzelm@39046
  2036
                                      else ()
wenzelm@39046
  2037
                                    (* sanity check: every element of terms' must also be *)
wenzelm@39046
  2038
                                    (*               present in terms                     *)
wenzelm@39046
  2039
                                    val _ =
wenzelm@39046
  2040
                                      if forall (member (op =) terms) terms' then ()
wenzelm@39046
  2041
                                      else
wenzelm@39046
  2042
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2043
                                          "element has disappeared")
wenzelm@39046
  2044
                                    (* sanity check: the order on elements of terms' is    *)
wenzelm@39046
  2045
                                    (*               the same in terms, for those elements *)
wenzelm@39046
  2046
                                    val _ =
wenzelm@39046
  2047
                                      let
wenzelm@39046
  2048
                                        fun search (x::xs) (y::ys) =
wenzelm@39046
  2049
                                              if x = y then search xs ys else search (x::xs) ys
blanchet@46096
  2050
                                          | search (_::_) [] =
wenzelm@39046
  2051
                                              raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39046
  2052
                                                "element order not preserved")
wenzelm@39046
  2053
                                          | search [] _ = ()
wenzelm@39046
  2054
                                      in search terms' terms end
wenzelm@39046
  2055
                                    val (intrs, new_offset) =
wenzelm@39046
  2056
                                      fold_map (fn t_elem => fn off =>
wenzelm@39046
  2057
                                        (* if 't_elem' existed at the previous depth,    *)
wenzelm@39046
  2058
                                        (* proceed recursively, otherwise map the entire *)
wenzelm@39046
  2059
                                        (* subtree to "undefined"                        *)
wenzelm@39046
  2060
                                        if member (op =) terms' t_elem then
wenzelm@39046
  2061
                                          make_constr ds off
wenzelm@39046
  2062
                                        else
wenzelm@39046
  2063
                                          (make_undef ds, off))
wenzelm@39046
  2064
                                      terms offset
wenzelm@39046
  2065
                                  in
wenzelm@39046
  2066
                                    (Node intrs, new_offset)
wenzelm@39046
  2067
                                  end
wenzelm@39046
  2068
                          in
wenzelm@39046
  2069
                            SOME (fst (make_constr ctypes offset), model, args)
wenzelm@39046
  2070
                          end
wenzelm@22567
  2071
                    end
wenzelm@39046
  2072
                | NONE =>  (* body type is not an inductive datatype *)
wenzelm@39046
  2073
                    NONE)
wenzelm@39046
  2074
            | _ =>  (* body type is a (free or schematic) type variable *)
wenzelm@39046
  2075
              NONE)
wenzelm@39046
  2076
        | _ =>  (* term is not a constant *)
wenzelm@22567
  2077
          NONE)
wenzelm@22567
  2078
  end;
webertj@14807
  2079
wenzelm@39046
  2080
(* Difficult code ahead.  Make sure you understand the                *)
wenzelm@39046
  2081
(* 'IDT_constructor_interpreter' and the order in which it enumerates *)
wenzelm@39046
  2082
(* elements of an IDT before you try to understand this function.     *)
webertj@15547
  2083
wenzelm@39049
  2084
fun IDT_recursion_interpreter ctxt model args t =
wenzelm@39049
  2085
  let
wenzelm@42361
  2086
    val thy = Proof_Context.theory_of ctxt
wenzelm@39049
  2087
  in
wenzelm@39049
  2088
    (* careful: here we descend arbitrarily deep into 't', possibly before *)
wenzelm@39049
  2089
    (* any other interpreter for atomic terms has had a chance to look at  *)
wenzelm@39049
  2090
    (* 't'                                                                 *)
wenzelm@39049
  2091
    case strip_comb t of
wenzelm@39049
  2092
      (Const (s, T), params) =>
wenzelm@39049
  2093
        (* iterate over all datatypes in 'thy' *)
wenzelm@39049
  2094
        Symtab.fold (fn (_, info) => fn result =>
wenzelm@39049
  2095
          case result of
wenzelm@39049
  2096
            SOME _ =>
wenzelm@39049
  2097
              result  (* just keep 'result' *)
wenzelm@39049
  2098
          | NONE =>
wenzelm@39049
  2099
              if member (op =) (#rec_names info) s then
wenzelm@39049
  2100
                (* we do have a recursion operator of one of the (mutually *)
wenzelm@39049
  2101
                (* recursive) datatypes given by 'info'                    *)
wenzelm@39049
  2102
                let
wenzelm@39049
  2103
                  (* number of all constructors, including those of different  *)
wenzelm@39049
  2104
                  (* (mutually recursive) datatypes within the same descriptor *)
wenzelm@39049
  2105
                  val mconstrs_count =
wenzelm@39049
  2106
                    Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
wenzelm@39049
  2107
                in
wenzelm@39049
  2108
                  if mconstrs_count < length params then
wenzelm@39049
  2109
                    (* too many actual parameters; for now we'll use the *)
wenzelm@39049
  2110
                    (* 'stlc_interpreter' to strip off one application   *)
wenzelm@39049
  2111
                    NONE
wenzelm@39049
  2112
                  else if mconstrs_count > length params then
wenzelm@39049
  2113
                    (* too few actual parameters; we use eta expansion          *)
wenzelm@39049
  2114
                    (* Note that the resulting expansion of lambda abstractions *)
wenzelm@39049
  2115
                    (* by the 'stlc_interpreter' may be rather slow (depending  *)
wenzelm@39049
  2116
                    (* on the argument types and the size of the IDT, of        *)
wenzelm@39049
  2117
                    (* course).                                                 *)
wenzelm@39049
  2118
                    SOME (interpret ctxt model args (eta_expand t
wenzelm@39049
  2119
                      (mconstrs_count - length params)))
wenzelm@39049
  2120
                  else  (* mconstrs_count = length params *)
wenzelm@39049
  2121
                    let
wenzelm@39049
  2122
                      (* interpret each parameter separately *)
wenzelm@39049
  2123
                      val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
wenzelm@39049
  2124
                        let
wenzelm@39049
  2125
                          val (i, m', a') = interpret ctxt m a p
wenzelm@39049
  2126
                        in
wenzelm@39049
  2127
                          (i, (m', a'))
wenzelm@39049
  2128
                        end) params (model, args)
wenzelm@39049
  2129
                      val (typs, _) = model'
wenzelm@39049
  2130
                      (* 'index' is /not/ necessarily the index of the IDT that *)
wenzelm@39049
  2131
                      (* the recursion operator is associated with, but merely  *)
wenzelm@39049
  2132
                      (* the index of some mutually recursive IDT               *)
wenzelm@39049
  2133
                      val index         = #index info
wenzelm@39049
  2134
                      val descr         = #descr info
wenzelm@39049
  2135
                      val (_, dtyps, _) = the (AList.lookup (op =) descr index)
wenzelm@39049
  2136
                      (* sanity check: we assume that the order of constructors *)
wenzelm@39049
  2137
                      (*               in 'descr' is the same as the order of   *)
wenzelm@39049
  2138
                      (*               corresponding parameters, otherwise the  *)
wenzelm@39049
  2139
                      (*               association code below won't match the   *)
wenzelm@39049
  2140
                      (*               right constructors/parameters; we also   *)
wenzelm@39049
  2141
                      (*               assume that the order of recursion       *)
wenzelm@39049
  2142
                      (*               operators in '#rec_names info' is the    *)
wenzelm@39049
  2143
                      (*               same as the order of corresponding       *)
wenzelm@39049
  2144
                      (*               datatypes in 'descr'                     *)
wenzelm@39049
  2145
                      val _ = if map fst descr <> (0 upto (length descr - 1)) then
wenzelm@39049
  2146
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2147
                            "order of constructors and corresponding parameters/" ^
wenzelm@39049
  2148
                              "recursion operators and corresponding datatypes " ^
wenzelm@39049
  2149
                              "different?")
wenzelm@39049
  2150
                        else ()
wenzelm@39049
  2151
                      (* sanity check: every element in 'dtyps' must be a *)
wenzelm@39049
  2152
                      (*               'DtTFree'                          *)
wenzelm@39049
  2153
                      val _ =
wenzelm@39049
  2154
                        if Library.exists (fn d =>
blanchet@58120
  2155
                          case d of Old_Datatype_Aux.DtTFree _ => false
wenzelm@39049
  2156
                                  | _ => true) dtyps
wenzelm@39049
  2157
                        then
wenzelm@39049
  2158
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2159
                            "datatype argument is not a variable")
wenzelm@39049
  2160
                        else ()
wenzelm@39049
  2161
                      (* the type of a recursion operator is *)
wenzelm@39049
  2162
                      (* [T1, ..., Tn, IDT] ---> Tresult     *)
wenzelm@42364
  2163
                      val IDT = nth (binder_types T) mconstrs_count
wenzelm@39049
  2164
                      (* by our assumption on the order of recursion operators *)
wenzelm@39049
  2165
                      (* and datatypes, this is the index of the datatype      *)
wenzelm@39049
  2166
                      (* corresponding to the given recursion operator         *)
wenzelm@39049
  2167
                      val idt_index = find_index (fn s' => s' = s) (#rec_names info)
wenzelm@39049
  2168
                      (* mutually recursive types must have the same type   *)
wenzelm@39049
  2169
                      (* parameters, unless the mutual recursion comes from *)
wenzelm@39049
  2170
                      (* indirect recursion                                 *)
wenzelm@39049
  2171
                      fun rec_typ_assoc acc [] = acc
wenzelm@39049
  2172
                        | rec_typ_assoc acc ((d, T)::xs) =
wenzelm@39049
  2173
                            (case AList.lookup op= acc d of
wenzelm@39049
  2174
                              NONE =>
wenzelm@39049
  2175
                                (case d of
blanchet@58120
  2176
                                  Old_Datatype_Aux.DtTFree _ =>
wenzelm@39049
  2177
                                  (* add the association, proceed *)
wenzelm@39049
  2178
                                  rec_typ_assoc ((d, T)::acc) xs
blanchet@58120
  2179
                                | Old_Datatype_Aux.DtType (s, ds) =>
wenzelm@39049
  2180
                                    let
wenzelm@39049
  2181
                                      val (s', Ts) = dest_Type T
wenzelm@39049
  2182
                                    in
wenzelm@39049
  2183
                                      if s=s' then
wenzelm@39049
  2184
                                        rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
wenzelm@39049
  2185
                                      else
wenzelm@39049
  2186
                                        raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2187
                                          "DtType/Type mismatch")
wenzelm@39049
  2188
                                    end
blanchet@58120
  2189
                                | Old_Datatype_Aux.DtRec i =>
wenzelm@39049
  2190
                                    let
wenzelm@39049
  2191
                                      val (_, ds, _) = the (AList.lookup (op =) descr i)
wenzelm@39049
  2192
                                      val (_, Ts)    = dest_Type T
wenzelm@39049
  2193
                                    in
wenzelm@39046
  2194
                                      rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
wenzelm@39049
  2195
                                    end)
wenzelm@39049
  2196
                            | SOME T' =>
wenzelm@39049
  2197
                                if T=T' then
wenzelm@39049
  2198
                                  (* ignore the association since it's already *)
wenzelm@39049
  2199
                                  (* present, proceed                          *)
wenzelm@39049
  2200
                                  rec_typ_assoc acc xs
wenzelm@39049
  2201
                                else
wenzelm@39049
  2202
                                  raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2203
                                    "different type associations for the same dtyp"))
wenzelm@39049
  2204
                      val typ_assoc = filter
blanchet@58120
  2205
                        (fn (Old_Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
wenzelm@39049
  2206
                        (rec_typ_assoc []
wenzelm@39049
  2207
                          (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
wenzelm@39049
  2208
                      (* sanity check: typ_assoc must associate types to the   *)
wenzelm@39049
  2209
                      (*               elements of 'dtyps' (and only to those) *)
wenzelm@39049
  2210
                      val _ =
wenzelm@39049
  2211
                        if not (eq_set (op =) (dtyps, map fst typ_assoc))
wenzelm@39049
  2212
                        then
wenzelm@39049
  2213
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2214
                            "type association has extra/missing elements")
wenzelm@39049
  2215
                        else ()
wenzelm@39049
  2216
                      (* interpret each constructor in the descriptor (including *)
wenzelm@39049
  2217
                      (* those of mutually recursive datatypes)                  *)
wenzelm@39049
  2218
                      (* (int * interpretation list) list *)
wenzelm@39049
  2219
                      val mc_intrs = map (fn (idx, (_, _, cs)) =>
wenzelm@39046
  2220
                        let
wenzelm@39049
  2221
                          val c_return_typ = typ_of_dtyp descr typ_assoc
blanchet@58120
  2222
                            (Old_Datatype_Aux.DtRec idx)
wenzelm@39046
  2223
                        in
wenzelm@39049
  2224
                          (idx, map (fn (cname, cargs) =>
wenzelm@39049
  2225
                            (#1 o interpret ctxt (typs, []) {maxvars=0,
wenzelm@39049
  2226
                              def_eq=false, next_idx=1, bounds=[],
wenzelm@39049
  2227
                              wellformed=True}) (Const (cname, map (typ_of_dtyp
wenzelm@39049
  2228
                              descr typ_assoc) cargs ---> c_return_typ))) cs)
wenzelm@39049
  2229
                        end) descr
wenzelm@39049
  2230
                      (* associate constructors with corresponding parameters *)
wenzelm@39049
  2231
                      (* (int * (interpretation * interpretation) list) list *)
wenzelm@39049
  2232
                      val (mc_p_intrs, p_intrs') = fold_map
wenzelm@39049
  2233
                        (fn (idx, c_intrs) => fn p_intrs' =>
wenzelm@39046
  2234
                          let
wenzelm@39049
  2235
                            val len = length c_intrs
wenzelm@39046
  2236
                          in
wenzelm@39049
  2237
                            ((idx, c_intrs ~~ List.take (p_intrs', len)),
wenzelm@39049
  2238
                              List.drop (p_intrs', len))
wenzelm@39049
  2239
                          end) mc_intrs p_intrs
wenzelm@39049
  2240
                      (* sanity check: no 'p_intr' may be left afterwards *)
wenzelm@39049
  2241
                      val _ =
wenzelm@39049
  2242
                        if p_intrs' <> [] then
webertj@25014
  2243
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2244
                            "more parameter than constructor interpretations")
wenzelm@39046
  2245
                        else ()
wenzelm@39049
  2246
                      (* The recursion operator, applied to 'mconstrs_count'     *)
wenzelm@39049
  2247
                      (* arguments, is a function that maps every element of the *)
wenzelm@39049
  2248
                      (* inductive datatype to an element of some result type.   *)
wenzelm@39049
  2249
                      (* Recursion operators for mutually recursive IDTs are     *)
wenzelm@39049
  2250
                      (* translated simultaneously.                              *)
wenzelm@39049
  2251
                      (* Since the order on datatype elements is given by an     *)
wenzelm@39049
  2252
                      (* order on constructors (and then by the order on         *)
wenzelm@39049
  2253
                      (* argument tuples), we can simply copy corresponding      *)
wenzelm@39049
  2254
                      (* subtrees from 'p_intrs', in the order in which they are *)
wenzelm@39049
  2255
                      (* given.                                                  *)
wenzelm@39049
  2256
                      fun ci_pi (Leaf xs, pi) =
wenzelm@39049
  2257
                            (* if the constructor does not match the arguments to a *)
wenzelm@39049
  2258
                            (* defined element of the IDT, the corresponding value  *)
wenzelm@39049
  2259
                            (* of the parameter must be ignored                     *)
wenzelm@39049
  2260
                            if List.exists (equal True) xs then [pi] else []
wenzelm@39049
  2261
                        | ci_pi (Node xs, Node ys) = maps ci_pi (xs ~~ ys)
wenzelm@39049
  2262
                        | ci_pi (Node _, Leaf _) =
wenzelm@39049
  2263
                            raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39049
  2264
                              "constructor takes more arguments than the " ^
wenzelm@39049
  2265
                                "associated parameter")
wenzelm@39049
  2266
                      val rec_operators = map (fn (idx, c_p_intrs) =>
wenzelm@39049
  2267
                        (idx, maps ci_pi c_p_intrs)) mc_p_intrs
wenzelm@39049
  2268
                      (* sanity check: every recursion operator must provide as  *)
wenzelm@39049
  2269
                      (*               many values as the corresponding datatype *)
wenzelm@39049
  2270
                      (*               has elements                              *)
wenzelm@39049
  2271
                      val _ = map (fn (idx, intrs) =>
wenzelm@39049
  2272
                        let
</