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