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