src/HOL/Tools/refute.ML
author wenzelm
Thu, 02 Sep 2010 17:12:16 +0200
changeset 39341 4006f5c3f421
parent 39340 cdff476ba39e
child 39347 423b72f2d242
permissions -rw-r--r--
just one refute.ML;
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@14807
    27
wenzelm@33259
    28
  val add_interpreter : string -> (theory -> model -> arguments -> term ->
wenzelm@22567
    29
    (interpretation * model * arguments) option) -> theory -> theory
wenzelm@33259
    30
  val add_printer     : string -> (theory -> model -> typ ->
wenzelm@33259
    31
    interpretation -> (int -> bool) -> term option) -> theory -> theory
webertj@14456
    32
wenzelm@33259
    33
  val interpret : theory -> model -> arguments -> term ->
wenzelm@22567
    34
    (interpretation * model * arguments)
webertj@14456
    35
wenzelm@33259
    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@34117
    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@34117
    51
  val satisfy_term :
blanchet@34117
    52
    theory -> (string * string) list -> term list -> term -> unit
wenzelm@22567
    53
  (* tries to find a model that refutes a formula: *)
blanchet@34117
    54
  val refute_term :
blanchet@34117
    55
    theory -> (string * string) list -> term list -> term -> unit
blanchet@34117
    56
  val refute_goal :
blanchet@34117
    57
    Proof.context -> (string * string) list -> thm -> int -> unit
webertj@14456
    58
wenzelm@22567
    59
  val setup : theory -> theory
webertj@22092
    60
blanchet@29739
    61
(* ------------------------------------------------------------------------- *)
blanchet@29739
    62
(* Additional functions used by Nitpick (to be factored out)                 *)
blanchet@29739
    63
(* ------------------------------------------------------------------------- *)
blanchet@29739
    64
wenzelm@33259
    65
  val close_form : term -> term
wenzelm@33259
    66
  val get_classdef : theory -> string -> (string * term) option
wenzelm@33259
    67
  val norm_rhs : term -> term
wenzelm@33259
    68
  val get_def : theory -> string * typ -> (string * term) option
wenzelm@33259
    69
  val get_typedef : theory -> typ -> (string * term) option
wenzelm@33259
    70
  val is_IDT_constructor : theory -> string * typ -> bool
wenzelm@33259
    71
  val is_IDT_recursor : theory -> string * typ -> bool
wenzelm@33259
    72
  val is_const_of_class: theory -> string * typ -> bool
wenzelm@33259
    73
  val string_of_typ : typ -> string
wenzelm@33259
    74
  val typ_of_dtyp : Datatype.descr -> (Datatype.dtyp * typ) list -> Datatype.dtyp -> typ
wenzelm@39339
    75
end;
wenzelm@39339
    76
webertj@14456
    77
webertj@14456
    78
structure Refute : REFUTE =
webertj@14456
    79
struct
webertj@14456
    80
wenzelm@39339
    81
open PropLogic;
webertj@14456
    82
wenzelm@39339
    83
(* We use 'REFUTE' only for internal error conditions that should    *)
wenzelm@39339
    84
(* never occur in the first place (i.e. errors caused by bugs in our *)
wenzelm@39339
    85
(* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
wenzelm@39339
    86
(* 'error'.                                                          *)
wenzelm@39339
    87
exception REFUTE of string * string;  (* ("in function", "cause") *)
webertj@14350
    88
wenzelm@39339
    89
(* should be raised by an interpreter when more variables would be *)
wenzelm@39339
    90
(* required than allowed by 'maxvars'                              *)
wenzelm@39339
    91
exception MAXVARS_EXCEEDED;
wenzelm@39339
    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@39339
   103
datatype 'a tree =
wenzelm@39339
   104
    Leaf of 'a
wenzelm@39339
   105
  | Node of ('a tree) list;
webertj@14350
   106
wenzelm@39339
   107
(* ('a -> 'b) -> 'a tree -> 'b tree *)
webertj@14350
   108
wenzelm@39339
   109
fun tree_map f tr =
wenzelm@39339
   110
  case tr of
wenzelm@39339
   111
    Leaf x  => Leaf (f x)
wenzelm@39339
   112
  | Node xs => Node (map (tree_map f) xs);
webertj@14350
   113
wenzelm@39339
   114
(* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
webertj@14350
   115
wenzelm@39339
   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@39339
   124
(* 'a tree * 'b tree -> ('a * 'b) tree *)
webertj@14350
   125
wenzelm@39339
   126
fun tree_pair (t1, t2) =
wenzelm@39339
   127
  case t1 of
wenzelm@39339
   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@39339
   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@30315
   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@34117
   159
(* "no_assms"    bool    If "true", assumptions in structured proofs are     *)
blanchet@34117
   160
(*                       not considered.                                     *)
blanchet@30315
   161
(* "expect"      string  Expected result ("genuine", "potential", "none", or *)
blanchet@34117
   162
(*                       "unknown").                                         *)
webertj@14807
   163
(* ------------------------------------------------------------------------- *)
webertj@14807
   164
wenzelm@39339
   165
type params =
wenzelm@39339
   166
  {
wenzelm@39339
   167
    sizes    : (string * int) list,
wenzelm@39339
   168
    minsize  : int,
wenzelm@39339
   169
    maxsize  : int,
wenzelm@39339
   170
    maxvars  : int,
wenzelm@39339
   171
    maxtime  : int,
wenzelm@39339
   172
    satsolver: string,
wenzelm@39339
   173
    no_assms : bool,
wenzelm@39339
   174
    expect   : string
wenzelm@39339
   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@39339
   182
type interpretation =
wenzelm@39339
   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@39339
   190
type model =
wenzelm@39339
   191
  (typ * int) list * (term * interpretation) list;
webertj@14350
   192
webertj@14350
   193
(* ------------------------------------------------------------------------- *)
webertj@14456
   194
(* arguments: additional arguments required during interpretation of terms   *)
webertj@14456
   195
(* ------------------------------------------------------------------------- *)
webertj@14807
   196
wenzelm@39339
   197
type arguments =
wenzelm@39339
   198
  {
wenzelm@39339
   199
    (* just passed unchanged from 'params': *)
wenzelm@39339
   200
    maxvars   : int,
wenzelm@39339
   201
    (* whether to use 'make_equality' or 'make_def_equality': *)
wenzelm@39339
   202
    def_eq    : bool,
wenzelm@39339
   203
    (* the following may change during the translation: *)
wenzelm@39339
   204
    next_idx  : int,
wenzelm@39339
   205
    bounds    : interpretation list,
wenzelm@39339
   206
    wellformed: prop_formula
wenzelm@39339
   207
  };
webertj@14456
   208
webertj@14456
   209
wenzelm@39339
   210
structure RefuteData = Theory_Data
wenzelm@39339
   211
(
wenzelm@39339
   212
  type T =
wenzelm@39339
   213
    {interpreters: (string * (theory -> model -> arguments -> term ->
wenzelm@39339
   214
      (interpretation * model * arguments) option)) list,
wenzelm@39339
   215
     printers: (string * (theory -> model -> typ -> interpretation ->
wenzelm@39339
   216
      (int -> bool) -> term option)) list,
wenzelm@39339
   217
     parameters: string Symtab.table};
wenzelm@39339
   218
  val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
wenzelm@39339
   219
  val extend = I;
wenzelm@39339
   220
  fun merge
wenzelm@39339
   221
    ({interpreters = in1, printers = pr1, parameters = pa1},
wenzelm@39339
   222
     {interpreters = in2, printers = pr2, parameters = pa2}) : T =
wenzelm@39339
   223
    {interpreters = AList.merge (op =) (K true) (in1, in2),
wenzelm@39339
   224
     printers = AList.merge (op =) (K true) (pr1, pr2),
wenzelm@39339
   225
     parameters = Symtab.merge (op=) (pa1, pa2)};
wenzelm@39339
   226
);
webertj@14456
   227
webertj@14456
   228
webertj@14456
   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@39339
   235
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
   236
  (interpretation * model * arguments) *)
webertj@14350
   237
wenzelm@39339
   238
fun interpret thy model args t =
wenzelm@39339
   239
  case get_first (fn (_, f) => f thy model args t)
wenzelm@22567
   240
      (#interpreters (RefuteData.get thy)) of
wenzelm@39339
   241
    NONE => raise REFUTE ("interpret",
wenzelm@39339
   242
      "no interpreter for term " ^ quote (Syntax.string_of_term_global thy t))
wenzelm@39339
   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@14456
   249
wenzelm@39339
   250
(* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
wenzelm@39339
   251
  Term.term *)
webertj@14456
   252
wenzelm@39339
   253
fun print thy model T intr assignment =
wenzelm@39339
   254
  case get_first (fn (_, f) => f thy model T intr assignment)
wenzelm@22567
   255
      (#printers (RefuteData.get thy)) of
wenzelm@39339
   256
    NONE => raise REFUTE ("print",
wenzelm@39339
   257
      "no printer for type " ^ quote (Syntax.string_of_typ_global thy T))
wenzelm@39339
   258
  | SOME x => x;
webertj@14350
   259
webertj@14350
   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@39339
   266
(* theory -> model -> (int -> bool) -> string *)
webertj@14807
   267
wenzelm@39339
   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@39339
   303
(* string -> (theory -> model -> arguments -> Term.term ->
wenzelm@39339
   304
  (interpretation * model * arguments) option) -> theory -> theory *)
webertj@14456
   305
wenzelm@39339
   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@39339
   311
      NONE => RefuteData.put {interpreters = (name, f) :: interpreters,
wenzelm@39339
   312
        printers = printers, parameters = parameters} thy
wenzelm@22567
   313
    | SOME _ => error ("Interpreter " ^ name ^ " already declared")
wenzelm@22567
   314
  end;
webertj@14456
   315
wenzelm@39339
   316
(* string -> (theory -> model -> Term.typ -> interpretation ->
wenzelm@39339
   317
  (int -> bool) -> Term.term option) -> theory -> theory *)
webertj@14456
   318
wenzelm@39339
   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@39339
   324
      NONE => RefuteData.put {interpreters = interpreters,
wenzelm@39339
   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@39339
   334
(* (string * string) -> theory -> theory *)
webertj@14456
   335
wenzelm@39339
   336
fun set_default_param (name, value) = RefuteData.map 
wenzelm@39339
   337
  (fn {interpreters, printers, parameters} =>
wenzelm@39339
   338
    {interpreters = interpreters, printers = printers,
wenzelm@39339
   339
      parameters = Symtab.update (name, value) parameters});
webertj@14456
   340
webertj@14456
   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@39339
   346
(* theory -> string -> string option *)
webertj@14456
   347
wenzelm@39339
   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@39339
   355
(* theory -> (string * string) list *)
webertj@14456
   356
wenzelm@39339
   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@39339
   365
(* theory -> (string * string) list -> params *)
webertj@14456
   366
wenzelm@39339
   367
fun actual_params thy override =
wenzelm@22567
   368
  let
blanchet@34117
   369
    (* (string * string) list * string -> bool *)
blanchet@34117
   370
    fun read_bool (parms, name) =
blanchet@34117
   371
      case AList.lookup (op =) parms name of
blanchet@34117
   372
        SOME "true" => true
blanchet@34117
   373
      | SOME "false" => false
blanchet@34117
   374
      | SOME s => error ("parameter " ^ quote name ^
wenzelm@39339
   375
          " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
blanchet@34117
   376
      | NONE   => error ("parameter " ^ quote name ^
blanchet@34117
   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@39339
   381
        SOME s =>
wenzelm@39339
   382
          (case Int.fromString s of
wenzelm@39339
   383
            SOME i => i
wenzelm@39339
   384
          | NONE   => error ("parameter " ^ quote name ^
wenzelm@39339
   385
            " (value is " ^ quote s ^ ") must be an integer value"))
wenzelm@39339
   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@39339
   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@39339
   398
    val minsize = read_int (allparams, "minsize")
wenzelm@39339
   399
    val maxsize = read_int (allparams, "maxsize")
wenzelm@39339
   400
    val maxvars = read_int (allparams, "maxvars")
wenzelm@39339
   401
    val maxtime = read_int (allparams, "maxtime")
wenzelm@22567
   402
    (* string *)
wenzelm@22567
   403
    val satsolver = read_string (allparams, "satsolver")
blanchet@34117
   404
    val no_assms = read_bool (allparams, "no_assms")
blanchet@30315
   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@39339
   411
    val sizes = map_filter
wenzelm@22567
   412
      (fn (name, value) => Option.map (pair name) (Int.fromString value))
wenzelm@33325
   413
      (filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
wenzelm@22567
   414
        andalso name<>"maxvars" andalso name<>"maxtime"
blanchet@34117
   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@34117
   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@39339
   426
fun typ_of_dtyp descr typ_assoc (Datatype_Aux.DtTFree a) =
wenzelm@39339
   427
      (* replace a 'DtTFree' variable by the associated type *)
wenzelm@39339
   428
      the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
wenzelm@39339
   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@39339
   431
  | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
wenzelm@39339
   432
      let
wenzelm@39339
   433
        val (s, ds, _) = the (AList.lookup (op =) descr i)
wenzelm@39339
   434
      in
wenzelm@39339
   435
        Type (s, map (typ_of_dtyp descr typ_assoc) ds)
wenzelm@39339
   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@39339
   442
(* Term.term -> Term.term *)
webertj@21985
   443
wenzelm@39339
   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@33262
   449
    fold (fn ((x, i), T) => fn t' =>
wenzelm@33262
   450
      Term.all T $ Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
wenzelm@22567
   451
  end;
webertj@21985
   452
blanchet@36553
   453
val monomorphic_term = Sledgehammer_Util.monomorphic_term
blanchet@36553
   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@39339
   461
(* theory -> string * Term.typ -> bool *)
webertj@21985
   462
wenzelm@39339
   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@36677
   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@39339
   477
(* theory -> string * Term.typ -> bool *)
webertj@21985
   478
wenzelm@39339
   479
fun is_IDT_constructor thy (s, T) =
wenzelm@39339
   480
  (case body_type T of
wenzelm@39339
   481
    Type (s', _) =>
haftmann@31784
   482
      (case Datatype.get_constrs thy s' of
wenzelm@22567
   483
        SOME constrs =>
wenzelm@39339
   484
          List.exists (fn (cname, cty) =>
wenzelm@39339
   485
            cname = s andalso Sign.typ_instance thy (T, cty)) constrs
wenzelm@39339
   486
      | NONE => false)
wenzelm@39339
   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@39339
   494
(* theory -> string * Term.typ -> bool *)
webertj@21985
   495
wenzelm@39339
   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@36677
   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@39339
   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@39339
   513
      | lambda v t = raise TERM ("lambda", [v, t])
blanchet@30275
   514
    val (lhs, rhs) = Logic.dest_equals eqn
wenzelm@39339
   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@37380
   521
(* get_def: looks up the definition of a constant                            *)
webertj@21985
   522
(* ------------------------------------------------------------------------- *)
webertj@21985
   523
wenzelm@39339
   524
(* theory -> string * Term.typ -> (string * Term.term) option *)
webertj@21985
   525
wenzelm@39339
   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@39339
   531
          (let
wenzelm@39339
   532
            val (lhs, _) = Logic.dest_equals ax  (* equations only *)
wenzelm@39339
   533
            val c        = Term.head_of lhs
wenzelm@39339
   534
            val (s', T') = Term.dest_Const c
wenzelm@22567
   535
          in
wenzelm@39339
   536
            if s=s' then
wenzelm@39339
   537
              let
wenzelm@39339
   538
                val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
wenzelm@39339
   539
                val ax'      = monomorphic_term typeSubs ax
wenzelm@39339
   540
                val rhs      = norm_rhs ax'
wenzelm@39339
   541
              in
wenzelm@39339
   542
                SOME (axname, rhs)
wenzelm@39339
   543
              end
wenzelm@39339
   544
            else
wenzelm@39339
   545
              get_def_ax axioms
wenzelm@39339
   546
          end handle ERROR _         => get_def_ax axioms
wenzelm@39339
   547
                   | TERM _          => get_def_ax axioms
wenzelm@39339
   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@39339
   557
(* theory -> Term.typ -> (string * Term.term) option *)
webertj@21985
   558
wenzelm@39339
   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@39339
   564
          (let
wenzelm@39339
   565
            (* Term.term -> Term.typ option *)
wenzelm@39339
   566
            fun type_of_type_definition (Const (s', T')) =
wenzelm@39339
   567
                  if s'= @{const_name type_definition} then
wenzelm@39339
   568
                    SOME T'
wenzelm@39339
   569
                  else
wenzelm@39339
   570
                    NONE
wenzelm@39339
   571
              | type_of_type_definition (Free _) = NONE
wenzelm@39339
   572
              | type_of_type_definition (Var _) = NONE
wenzelm@39339
   573
              | type_of_type_definition (Bound _) = NONE
wenzelm@39339
   574
              | type_of_type_definition (Abs (_, _, body)) =
wenzelm@39339
   575
                  type_of_type_definition body
wenzelm@39339
   576
              | type_of_type_definition (t1 $ t2) =
wenzelm@39339
   577
                  (case type_of_type_definition t1 of
wenzelm@39339
   578
                    SOME x => SOME x
wenzelm@39339
   579
                  | NONE => type_of_type_definition t2)
wenzelm@22567
   580
          in
wenzelm@39339
   581
            case type_of_type_definition ax of
wenzelm@39339
   582
              SOME T' =>
wenzelm@39339
   583
                let
wenzelm@39339
   584
                  val T''      = (domain_type o domain_type) T'
wenzelm@39339
   585
                  val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
wenzelm@39339
   586
                in
wenzelm@39339
   587
                  SOME (axname, monomorphic_term typeSubs ax)
wenzelm@39339
   588
                end
wenzelm@39339
   589
            | NONE => get_typedef_ax axioms
wenzelm@39339
   590
          end handle ERROR _         => get_typedef_ax axioms
wenzelm@39339
   591
                   | TERM _          => get_typedef_ax axioms
wenzelm@39339
   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@39339
   602
(* theory -> string -> (string * Term.term) option *)
webertj@21985
   603
wenzelm@39339
   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@39339
   620
(* theory -> Term.term -> Term.term *)
webertj@21985
   621
wenzelm@39339
   622
(* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
wenzelm@39339
   623
(*       normalization; this would save some unfolding for terms where    *)
wenzelm@39339
   624
(*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
wenzelm@39339
   625
(*       the other hand, this would cause additional work for terms where *)
wenzelm@39339
   626
(*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
webertj@21985
   627
wenzelm@39339
   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@29739
   634
        Const (@{const_name all}, _) => t
blanchet@29739
   635
      | Const (@{const_name "=="}, _) => t
blanchet@29739
   636
      | Const (@{const_name "==>"}, _) => t
blanchet@29739
   637
      | Const (@{const_name TYPE}, _) => t  (* axiomatic type classes *)
wenzelm@22567
   638
      (* HOL *)
blanchet@29739
   639
      | Const (@{const_name Trueprop}, _) => t
blanchet@29739
   640
      | Const (@{const_name Not}, _) => t
wenzelm@22567
   641
      | (* redundant, since 'True' is also an IDT constructor *)
blanchet@29739
   642
        Const (@{const_name True}, _) => t
wenzelm@22567
   643
      | (* redundant, since 'False' is also an IDT constructor *)
blanchet@29739
   644
        Const (@{const_name False}, _) => t
blanchet@29739
   645
      | Const (@{const_name undefined}, _) => t
blanchet@29739
   646
      | Const (@{const_name The}, _) => t
blanchet@29757
   647
      | Const (@{const_name Hilbert_Choice.Eps}, _) => t
blanchet@29739
   648
      | Const (@{const_name All}, _) => t
blanchet@29739
   649
      | Const (@{const_name Ex}, _) => t
haftmann@39093
   650
      | Const (@{const_name HOL.eq}, _) => t
haftmann@39028
   651
      | Const (@{const_name HOL.conj}, _) => t
haftmann@39028
   652
      | Const (@{const_name HOL.disj}, _) => t
haftmann@39019
   653
      | Const (@{const_name HOL.implies}, _) => t
wenzelm@22567
   654
      (* sets *)
blanchet@29739
   655
      | Const (@{const_name Collect}, _) => t
haftmann@37677
   656
      | Const (@{const_name Set.member}, _) => t
wenzelm@22567
   657
      (* other optimizations *)
blanchet@29757
   658
      | Const (@{const_name Finite_Set.card}, _) => t
blanchet@29757
   659
      | Const (@{const_name Finite_Set.finite}, _) => t
haftmann@37363
   660
      | Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
wenzelm@39339
   661
          Type ("fun", [@{typ nat}, @{typ bool}])])) => t
haftmann@37363
   662
      | Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
wenzelm@39339
   663
          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
haftmann@37363
   664
      | Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
wenzelm@39339
   665
          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
haftmann@37363
   666
      | Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
wenzelm@39339
   667
          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
blanchet@29757
   668
      | Const (@{const_name List.append}, _) => t
blanchet@36130
   669
(* UNSOUND
blanchet@29739
   670
      | Const (@{const_name lfp}, _) => t
blanchet@29739
   671
      | Const (@{const_name gfp}, _) => t
blanchet@36130
   672
*)
blanchet@29757
   673
      | Const (@{const_name fst}, _) => t
blanchet@29757
   674
      | Const (@{const_name snd}, _) => t
wenzelm@22567
   675
      (* simply-typed lambda calculus *)
wenzelm@22567
   676
      | Const (s, T) =>
wenzelm@39339
   677
          (if is_IDT_constructor thy (s, T)
wenzelm@39339
   678
            orelse is_IDT_recursor thy (s, T) then
wenzelm@39339
   679
            t  (* do not unfold IDT constructors/recursors *)
wenzelm@39339
   680
          (* unfold the constant if there is a defining equation *)
wenzelm@39339
   681
          else
wenzelm@39339
   682
            case get_def thy (s, T) of
wenzelm@39339
   683
              SOME (axname, rhs) =>
wenzelm@39339
   684
              (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
wenzelm@39339
   685
              (* occurs on the right-hand side of the equation, i.e. in  *)
wenzelm@39339
   686
              (* 'rhs', we must not use this equation to unfold, because *)
wenzelm@39339
   687
              (* that would loop.  Here would be the right place to      *)
wenzelm@39339
   688
              (* check this.  However, getting this really right seems   *)
wenzelm@39339
   689
              (* difficult because the user may state arbitrary axioms,  *)
wenzelm@39339
   690
              (* which could interact with overloading to create loops.  *)
wenzelm@39339
   691
              ((*tracing (" unfolding: " ^ axname);*)
wenzelm@39339
   692
               unfold_loop rhs)
wenzelm@39339
   693
            | NONE => t)
wenzelm@39339
   694
      | Free _ => t
wenzelm@39339
   695
      | Var _ => t
wenzelm@39339
   696
      | Bound _ => t
wenzelm@22567
   697
      | Abs (s, T, body) => Abs (s, T, unfold_loop body)
wenzelm@39339
   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@39339
   709
(* Note: to make the collection of axioms more easily extensible, this    *)
wenzelm@39339
   710
(*       function could be based on user-supplied "axiom collectors",     *)
wenzelm@39339
   711
(*       similar to 'interpret'/interpreters or 'print'/printers          *)
webertj@14807
   712
wenzelm@39339
   713
(* Note: currently we use "inverse" functions to the definitional         *)
wenzelm@39339
   714
(*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
wenzelm@39339
   715
(*       "typedef", "definition".  A more general approach could consider *)
wenzelm@39339
   716
(*       *every* axiom of the theory and collect it if it has a constant/ *)
wenzelm@39339
   717
(*       type/typeclass in common with the term 't'.                      *)
webertj@21985
   718
wenzelm@39339
   719
(* theory -> Term.term -> Term.term list *)
webertj@14807
   720
wenzelm@39339
   721
(* Which axioms are "relevant" for a particular term/type goes hand in    *)
wenzelm@39339
   722
(* hand with the interpretation of that term/type by its interpreter (see *)
wenzelm@39339
   723
(* way below): if the interpretation respects an axiom anyway, the axiom  *)
wenzelm@39339
   724
(* does not need to be added as a constraint here.                        *)
webertj@14807
   725
wenzelm@39339
   726
(* To avoid collecting the same axiom multiple times, we use an           *)
wenzelm@39339
   727
(* accumulator 'axs' which contains all axioms collected so far.          *)
webertj@14807
   728
wenzelm@39339
   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@33262
   734
      let
wenzelm@33262
   735
        val ax' = unfold_defs thy ax
wenzelm@33262
   736
      in
wenzelm@33262
   737
        if member (op aconv) axs ax' then axs
wenzelm@33262
   738
        else (tracing axname; collect_term_axioms ax' (ax' :: axs))
wenzelm@33262
   739
      end
wenzelm@33262
   740
    and collect_sort_axioms T axs =
wenzelm@33262
   741
      let
wenzelm@33262
   742
        val sort =
wenzelm@33262
   743
          (case T of
wenzelm@33262
   744
            TFree (_, sort) => sort
wenzelm@33262
   745
          | TVar (_, sort)  => sort
wenzelm@33262
   746
          | _ => raise REFUTE ("collect_axioms",
wenzelm@33262
   747
              "type " ^ Syntax.string_of_typ_global thy T ^ " is not a variable"))
wenzelm@33262
   748
        (* obtain axioms for all superclasses *)
wenzelm@33262
   749
        val superclasses = sort @ maps (Sign.super_classes thy) sort
wenzelm@33262
   750
        (* merely an optimization, because 'collect_this_axiom' disallows *)
wenzelm@33262
   751
        (* duplicate axioms anyway:                                       *)
wenzelm@33262
   752
        val superclasses = distinct (op =) superclasses
wenzelm@33262
   753
        val class_axioms = maps (fn class => map (fn ax =>
wenzelm@33262
   754
          ("<" ^ class ^ ">", Thm.prop_of ax))
wenzelm@33262
   755
          (#axioms (AxClass.get_info thy class) handle ERROR _ => []))
wenzelm@33262
   756
          superclasses
wenzelm@33262
   757
        (* replace the (at most one) schematic type variable in each axiom *)
wenzelm@33262
   758
        (* by the actual type 'T'                                          *)
wenzelm@33262
   759
        val monomorphic_class_axioms = map (fn (axname, ax) =>
wenzelm@33262
   760
          (case Term.add_tvars ax [] of
wenzelm@33262
   761
            [] => (axname, ax)
wenzelm@33262
   762
          | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
wenzelm@33262
   763
          | _ =>
wenzelm@33262
   764
            raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
wenzelm@33262
   765
              Syntax.string_of_term_global thy ax ^
wenzelm@33262
   766
              ") contains more than one type variable")))
wenzelm@33262
   767
          class_axioms
wenzelm@33262
   768
      in
wenzelm@33262
   769
        fold collect_this_axiom monomorphic_class_axioms axs
wenzelm@33262
   770
      end
wenzelm@33262
   771
    and collect_type_axioms T axs =
wenzelm@22567
   772
      case T of
wenzelm@22567
   773
      (* simple types *)
wenzelm@33262
   774
        Type ("prop", []) => axs
wenzelm@33262
   775
      | Type ("fun", [T1, T2]) => collect_type_axioms T2 (collect_type_axioms T1 axs)
wenzelm@22567
   776
      (* axiomatic type classes *)
wenzelm@33262
   777
      | Type ("itself", [T1]) => collect_type_axioms T1 axs
wenzelm@33262
   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@33262
   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@39339
   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@33262
   790
            fold collect_type_axioms Ts axs))
wenzelm@22567
   791
      (* axiomatic type classes *)
wenzelm@33262
   792
      | TFree _ => collect_sort_axioms T axs
wenzelm@22567
   793
      (* axiomatic type classes *)
wenzelm@33262
   794
      | TVar _ => collect_sort_axioms T axs
wenzelm@33262
   795
    and collect_term_axioms t axs =
wenzelm@22567
   796
      case t of
wenzelm@22567
   797
      (* Pure *)
blanchet@29739
   798
        Const (@{const_name all}, _) => axs
blanchet@29739
   799
      | Const (@{const_name "=="}, _) => axs
blanchet@29739
   800
      | Const (@{const_name "==>"}, _) => axs
wenzelm@22567
   801
      (* axiomatic type classes *)
wenzelm@33262
   802
      | Const (@{const_name TYPE}, T) => collect_type_axioms T axs
wenzelm@22567
   803
      (* HOL *)
blanchet@29739
   804
      | Const (@{const_name Trueprop}, _) => axs
blanchet@29739
   805
      | Const (@{const_name Not}, _) => axs
wenzelm@22567
   806
      (* redundant, since 'True' is also an IDT constructor *)
blanchet@29739
   807
      | Const (@{const_name True}, _) => axs
wenzelm@22567
   808
      (* redundant, since 'False' is also an IDT constructor *)
blanchet@29739
   809
      | Const (@{const_name False}, _) => axs
wenzelm@33262
   810
      | Const (@{const_name undefined}, T) => collect_type_axioms T axs
blanchet@29739
   811
      | Const (@{const_name The}, T) =>
wenzelm@39339
   812
          let
wenzelm@39339
   813
            val ax = specialize_type thy (@{const_name The}, T)
wenzelm@39339
   814
              (the (AList.lookup (op =) axioms "HOL.the_eq_trivial"))
wenzelm@39339
   815
          in
wenzelm@39339
   816
            collect_this_axiom ("HOL.the_eq_trivial", ax) axs
wenzelm@39339
   817
          end
blanchet@29757
   818
      | Const (@{const_name Hilbert_Choice.Eps}, T) =>
wenzelm@39339
   819
          let
wenzelm@39339
   820
            val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T)
wenzelm@39339
   821
              (the (AList.lookup (op =) axioms "Hilbert_Choice.someI"))
wenzelm@39339
   822
          in
wenzelm@39339
   823
            collect_this_axiom ("Hilbert_Choice.someI", ax) axs
wenzelm@39339
   824
          end
wenzelm@33262
   825
      | Const (@{const_name All}, T) => collect_type_axioms T axs
wenzelm@33262
   826
      | Const (@{const_name Ex}, T) => collect_type_axioms T axs
haftmann@39093
   827
      | Const (@{const_name HOL.eq}, T) => collect_type_axioms T axs
haftmann@39028
   828
      | Const (@{const_name HOL.conj}, _) => axs
haftmann@39028
   829
      | Const (@{const_name HOL.disj}, _) => axs
haftmann@39019
   830
      | Const (@{const_name HOL.implies}, _) => axs
wenzelm@22567
   831
      (* sets *)
wenzelm@33262
   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@33262
   835
      | Const (@{const_name Finite_Set.card}, T) => collect_type_axioms T axs
blanchet@29757
   836
      | Const (@{const_name Finite_Set.finite}, T) =>
wenzelm@33262
   837
        collect_type_axioms T axs
haftmann@37363
   838
      | Const (@{const_name Orderings.less}, T as Type ("fun", [@{typ nat},
haftmann@38778
   839
        Type ("fun", [@{typ nat}, @{typ bool}])])) =>
wenzelm@33262
   840
          collect_type_axioms T axs
haftmann@37363
   841
      | Const (@{const_name Groups.plus}, T as Type ("fun", [@{typ nat},
haftmann@37363
   842
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33262
   843
          collect_type_axioms T axs
haftmann@37363
   844
      | Const (@{const_name Groups.minus}, T as Type ("fun", [@{typ nat},
haftmann@37363
   845
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33262
   846
          collect_type_axioms T axs
haftmann@37363
   847
      | Const (@{const_name Groups.times}, T as Type ("fun", [@{typ nat},
haftmann@37363
   848
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@33262
   849
          collect_type_axioms T axs
wenzelm@33262
   850
      | Const (@{const_name List.append}, T) => collect_type_axioms T axs
blanchet@36130
   851
(* UNSOUND
wenzelm@33262
   852
      | Const (@{const_name lfp}, T) => collect_type_axioms T axs
wenzelm@33262
   853
      | Const (@{const_name gfp}, T) => collect_type_axioms T axs
blanchet@36130
   854
*)
wenzelm@33262
   855
      | Const (@{const_name fst}, T) => collect_type_axioms T axs
wenzelm@33262
   856
      | Const (@{const_name snd}, T) => collect_type_axioms T axs
wenzelm@22567
   857
      (* simply-typed lambda calculus *)
blanchet@29739
   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@33262
   863
              val class = Logic.class_of_const s
wenzelm@31943
   864
              val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]), class)
wenzelm@33262
   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@33262
   868
              val ax_1 = Option.map (fn ax => (Syntax.string_of_term_global thy ax, ax)) ax_in
wenzelm@33262
   869
              val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
wenzelm@22567
   870
            in
wenzelm@33262
   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@33262
   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@33262
   882
            collect_type_axioms T axs
wenzelm@33262
   883
      | Free (_, T) => collect_type_axioms T axs
wenzelm@33262
   884
      | Var (_, T) => collect_type_axioms T axs
wenzelm@33262
   885
      | Bound _ => axs
wenzelm@33262
   886
      | Abs (_, T, body) => collect_term_axioms body (collect_type_axioms T axs)
wenzelm@33262
   887
      | t1 $ t2 => collect_term_axioms t2 (collect_term_axioms t1 axs)
wenzelm@33262
   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@14456
   900
(* ------------------------------------------------------------------------- *)
webertj@14456
   901
wenzelm@39339
   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@39339
   907
      | Type ("prop", []) => acc
wenzelm@39339
   908
      | Type (s, Ts) =>
wenzelm@39339
   909
          (case Datatype.get_info thy s of
wenzelm@39339
   910
            SOME info =>  (* inductive datatype *)
wenzelm@39339
   911
              let
wenzelm@39339
   912
                val index = #index info
wenzelm@39339
   913
                val descr = #descr info
wenzelm@39339
   914
                val (_, typs, _) = the (AList.lookup (op =) descr index)
wenzelm@39339
   915
                val typ_assoc = typs ~~ Ts
wenzelm@39339
   916
                (* sanity check: every element in 'dtyps' must be a *)
wenzelm@39339
   917
                (* 'DtTFree'                                        *)
wenzelm@39339
   918
                val _ = if Library.exists (fn d =>
wenzelm@39339
   919
                  case d of Datatype_Aux.DtTFree _ => false | _ => true) typs then
wenzelm@39339
   920
                  raise REFUTE ("ground_types", "datatype argument (for type "
wenzelm@39339
   921
                    ^ Syntax.string_of_typ_global thy T ^ ") is not a variable")
wenzelm@39339
   922
                else ()
wenzelm@39339
   923
                (* required for mutually recursive datatypes; those need to   *)
wenzelm@39339
   924
                (* be added even if they are an instance of an otherwise non- *)
wenzelm@39339
   925
                (* recursive datatype                                         *)
wenzelm@39339
   926
                fun collect_dtyp d acc =
webertj@25014
   927
                  let
wenzelm@39339
   928
                    val dT = typ_of_dtyp descr typ_assoc d
webertj@25014
   929
                  in
wenzelm@39339
   930
                    case d of
wenzelm@39339
   931
                      Datatype_Aux.DtTFree _ =>
wenzelm@39339
   932
                      collect_types dT acc
wenzelm@39339
   933
                    | Datatype_Aux.DtType (_, ds) =>
wenzelm@39339
   934
                      collect_types dT (fold_rev collect_dtyp ds acc)
wenzelm@39339
   935
                    | Datatype_Aux.DtRec i =>
wenzelm@39339
   936
                      if member (op =) acc dT then
wenzelm@39339
   937
                        acc  (* prevent infinite recursion *)
wenzelm@39339
   938
                      else
wenzelm@39339
   939
                        let
wenzelm@39339
   940
                          val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
wenzelm@39339
   941
                          (* if the current type is a recursive IDT (i.e. a depth *)
wenzelm@39339
   942
                          (* is required), add it to 'acc'                        *)
wenzelm@39339
   943
                          val acc_dT = if Library.exists (fn (_, ds) =>
wenzelm@39339
   944
                            Library.exists Datatype_Aux.is_rec_type ds) dconstrs then
wenzelm@39339
   945
                              insert (op =) dT acc
wenzelm@39339
   946
                            else acc
wenzelm@39339
   947
                          (* collect argument types *)
wenzelm@39339
   948
                          val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
wenzelm@39339
   949
                          (* collect constructor types *)
wenzelm@39339
   950
                          val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
wenzelm@39339
   951
                        in
wenzelm@39339
   952
                          acc_dconstrs
wenzelm@39339
   953
                        end
webertj@25014
   954
                  end
wenzelm@39339
   955
              in
wenzelm@39339
   956
                (* argument types 'Ts' could be added here, but they are also *)
wenzelm@39339
   957
                (* added by 'collect_dtyp' automatically                      *)
wenzelm@39339
   958
                collect_dtyp (Datatype_Aux.DtRec index) acc
wenzelm@39339
   959
              end
wenzelm@39339
   960
          | NONE =>
wenzelm@39339
   961
            (* not an inductive datatype, e.g. defined via "typedef" or *)
wenzelm@39339
   962
            (* "typedecl"                                               *)
wenzelm@39339
   963
            insert (op =) T (fold collect_types Ts acc))
wenzelm@39339
   964
      | TFree _ => insert (op =) T acc
wenzelm@39339
   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@39339
   977
(* Term.typ -> string *)
webertj@14807
   978
wenzelm@39339
   979
fun string_of_typ (Type (s, _))     = s
wenzelm@39339
   980
  | string_of_typ (TFree (s, _))    = s
wenzelm@39339
   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@39339
   989
(* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
webertj@14807
   990
wenzelm@39339
   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@33262
   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@14807
  1006
(* ------------------------------------------------------------------------- *)
webertj@14807
  1007
wenzelm@39339
  1008
(* (Term.typ * int) list -> (string * int) list -> int -> int ->
wenzelm@39339
  1009
  (Term.typ * int) list option *)
webertj@14807
  1010
wenzelm@39339
  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@39339
  1017
          if sum = 0 then
wenzelm@39339
  1018
            SOME []
wenzelm@39339
  1019
          else
wenzelm@39339
  1020
            NONE
wenzelm@22567
  1021
      | make_first max len sum =
wenzelm@39339
  1022
          if sum <= max orelse max < 0 then
wenzelm@39339
  1023
            Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
wenzelm@39339
  1024
          else
wenzelm@39339
  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@39339
  1030
          NONE
wenzelm@22567
  1031
      | next max len sum [x] =
wenzelm@39339
  1032
          (* we've reached the last list element, so there's no shift possible *)
wenzelm@39339
  1033
          make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
wenzelm@22567
  1034
      | next max len sum (x1::x2::xs) =
wenzelm@39339
  1035
          if x1>0 andalso (x2<max orelse max<0) then
wenzelm@39339
  1036
            (* we can shift *)
wenzelm@39339
  1037
            SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
wenzelm@39339
  1038
          else
wenzelm@39339
  1039
            (* continue search *)
wenzelm@39339
  1040
            next max (len+1) (sum+x1) (x2::xs)
wenzelm@22567
  1041
    (* only consider those types for which the size is not fixed *)
wenzelm@33325
  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@39339
  1048
        (* merge with those types for which the size is fixed *)
wenzelm@39339
  1049
        SOME (fst (fold_map (fn (T, _) => fn ds =>
wenzelm@39339
  1050
          case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@39339
  1051
          (* return the fixed size *)
wenzelm@39339
  1052
            SOME n => ((T, n), ds)
wenzelm@39339
  1053
          (* consume the head of 'ds', add 'minsize' *)
wenzelm@39339
  1054
          | NONE   => ((T, minsize + hd ds), tl ds))
wenzelm@39339
  1055
          xs diffs'))
wenzelm@39339
  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@39339
  1064
(* interpretation -> prop_formula *)
webertj@14807
  1065
wenzelm@39339
  1066
fun toTrue (Leaf [fm, _]) = fm
wenzelm@39339
  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@39339
  1075
(* interpretation -> prop_formula *)
webertj@14807
  1076
wenzelm@39339
  1077
fun toFalse (Leaf [_, fm]) = fm
wenzelm@39339
  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@34117
  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@39339
  1091
(* theory -> params -> Term.term -> bool -> unit *)
webertj@14807
  1092
wenzelm@39339
  1093
fun find_model thy
wenzelm@39339
  1094
    {sizes, minsize, maxsize, maxvars, maxtime, satsolver, no_assms, expect}
wenzelm@39339
  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@39339
  1104
        val timer = Timer.startRealTimer ()
wenzelm@39339
  1105
        val t =
wenzelm@39339
  1106
          if no_assms then t
wenzelm@39339
  1107
          else if negate then Logic.list_implies (assm_ts, t)
wenzelm@39339
  1108
          else Logic.mk_conjunction_list (t :: assm_ts)
wenzelm@39339
  1109
        val u = unfold_defs thy t
wenzelm@39339
  1110
        val _ = tracing ("Unfolded term: " ^ Syntax.string_of_term_global thy u)
wenzelm@39339
  1111
        val axioms = collect_axioms thy u
wenzelm@39339
  1112
        (* Term.typ list *)
wenzelm@39339
  1113
        val types = fold (union (op =) o ground_types thy) (u :: axioms) []
wenzelm@39339
  1114
        val _ = tracing ("Ground types: "
wenzelm@39339
  1115
          ^ (if null types then "none."
wenzelm@39339
  1116
             else commas (map (Syntax.string_of_typ_global thy) types)))
wenzelm@39339
  1117
        (* we can only consider fragments of recursive IDTs, so we issue a  *)
wenzelm@39339
  1118
        (* warning if the formula contains a recursive IDT                  *)
wenzelm@39339
  1119
        (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
wenzelm@39339
  1120
        val maybe_spurious = Library.exists (fn
wenzelm@39339
  1121
            Type (s, _) =>
wenzelm@39339
  1122
              (case Datatype.get_info thy s of
wenzelm@39339
  1123
                SOME info =>  (* inductive datatype *)
wenzelm@39339
  1124
                  let
wenzelm@39339
  1125
                    val index           = #index info
wenzelm@39339
  1126
                    val descr           = #descr info
wenzelm@39339
  1127
                    val (_, _, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39339
  1128
                  in
wenzelm@39339
  1129
                    (* recursive datatype? *)
wenzelm@39339
  1130
                    Library.exists (fn (_, ds) =>
wenzelm@39339
  1131
                      Library.exists Datatype_Aux.is_rec_type ds) constrs
wenzelm@39339
  1132
                  end
wenzelm@39339
  1133
              | NONE => false)
wenzelm@39339
  1134
          | _ => false) types
wenzelm@39339
  1135
        val _ =
wenzelm@39339
  1136
          if maybe_spurious then
wenzelm@39339
  1137
            warning ("Term contains a recursive datatype; "
wenzelm@39339
  1138
              ^ "countermodel(s) may be spurious!")
wenzelm@39339
  1139
          else
wenzelm@39339
  1140
            ()
wenzelm@39339
  1141
        (* (Term.typ * int) list -> string *)
wenzelm@39339
  1142
        fun find_model_loop universe =
wenzelm@22567
  1143
          let
wenzelm@39339
  1144
            val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
wenzelm@39339
  1145
            val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
wenzelm@39339
  1146
                    orelse raise TimeLimit.TimeOut
wenzelm@39339
  1147
            val init_model = (universe, [])
wenzelm@39339
  1148
            val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
wenzelm@39339
  1149
              bounds = [], wellformed = True}
wenzelm@39339
  1150
            val _ = tracing ("Translating term (sizes: "
wenzelm@39339
  1151
              ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
wenzelm@39339
  1152
            (* translate 'u' and all axioms *)
wenzelm@39339
  1153
            val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
wenzelm@39339
  1154
              let
wenzelm@39339
  1155
                val (i, m', a') = interpret thy m a t'
wenzelm@39339
  1156
              in
wenzelm@39339
  1157
                (* set 'def_eq' to 'true' *)
wenzelm@39339
  1158
                (i, (m', {maxvars = #maxvars a', def_eq = true,
wenzelm@39339
  1159
                  next_idx = #next_idx a', bounds = #bounds a',
wenzelm@39339
  1160
                  wellformed = #wellformed a'}))
wenzelm@39339
  1161
              end) (u :: axioms) (init_model, init_args)
wenzelm@39339
  1162
            (* make 'u' either true or false, and make all axioms true, and *)
wenzelm@39339
  1163
            (* add the well-formedness side condition                       *)
wenzelm@39339
  1164
            val fm_u = (if negate then toFalse else toTrue) (hd intrs)
wenzelm@39339
  1165
            val fm_ax = PropLogic.all (map toTrue (tl intrs))
wenzelm@39339
  1166
            val fm = PropLogic.all [#wellformed args, fm_ax, fm_u]
wenzelm@39339
  1167
            val _ =
wenzelm@39339
  1168
              (if satsolver = "dpll" orelse satsolver = "enumerate" then
wenzelm@39339
  1169
                warning ("Using SAT solver " ^ quote satsolver ^
wenzelm@39339
  1170
                         "; for better performance, consider installing an \
wenzelm@39339
  1171
                         \external solver.")
wenzelm@39339
  1172
               else ());
wenzelm@39339
  1173
            val solver =
wenzelm@39339
  1174
              SatSolver.invoke_solver satsolver
wenzelm@39339
  1175
              handle Option.Option =>
wenzelm@39339
  1176
                     error ("Unknown SAT solver: " ^ quote satsolver ^
wenzelm@39339
  1177
                            ". Available solvers: " ^
wenzelm@39339
  1178
                            commas (map (quote o fst) (!SatSolver.solvers)) ^ ".")
wenzelm@22567
  1179
          in
wenzelm@39339
  1180
            priority "Invoking SAT solver...";
wenzelm@39339
  1181
            (case solver fm of
wenzelm@39339
  1182
              SatSolver.SATISFIABLE assignment =>
wenzelm@39339
  1183
                (priority ("*** Model found: ***\n" ^ print_model thy model
wenzelm@39339
  1184
                  (fn i => case assignment i of SOME b => b | NONE => true));
wenzelm@39339
  1185
                 if maybe_spurious then "potential" else "genuine")
wenzelm@39339
  1186
            | SatSolver.UNSATISFIABLE _ =>
wenzelm@39339
  1187
                (priority "No model exists.";
wenzelm@39339
  1188
                case next_universe universe sizes minsize maxsize of
wenzelm@39339
  1189
                  SOME universe' => find_model_loop universe'
wenzelm@39339
  1190
                | NONE => (priority
wenzelm@39339
  1191
                  "Search terminated, no larger universe within the given limits.";
wenzelm@39339
  1192
                  "none"))
wenzelm@39339
  1193
            | SatSolver.UNKNOWN =>
wenzelm@39339
  1194
                (priority "No model found.";
wenzelm@39339
  1195
                case next_universe universe sizes minsize maxsize of
wenzelm@39339
  1196
                  SOME universe' => find_model_loop universe'
wenzelm@39339
  1197
                | NONE           => (priority
wenzelm@39339
  1198
                  "Search terminated, no larger universe within the given limits.";
wenzelm@39339
  1199
                  "unknown"))) handle SatSolver.NOT_CONFIGURED =>
wenzelm@39339
  1200
              (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
wenzelm@39339
  1201
               "unknown")
wenzelm@39339
  1202
          end
wenzelm@39339
  1203
          handle MAXVARS_EXCEEDED =>
wenzelm@39339
  1204
            (priority ("Search terminated, number of Boolean variables ("
wenzelm@39339
  1205
              ^ string_of_int maxvars ^ " allowed) exceeded.");
wenzelm@39339
  1206
              "unknown")
wenzelm@39339
  1207
blanchet@30315
  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@39339
  1212
  in
wenzelm@39339
  1213
    (* some parameter sanity checks *)
wenzelm@39339
  1214
    minsize>=1 orelse
wenzelm@39339
  1215
      error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
wenzelm@39339
  1216
    maxsize>=1 orelse
wenzelm@39339
  1217
      error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
wenzelm@39339
  1218
    maxsize>=minsize orelse
wenzelm@39339
  1219
      error ("\"maxsize\" (=" ^ string_of_int maxsize ^
wenzelm@39339
  1220
      ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
wenzelm@39339
  1221
    maxvars>=0 orelse
wenzelm@39339
  1222
      error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
wenzelm@39339
  1223
    maxtime>=0 orelse
wenzelm@39339
  1224
      error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
wenzelm@39339
  1225
    (* enter loop with or without time limit *)
wenzelm@39339
  1226
    priority ("Trying to find a model that "
wenzelm@39339
  1227
      ^ (if negate then "refutes" else "satisfies") ^ ": "
wenzelm@39339
  1228
      ^ Syntax.string_of_term_global thy t);
wenzelm@39339
  1229
    if maxtime > 0 then (
wenzelm@39339
  1230
      TimeLimit.timeLimit (Time.fromSeconds maxtime)
wenzelm@22567
  1231
        wrapper ()
wenzelm@39339
  1232
      handle TimeLimit.TimeOut =>
wenzelm@39339
  1233
        (priority ("Search terminated, time limit (" ^
wenzelm@39339
  1234
            string_of_int maxtime
wenzelm@39339
  1235
            ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
wenzelm@39339
  1236
         check_expect "unknown")
wenzelm@39339
  1237
    ) else wrapper ()
wenzelm@39339
  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@39339
  1251
(* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
webertj@14350
  1252
wenzelm@39339
  1253
fun satisfy_term thy params assm_ts t =
wenzelm@39339
  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@39339
  1262
(* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
webertj@14350
  1263
wenzelm@39339
  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@33262
  1277
    val ex_closure = fold (fn ((x, i), T) => fn t' =>
wenzelm@33262
  1278
      HOLogic.exists_const T $
wenzelm@33262
  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@29757
  1293
    fun strip_all_body (Const (@{const_name all}, _) $ Abs (_, _, t)) =
wenzelm@39339
  1294
          strip_all_body t
blanchet@29757
  1295
      | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@39339
  1296
          strip_all_body t
blanchet@29757
  1297
      | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
wenzelm@39339
  1298
          strip_all_body t
blanchet@29739
  1299
      | strip_all_body t = t
wenzelm@22567
  1300
    (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
blanchet@29739
  1301
    fun strip_all_vars (Const (@{const_name all}, _) $ Abs (a, T, t)) =
wenzelm@39339
  1302
          (a, T) :: strip_all_vars t
blanchet@29739
  1303
      | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@39339
  1304
          strip_all_vars t
blanchet@29739
  1305
      | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
wenzelm@39339
  1306
          (a, T) :: strip_all_vars t
wenzelm@39339
  1307
      | strip_all_vars t = [] : (string * typ) list
wenzelm@22567
  1308
    val strip_t = strip_all_body ex_closure
wenzelm@39339
  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@34117
  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@39339
  1319
fun refute_goal ctxt params th i =
blanchet@34117
  1320
  let
blanchet@34117
  1321
    val t = th |> prop_of
blanchet@34117
  1322
  in
blanchet@34117
  1323
    if Logic.count_prems t = 0 then
blanchet@34117
  1324
      priority "No subgoal!"
blanchet@34117
  1325
    else
blanchet@34117
  1326
      let
blanchet@34117
  1327
        val assms = map term_of (Assumption.all_assms_of ctxt)
blanchet@34117
  1328
        val (t, frees) = Logic.goal_params t i
blanchet@34117
  1329
      in
blanchet@34117
  1330
        refute_term (ProofContext.theory_of ctxt) params assms
blanchet@34117
  1331
        (subst_bounds (frees, t))
blanchet@34117
  1332
      end
blanchet@34117
  1333
  end
webertj@14456
  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@39339
  1346
(* theory -> model -> Term.typ -> interpretation list *)
webertj@14350
  1347
wenzelm@39339
  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@39339
  1353
      let
wenzelm@39339
  1354
        (* returns the k-th unit vector of length n *)
wenzelm@39339
  1355
        (* int * int -> interpretation *)
wenzelm@39339
  1356
        fun unit_vector (k, n) =
wenzelm@39339
  1357
          Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
wenzelm@39339
  1358
        (* int -> interpretation list *)
wenzelm@39339
  1359
        fun unit_vectors_loop k =
wenzelm@39339
  1360
          if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
wenzelm@39339
  1361
      in
wenzelm@39339
  1362
        unit_vectors_loop 1
wenzelm@39339
  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@39339
  1367
    fun pick_all 1 xs = map single xs
wenzelm@22567
  1368
      | pick_all n xs =
wenzelm@39339
  1369
          let val rec_pick = pick_all (n - 1) xs in
wenzelm@39339
  1370
            maps (fn x => map (cons x) rec_pick) xs
wenzelm@39339
  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@39339
  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
(* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
webertj@25014
  1387
(*               (make_constants T)', but implemented more efficiently)      *)
webertj@25014
  1388
(* ------------------------------------------------------------------------- *)
webertj@25014
  1389
wenzelm@39339
  1390
(* theory -> model -> Term.typ -> int *)
webertj@25014
  1391
wenzelm@39339
  1392
(* returns 0 for an empty ground type or a function type with empty      *)
wenzelm@39339
  1393
(* codomain, but fails for a function type with empty domain --          *)
wenzelm@39339
  1394
(* admissibility of datatype constructor argument types (see "Inductive  *)
wenzelm@39339
  1395
(* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
wenzelm@39339
  1396
(* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
wenzelm@39339
  1397
(* never occur as the domain of a function type that is the type of a    *)
wenzelm@39339
  1398
(* constructor argument                                                  *)
webertj@25014
  1399
wenzelm@39339
  1400
fun size_of_type thy model T =
wenzelm@22567
  1401
  let
webertj@25014
  1402
    (* returns the number of elements that have the same tree structure as a *)
webertj@25014
  1403
    (* given interpretation                                                  *)
webertj@25014
  1404
    fun size_of_intr (Leaf xs) = length xs
wenzelm@39340
  1405
      | size_of_intr (Node xs) = Integer.pow (length xs) (size_of_intr (hd xs))
webertj@25014
  1406
    (* obtain the interpretation for a variable of type 'T' *)
webertj@25014
  1407
    val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1408
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1409
  in
webertj@25014
  1410
    size_of_intr i
wenzelm@22567
  1411
  end;
webertj@14807
  1412
webertj@14807
  1413
(* ------------------------------------------------------------------------- *)
webertj@14807
  1414
(* TT/FF: interpretations that denote "true" or "false", respectively        *)
webertj@14807
  1415
(* ------------------------------------------------------------------------- *)
webertj@14807
  1416
wenzelm@39339
  1417
(* interpretation *)
webertj@14807
  1418
wenzelm@39339
  1419
val TT = Leaf [True, False];
webertj@14807
  1420
wenzelm@39339
  1421
val FF = Leaf [False, True];
webertj@14807
  1422
webertj@14807
  1423
(* ------------------------------------------------------------------------- *)
webertj@14807
  1424
(* make_equality: returns an interpretation that denotes (extensional)       *)
webertj@14807
  1425
(*                equality of two interpretations                            *)
webertj@15547
  1426
(* - two interpretations are 'equal' iff they are both defined and denote    *)
webertj@15547
  1427
(*   the same value                                                          *)
webertj@15547
  1428
(* - two interpretations are 'not_equal' iff they are both defined at least  *)
webertj@15547
  1429
(*   partially, and a defined part denotes different values                  *)
webertj@15547
  1430
(* - a completely undefined interpretation is neither 'equal' nor            *)
webertj@15547
  1431
(*   'not_equal' to another interpretation                                   *)
webertj@14807
  1432
(* ------------------------------------------------------------------------- *)
webertj@14807
  1433
wenzelm@39339
  1434
(* We could in principle represent '=' on a type T by a particular        *)
wenzelm@39339
  1435
(* interpretation.  However, the size of that interpretation is quadratic *)
wenzelm@39339
  1436
(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
wenzelm@39339
  1437
(* 'i2' directly is more efficient than constructing the interpretation   *)
wenzelm@39339
  1438
(* for equality on T first, and "applying" this interpretation to 'i1'    *)
wenzelm@39339
  1439
(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
webertj@14807
  1440
wenzelm@39339
  1441
(* interpretation * interpretation -> interpretation *)
webertj@14807
  1442
wenzelm@39339
  1443
fun make_equality (i1, i2) =
wenzelm@22567
  1444
  let
wenzelm@22567
  1445
    (* interpretation * interpretation -> prop_formula *)
wenzelm@22567
  1446
    fun equal (i1, i2) =
wenzelm@22567
  1447
      (case i1 of
wenzelm@22567
  1448
        Leaf xs =>
wenzelm@39339
  1449
          (case i2 of
wenzelm@39339
  1450
            Leaf ys => PropLogic.dot_product (xs, ys)  (* defined and equal *)
wenzelm@39339
  1451
          | Node _  => raise REFUTE ("make_equality",
wenzelm@39339
  1452
            "second interpretation is higher"))
wenzelm@22567
  1453
      | Node xs =>
wenzelm@39339
  1454
          (case i2 of
wenzelm@39339
  1455
            Leaf _  => raise REFUTE ("make_equality",
wenzelm@39339
  1456
            "first interpretation is higher")
wenzelm@39339
  1457
          | Node ys => PropLogic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1458
    (* interpretation * interpretation -> prop_formula *)
wenzelm@22567
  1459
    fun not_equal (i1, i2) =
wenzelm@22567
  1460
      (case i1 of
wenzelm@22567
  1461
        Leaf xs =>
wenzelm@39339
  1462
          (case i2 of
wenzelm@39339
  1463
            (* defined and not equal *)
wenzelm@39339
  1464
            Leaf ys => PropLogic.all ((PropLogic.exists xs)
wenzelm@39339
  1465
            :: (PropLogic.exists ys)
wenzelm@39339
  1466
            :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
wenzelm@39339
  1467
          | Node _  => raise REFUTE ("make_equality",
wenzelm@39339
  1468
            "second interpretation is higher"))
wenzelm@22567
  1469
      | Node xs =>
wenzelm@39339
  1470
          (case i2 of
wenzelm@39339
  1471
            Leaf _  => raise REFUTE ("make_equality",
wenzelm@39339
  1472
            "first interpretation is higher")
wenzelm@39339
  1473
          | Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
wenzelm@22567
  1474
  in
wenzelm@22567
  1475
    (* a value may be undefined; therefore 'not_equal' is not just the *)
wenzelm@22567
  1476
    (* negation of 'equal'                                             *)
wenzelm@22567
  1477
    Leaf [equal (i1, i2), not_equal (i1, i2)]
wenzelm@22567
  1478
  end;
webertj@14807
  1479
webertj@15292
  1480
(* ------------------------------------------------------------------------- *)
webertj@15547
  1481
(* make_def_equality: returns an interpretation that denotes (extensional)   *)
webertj@15547
  1482
(*                    equality of two interpretations                        *)
webertj@15547
  1483
(* This function treats undefined/partially defined interpretations          *)
webertj@15547
  1484
(* different from 'make_equality': two undefined interpretations are         *)
webertj@15547
  1485
(* considered equal, while a defined interpretation is considered not equal  *)
webertj@15547
  1486
(* to an undefined interpretation.                                           *)
webertj@15547
  1487
(* ------------------------------------------------------------------------- *)
webertj@15547
  1488
wenzelm@39339
  1489
(* interpretation * interpretation -> interpretation *)
webertj@15547
  1490
wenzelm@39339
  1491
fun make_def_equality (i1, i2) =
wenzelm@22567
  1492
  let
wenzelm@22567
  1493
    (* interpretation * interpretation -> prop_formula *)
wenzelm@22567
  1494
    fun equal (i1, i2) =
wenzelm@22567
  1495
      (case i1 of
wenzelm@22567
  1496
        Leaf xs =>
wenzelm@39339
  1497
          (case i2 of
wenzelm@39339
  1498
            (* defined and equal, or both undefined *)
wenzelm@39339
  1499
            Leaf ys => SOr (PropLogic.dot_product (xs, ys),
wenzelm@39339
  1500
            SAnd (PropLogic.all (map SNot xs), PropLogic.all (map SNot ys)))
wenzelm@39339
  1501
          | Node _  => raise REFUTE ("make_def_equality",
wenzelm@39339
  1502
            "second interpretation is higher"))
wenzelm@22567
  1503
      | Node xs =>
wenzelm@39339
  1504
          (case i2 of
wenzelm@39339
  1505
            Leaf _  => raise REFUTE ("make_def_equality",
wenzelm@39339
  1506
            "first interpretation is higher")
wenzelm@39339
  1507
          | Node ys => PropLogic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1508
    (* interpretation *)
wenzelm@22567
  1509
    val eq = equal (i1, i2)
wenzelm@22567
  1510
  in
wenzelm@22567
  1511
    Leaf [eq, SNot eq]
wenzelm@22567
  1512
  end;
webertj@15547
  1513
webertj@15547
  1514
(* ------------------------------------------------------------------------- *)
webertj@15547
  1515
(* interpretation_apply: returns an interpretation that denotes the result   *)
webertj@22092
  1516
(*                       of applying the function denoted by 'i1' to the     *)
webertj@15547
  1517
(*                       argument denoted by 'i2'                            *)
webertj@15547
  1518
(* ------------------------------------------------------------------------- *)
webertj@15547
  1519
wenzelm@39339
  1520
(* interpretation * interpretation -> interpretation *)
webertj@15547
  1521
wenzelm@39339
  1522
fun interpretation_apply (i1, i2) =
wenzelm@22567
  1523
  let
wenzelm@22567
  1524
    (* interpretation * interpretation -> interpretation *)
wenzelm@22567
  1525
    fun interpretation_disjunction (tr1,tr2) =
wenzelm@22567
  1526
      tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
wenzelm@22567
  1527
        (tree_pair (tr1,tr2))
wenzelm@22567
  1528
    (* prop_formula * interpretation -> interpretation *)
wenzelm@22567
  1529
    fun prop_formula_times_interpretation (fm,tr) =
wenzelm@22567
  1530
      tree_map (map (fn x => SAnd (fm,x))) tr
wenzelm@22567
  1531
    (* prop_formula list * interpretation list -> interpretation *)
wenzelm@22567
  1532
    fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
wenzelm@39339
  1533
          prop_formula_times_interpretation (fm,tr)
wenzelm@22567
  1534
      | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
wenzelm@39339
  1535
          interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
wenzelm@39339
  1536
            prop_formula_list_dot_product_interpretation_list (fms,trees))
wenzelm@22567
  1537
      | prop_formula_list_dot_product_interpretation_list (_,_) =
wenzelm@39339
  1538
          raise REFUTE ("interpretation_apply", "empty list (in dot product)")
wenzelm@22567
  1539
    (* concatenates 'x' with every list in 'xss', returning a new list of *)
wenzelm@22567
  1540
    (* lists                                                              *)
wenzelm@22567
  1541
    (* 'a -> 'a list list -> 'a list list *)
wenzelm@39339
  1542
    fun cons_list x xss = map (cons x) xss
wenzelm@22567
  1543
    (* returns a list of lists, each one consisting of one element from each *)
wenzelm@22567
  1544
    (* element of 'xss'                                                      *)
wenzelm@22567
  1545
    (* 'a list list -> 'a list list *)
wenzelm@39339
  1546
    fun pick_all [xs] = map single xs
wenzelm@22567
  1547
      | pick_all (xs::xss) =
wenzelm@39339
  1548
          let val rec_pick = pick_all xss in
wenzelm@39339
  1549
            maps (fn x => map (cons x) rec_pick) xs
wenzelm@39339
  1550
          end
wenzelm@39339
  1551
      | pick_all _ = raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
wenzelm@22567
  1552
    (* interpretation -> prop_formula list *)
wenzelm@39339
  1553
    fun interpretation_to_prop_formula_list (Leaf xs) = xs
wenzelm@22567
  1554
      | interpretation_to_prop_formula_list (Node trees) =
wenzelm@39339
  1555
          map PropLogic.all (pick_all
wenzelm@39339
  1556
            (map interpretation_to_prop_formula_list trees))
wenzelm@22567
  1557
  in
wenzelm@22567
  1558
    case i1 of
wenzelm@22567
  1559
      Leaf _ =>
wenzelm@39339
  1560
        raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
wenzelm@22567
  1561
    | Node xs =>
wenzelm@39339
  1562
        prop_formula_list_dot_product_interpretation_list
wenzelm@39339
  1563
          (interpretation_to_prop_formula_list i2, xs)
wenzelm@22567
  1564
  end;
webertj@15547
  1565
webertj@15547
  1566
(* ------------------------------------------------------------------------- *)
webertj@15292
  1567
(* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
webertj@15292
  1568
(* ------------------------------------------------------------------------- *)
webertj@15292
  1569
wenzelm@39339
  1570
(* Term.term -> int -> Term.term *)
webertj@15292
  1571
wenzelm@39339
  1572
fun eta_expand t i =
wenzelm@22567
  1573
  let
wenzelm@22567
  1574
    val Ts = Term.binder_types (Term.fastype_of t)
wenzelm@22567
  1575
    val t' = Term.incr_boundvars i t
wenzelm@22567
  1576
  in
wenzelm@33346
  1577
    fold_rev (fn T => fn term => Abs ("<eta_expand>", T, term))
wenzelm@33346
  1578
      (List.take (Ts, i))
wenzelm@33346
  1579
      (Term.list_comb (t', map Bound (i-1 downto 0)))
wenzelm@22567
  1580
  end;
webertj@15292
  1581
webertj@15335
  1582
(* ------------------------------------------------------------------------- *)
webertj@15547
  1583
(* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
webertj@15547
  1584
(*               is the sum (over its constructors) of the product (over     *)
webertj@15547
  1585
(*               their arguments) of the size of the argument types          *)
webertj@15335
  1586
(* ------------------------------------------------------------------------- *)
webertj@15335
  1587
wenzelm@39339
  1588
fun size_of_dtyp thy typ_sizes descr typ_assoc constructors =
wenzelm@39339
  1589
  Integer.sum (map (fn (_, dtyps) =>
wenzelm@39339
  1590
    Integer.prod (map (size_of_type thy (typ_sizes, []) o
wenzelm@39339
  1591
      (typ_of_dtyp descr typ_assoc)) dtyps))
wenzelm@39339
  1592
        constructors);
webertj@15335
  1593
webertj@15292
  1594
webertj@15292
  1595
(* ------------------------------------------------------------------------- *)
webertj@15292
  1596
(* INTERPRETERS: Actual Interpreters                                         *)
webertj@15292
  1597
(* ------------------------------------------------------------------------- *)
webertj@14807
  1598
wenzelm@39339
  1599
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  1600
  (interpretation * model * arguments) option *)
webertj@14807
  1601
wenzelm@39339
  1602
(* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
wenzelm@39339
  1603
(* variables, function types, and propT                                  *)
webertj@14807
  1604
wenzelm@39339
  1605
fun stlc_interpreter thy model args t =
wenzelm@22567
  1606
  let
wenzelm@39339
  1607
    val (typs, terms) = model
wenzelm@22567
  1608
    val {maxvars, def_eq, next_idx, bounds, wellformed} = args
wenzelm@22567
  1609
    (* Term.typ -> (interpretation * model * arguments) option *)
wenzelm@22567
  1610
    fun interpret_groundterm T =
wenzelm@22567
  1611
      let
wenzelm@39339
  1612
        (* unit -> (interpretation * model * arguments) option *)
wenzelm@39339
  1613
        fun interpret_groundtype () =
wenzelm@39339
  1614
          let
wenzelm@39339
  1615
            (* the model must specify a size for ground types *)
wenzelm@39339
  1616
            val size =
wenzelm@39339
  1617
              if T = Term.propT then 2
wenzelm@39339
  1618
              else the (AList.lookup (op =) typs T)
wenzelm@39339
  1619
            val next = next_idx + size
wenzelm@39339
  1620
            (* check if 'maxvars' is large enough *)
wenzelm@39339
  1621
            val _ = (if next - 1 > maxvars andalso maxvars > 0 then
wenzelm@39339
  1622
              raise MAXVARS_EXCEEDED else ())
wenzelm@39339
  1623
            (* prop_formula list *)
wenzelm@39339
  1624
            val fms  = map BoolVar (next_idx upto (next_idx + size - 1))
wenzelm@39339
  1625
            (* interpretation *)
wenzelm@39339
  1626
            val intr = Leaf fms
wenzelm@39339
  1627
            (* prop_formula list -> prop_formula *)
wenzelm@39339
  1628
            fun one_of_two_false [] = True
wenzelm@39339
  1629
              | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
wenzelm@39339
  1630
                  SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@39339
  1631
            (* prop_formula *)
wenzelm@39339
  1632
            val wf = one_of_two_false fms
wenzelm@39339
  1633
          in
wenzelm@39339
  1634
            (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39339
  1635
            (* condition                                                  *)
wenzelm@39339
  1636
            SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@39339
  1637
              def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@39339
  1638
              wellformed = SAnd (wellformed, wf)})
wenzelm@39339
  1639
          end
wenzelm@22567
  1640
      in
wenzelm@39339
  1641
        case T of
wenzelm@39339
  1642
          Type ("fun", [T1, T2]) =>
wenzelm@39339
  1643
            let
wenzelm@39339
  1644
              (* we create 'size_of_type ... T1' different copies of the        *)
wenzelm@39339
  1645
              (* interpretation for 'T2', which are then combined into a single *)
wenzelm@39339
  1646
              (* new interpretation                                             *)
wenzelm@39339
  1647
              (* make fresh copies, with different variable indices *)
wenzelm@39339
  1648
              (* 'idx': next variable index                         *)
wenzelm@39339
  1649
              (* 'n'  : number of copies                            *)
wenzelm@39339
  1650
              (* int -> int -> (int * interpretation list * prop_formula *)
wenzelm@39339
  1651
              fun make_copies idx 0 = (idx, [], True)
wenzelm@39339
  1652
                | make_copies idx n =
wenzelm@39339
  1653
                    let
wenzelm@39339
  1654
                      val (copy, _, new_args) = interpret thy (typs, [])
wenzelm@39339
  1655
                        {maxvars = maxvars, def_eq = false, next_idx = idx,
wenzelm@39339
  1656
                        bounds = [], wellformed = True} (Free ("dummy", T2))
wenzelm@39339
  1657
                      val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
wenzelm@39339
  1658
                    in
wenzelm@39339
  1659
                      (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
wenzelm@39339
  1660
                    end
wenzelm@39339
  1661
              val (next, copies, wf) = make_copies next_idx
wenzelm@39339
  1662
                (size_of_type thy model T1)
wenzelm@39339
  1663
              (* combine copies into a single interpretation *)
wenzelm@39339
  1664
              val intr = Node copies
wenzelm@39339
  1665
            in
wenzelm@39339
  1666
              (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39339
  1667
              (* condition                                                  *)
wenzelm@39339
  1668
              SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@39339
  1669
                def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@39339
  1670
                wellformed = SAnd (wellformed, wf)})
wenzelm@39339
  1671
            end
wenzelm@39339
  1672
        | Type _  => interpret_groundtype ()
wenzelm@39339
  1673
        | TFree _ => interpret_groundtype ()
wenzelm@39339
  1674
        | TVar  _ => interpret_groundtype ()
wenzelm@22567
  1675
      end
wenzelm@22567
  1676
  in
wenzelm@22567
  1677
    case AList.lookup (op =) terms t of
wenzelm@22567
  1678
      SOME intr =>
wenzelm@39339
  1679
        (* return an existing interpretation *)
wenzelm@39339
  1680
        SOME (intr, model, args)
wenzelm@22567
  1681
    | NONE =>
wenzelm@39339
  1682
        (case t of
wenzelm@39339
  1683
          Const (_, T) => interpret_groundterm T
wenzelm@39339
  1684
        | Free (_, T) => interpret_groundterm T
wenzelm@39339
  1685
        | Var (_, T) => interpret_groundterm T
wenzelm@39339
  1686
        | Bound i => SOME (List.nth (#bounds args, i), model, args)
wenzelm@39339
  1687
        | Abs (x, T, body) =>
wenzelm@39339
  1688
            let
wenzelm@39339
  1689
              (* create all constants of type 'T' *)
wenzelm@39339
  1690
              val constants = make_constants thy model T
wenzelm@39339
  1691
              (* interpret the 'body' separately for each constant *)
wenzelm@39339
  1692
              val (bodies, (model', args')) = fold_map
wenzelm@39339
  1693
                (fn c => fn (m, a) =>
wenzelm@39339
  1694
                  let
wenzelm@39339
  1695
                    (* add 'c' to 'bounds' *)
wenzelm@39339
  1696
                    val (i', m', a') = interpret thy m {maxvars = #maxvars a,
wenzelm@39339
  1697
                      def_eq = #def_eq a, next_idx = #next_idx a,
wenzelm@39339
  1698
                      bounds = (c :: #bounds a), wellformed = #wellformed a} body
wenzelm@39339
  1699
                  in
wenzelm@39339
  1700
                    (* keep the new model m' and 'next_idx' and 'wellformed', *)
wenzelm@39339
  1701
                    (* but use old 'bounds'                                   *)
wenzelm@39339
  1702
                    (i', (m', {maxvars = maxvars, def_eq = def_eq,
wenzelm@39339
  1703
                      next_idx = #next_idx a', bounds = bounds,
wenzelm@39339
  1704
                      wellformed = #wellformed a'}))
wenzelm@39339
  1705
                  end)
wenzelm@39339
  1706
                constants (model, args)
wenzelm@39339
  1707
            in
wenzelm@39339
  1708
              SOME (Node bodies, model', args')
wenzelm@39339
  1709
            end
wenzelm@39339
  1710
        | t1 $ t2 =>
wenzelm@39339
  1711
            let
wenzelm@39339
  1712
              (* interpret 't1' and 't2' separately *)
wenzelm@39339
  1713
              val (intr1, model1, args1) = interpret thy model args t1
wenzelm@39339
  1714
              val (intr2, model2, args2) = interpret thy model1 args1 t2
wenzelm@39339
  1715
            in
wenzelm@39339
  1716
              SOME (interpretation_apply (intr1, intr2), model2, args2)
wenzelm@39339
  1717
            end)
wenzelm@22567
  1718
  end;
webertj@14807
  1719
wenzelm@39339
  1720
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  1721
  (interpretation * model * arguments) option *)
webertj@14807
  1722
wenzelm@39339
  1723
fun Pure_interpreter thy model args t =
wenzelm@39339
  1724
  case t of
wenzelm@39339
  1725
    Const (@{const_name all}, _) $ t1 =>
wenzelm@22567
  1726
      let
wenzelm@22567
  1727
        val (i, m, a) = interpret thy model args t1
wenzelm@22567
  1728
      in
wenzelm@22567
  1729
        case i of
wenzelm@22567
  1730
          Node xs =>
wenzelm@39339
  1731
            (* 3-valued logic *)
wenzelm@39339
  1732
            let
wenzelm@39339
  1733
              val fmTrue  = PropLogic.all (map toTrue xs)
wenzelm@39339
  1734
              val fmFalse = PropLogic.exists (map toFalse xs)
wenzelm@39339
  1735
            in
wenzelm@39339
  1736
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39339
  1737
            end
wenzelm@22567
  1738
        | _ =>
wenzelm@22567
  1739
          raise REFUTE ("Pure_interpreter",
wenzelm@22567
  1740
            "\"all\" is followed by a non-function")
wenzelm@22567
  1741
      end
wenzelm@39339
  1742
  | Const (@{const_name all}, _) =>
wenzelm@22567
  1743
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1744
  | Const (@{const_name "=="}, _) $ t1 $ t2 =>
wenzelm@22567
  1745
      let
wenzelm@22567
  1746
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1747
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1748
      in
wenzelm@22567
  1749
        (* we use either 'make_def_equality' or 'make_equality' *)
wenzelm@22567
  1750
        SOME ((if #def_eq args then make_def_equality else make_equality)
wenzelm@22567
  1751
          (i1, i2), m2, a2)
wenzelm@22567
  1752
      end
wenzelm@39339
  1753
  | Const (@{const_name "=="}, _) $ t1 =>
wenzelm@22567
  1754
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1755
  | Const (@{const_name "=="}, _) =>
wenzelm@22567
  1756
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@39339
  1757
  | Const (@{const_name "==>"}, _) $ t1 $ t2 =>
wenzelm@22567
  1758
      (* 3-valued logic *)
wenzelm@22567
  1759
      let
wenzelm@22567
  1760
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1761
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1762
        val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
wenzelm@22567
  1763
        val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1764
      in
wenzelm@22567
  1765
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1766
      end
wenzelm@39339
  1767
  | Const (@{const_name "==>"}, _) $ t1 =>
wenzelm@22567
  1768
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1769
  | Const (@{const_name "==>"}, _) =>
wenzelm@22567
  1770
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@39339
  1771
  | _ => NONE;
webertj@14807
  1772
wenzelm@39339
  1773
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  1774
  (interpretation * model * arguments) option *)
webertj@14807
  1775
wenzelm@39339
  1776
fun HOLogic_interpreter thy model args t =
wenzelm@39339
  1777
(* Providing interpretations directly is more efficient than unfolding the *)
wenzelm@39339
  1778
(* logical constants.  In HOL however, logical constants can themselves be *)
wenzelm@39339
  1779
(* arguments.  They are then translated using eta-expansion.               *)
wenzelm@39339
  1780
  case t of
wenzelm@39339
  1781
    Const (@{const_name Trueprop}, _) =>
wenzelm@22567
  1782
      SOME (Node [TT, FF], model, args)
wenzelm@39339
  1783
  | Const (@{const_name Not}, _) =>
wenzelm@22567
  1784
      SOME (Node [FF, TT], model, args)
wenzelm@39339
  1785
  (* redundant, since 'True' is also an IDT constructor *)
wenzelm@39339
  1786
  | Const (@{const_name True}, _) =>
wenzelm@22567
  1787
      SOME (TT, model, args)
wenzelm@39339
  1788
  (* redundant, since 'False' is also an IDT constructor *)
wenzelm@39339
  1789
  | Const (@{const_name False}, _) =>
wenzelm@22567
  1790
      SOME (FF, model, args)
wenzelm@39339
  1791
  | Const (@{const_name All}, _) $ t1 =>  (* similar to "all" (Pure) *)
wenzelm@22567
  1792
      let
wenzelm@22567
  1793
        val (i, m, a) = interpret thy model args t1
wenzelm@22567
  1794
      in
wenzelm@22567
  1795
        case i of
wenzelm@22567
  1796
          Node xs =>
wenzelm@39339
  1797
            (* 3-valued logic *)
wenzelm@39339
  1798
            let
wenzelm@39339
  1799
              val fmTrue  = PropLogic.all (map toTrue xs)
wenzelm@39339
  1800
              val fmFalse = PropLogic.exists (map toFalse xs)
wenzelm@39339
  1801
            in
wenzelm@39339
  1802
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39339
  1803
            end
wenzelm@22567
  1804
        | _ =>
wenzelm@22567
  1805
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1806
            "\"All\" is followed by a non-function")
wenzelm@22567
  1807
      end
wenzelm@39339
  1808
  | Const (@{const_name All}, _) =>
wenzelm@22567
  1809
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1810
  | Const (@{const_name Ex}, _) $ t1 =>
wenzelm@22567
  1811
      let
wenzelm@22567
  1812
        val (i, m, a) = interpret thy model args t1
wenzelm@22567
  1813
      in
wenzelm@22567
  1814
        case i of
wenzelm@22567
  1815
          Node xs =>
wenzelm@39339
  1816
            (* 3-valued logic *)
wenzelm@39339
  1817
            let
wenzelm@39339
  1818
              val fmTrue  = PropLogic.exists (map toTrue xs)
wenzelm@39339
  1819
              val fmFalse = PropLogic.all (map toFalse xs)
wenzelm@39339
  1820
            in
wenzelm@39339
  1821
              SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@39339
  1822
            end
wenzelm@22567
  1823
        | _ =>
wenzelm@22567
  1824
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1825
            "\"Ex\" is followed by a non-function")
wenzelm@22567
  1826
      end
wenzelm@39339
  1827
  | Const (@{const_name Ex}, _) =>
wenzelm@22567
  1828
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1829
  | Const (@{const_name HOL.eq}, _) $ t1 $ t2 =>  (* similar to "==" (Pure) *)
wenzelm@22567
  1830
      let
wenzelm@22567
  1831
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1832
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1833
      in
wenzelm@22567
  1834
        SOME (make_equality (i1, i2), m2, a2)
wenzelm@22567
  1835
      end
wenzelm@39339
  1836
  | Const (@{const_name HOL.eq}, _) $ t1 =>
wenzelm@22567
  1837
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1838
  | Const (@{const_name HOL.eq}, _) =>
wenzelm@22567
  1839
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@39339
  1840
  | Const (@{const_name HOL.conj}, _) $ t1 $ t2 =>
wenzelm@22567
  1841
      (* 3-valued logic *)
wenzelm@22567
  1842
      let
wenzelm@22567
  1843
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1844
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1845
        val fmTrue       = PropLogic.SAnd (toTrue i1, toTrue i2)
wenzelm@22567
  1846
        val fmFalse      = PropLogic.SOr (toFalse i1, toFalse i2)
wenzelm@22567
  1847
      in
wenzelm@22567
  1848
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1849
      end
wenzelm@39339
  1850
  | Const (@{const_name HOL.conj}, _) $ t1 =>
wenzelm@22567
  1851
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1852
  | Const (@{const_name HOL.conj}, _) =>
wenzelm@22567
  1853
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1854
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1855
      (* "False & undef":                                          *)
wenzelm@22567
  1856
      (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
wenzelm@39339
  1857
  | Const (@{const_name HOL.disj}, _) $ t1 $ t2 =>
wenzelm@22567
  1858
      (* 3-valued logic *)
wenzelm@22567
  1859
      let
wenzelm@22567
  1860
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1861
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1862
        val fmTrue       = PropLogic.SOr (toTrue i1, toTrue i2)
wenzelm@22567
  1863
        val fmFalse      = PropLogic.SAnd (toFalse i1, toFalse i2)
wenzelm@22567
  1864
      in
wenzelm@22567
  1865
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1866
      end
wenzelm@39339
  1867
  | Const (@{const_name HOL.disj}, _) $ t1 =>
wenzelm@22567
  1868
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1869
  | Const (@{const_name HOL.disj}, _) =>
wenzelm@22567
  1870
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1871
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1872
      (* "True | undef":                                           *)
wenzelm@22567
  1873
      (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
wenzelm@39339
  1874
  | Const (@{const_name HOL.implies}, _) $ t1 $ t2 =>  (* similar to "==>" (Pure) *)
wenzelm@22567
  1875
      (* 3-valued logic *)
wenzelm@22567
  1876
      let
wenzelm@22567
  1877
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1878
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1879
        val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
wenzelm@22567
  1880
        val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1881
      in
wenzelm@22567
  1882
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1883
      end
wenzelm@39339
  1884
  | Const (@{const_name HOL.implies}, _) $ t1 =>
wenzelm@22567
  1885
      SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  1886
  | Const (@{const_name HOL.implies}, _) =>
wenzelm@22567
  1887
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1888
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1889
      (* "False --> undef":                                        *)
wenzelm@22567
  1890
      (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
wenzelm@39339
  1891
  | _ => NONE;
webertj@14807
  1892
wenzelm@39339
  1893
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  1894
  (interpretation * model * arguments) option *)
webertj@14807
  1895
wenzelm@39339
  1896
(* interprets variables and constants whose type is an IDT (this is        *)
wenzelm@39339
  1897
(* relatively easy and merely requires us to compute the size of the IDT); *)
wenzelm@39339
  1898
(* constructors of IDTs however are properly interpreted by                *)
wenzelm@39339
  1899
(* 'IDT_constructor_interpreter'                                           *)
webertj@15547
  1900
wenzelm@39339
  1901
fun IDT_interpreter thy model args t =
wenzelm@22567
  1902
  let
wenzelm@22567
  1903
    val (typs, terms) = model
wenzelm@22567
  1904
    (* Term.typ -> (interpretation * model * arguments) option *)
wenzelm@22567
  1905
    fun interpret_term (Type (s, Ts)) =
wenzelm@39339
  1906
          (case Datatype.get_info thy s of
wenzelm@39339
  1907
            SOME info =>  (* inductive datatype *)
wenzelm@39339
  1908
              let
wenzelm@39339
  1909
                (* int option -- only recursive IDTs have an associated depth *)
wenzelm@39339
  1910
                val depth = AList.lookup (op =) typs (Type (s, Ts))
wenzelm@39339
  1911
                (* sanity check: depth must be at least 0 *)
wenzelm@39339
  1912
                val _ =
wenzelm@39339
  1913
                  (case depth of SOME n =>
wenzelm@39339
  1914
                    if n < 0 then
wenzelm@39339
  1915
                      raise REFUTE ("IDT_interpreter", "negative depth")
wenzelm@39339
  1916
                    else ()
wenzelm@39339
  1917
                  | _ => ())
wenzelm@39339
  1918
              in
wenzelm@39339
  1919
                (* termination condition to avoid infinite recursion *)
wenzelm@39339
  1920
                if depth = (SOME 0) then
wenzelm@39339
  1921
                  (* return a leaf of size 0 *)
wenzelm@39339
  1922
                  SOME (Leaf [], model, args)
wenzelm@39339
  1923
                else
wenzelm@39339
  1924
                  let
wenzelm@39339
  1925
                    val index               = #index info
wenzelm@39339
  1926
                    val descr               = #descr info
wenzelm@39339
  1927
                    val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39339
  1928
                    val typ_assoc           = dtyps ~~ Ts
wenzelm@39339
  1929
                    (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39339
  1930
                    val _ =
wenzelm@39339
  1931
                      if Library.exists (fn d =>
wenzelm@39339
  1932
                        case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39339
  1933
                      then
wenzelm@39339
  1934
                        raise REFUTE ("IDT_interpreter",
wenzelm@39339
  1935
                          "datatype argument (for type "
wenzelm@39339
  1936
                          ^ Syntax.string_of_typ_global thy (Type (s, Ts))
wenzelm@39339
  1937
                          ^ ") is not a variable")
wenzelm@39339
  1938
                      else ()
wenzelm@39339
  1939
                    (* if the model specifies a depth for the current type, *)
wenzelm@39339
  1940
                    (* decrement it to avoid infinite recursion             *)
wenzelm@39339
  1941
                    val typs' = case depth of NONE => typs | SOME n =>
wenzelm@39339
  1942
                      AList.update (op =) (Type (s, Ts), n-1) typs
wenzelm@39339
  1943
                    (* recursively compute the size of the datatype *)
wenzelm@39339
  1944
                    val size     = size_of_dtyp thy typs' descr typ_assoc constrs
wenzelm@39339
  1945
                    val next_idx = #next_idx args
wenzelm@39339
  1946
                    val next     = next_idx+size
wenzelm@39339
  1947
                    (* check if 'maxvars' is large enough *)
wenzelm@39339
  1948
                    val _        = (if next-1 > #maxvars args andalso
wenzelm@39339
  1949
                      #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
wenzelm@39339
  1950
                    (* prop_formula list *)
wenzelm@39339
  1951
                    val fms      = map BoolVar (next_idx upto (next_idx+size-1))
wenzelm@39339
  1952
                    (* interpretation *)
wenzelm@39339
  1953
                    val intr     = Leaf fms
wenzelm@39339
  1954
                    (* prop_formula list -> prop_formula *)
wenzelm@39339
  1955
                    fun one_of_two_false [] = True
wenzelm@39339
  1956
                      | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
wenzelm@39339
  1957
                          SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@39339
  1958
                    (* prop_formula *)
wenzelm@39339
  1959
                    val wf = one_of_two_false fms
wenzelm@39339
  1960
                  in
wenzelm@39339
  1961
                    (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@39339
  1962
                    (* condition                                                  *)
wenzelm@39339
  1963
                    SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
wenzelm@39339
  1964
                      def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
wenzelm@39339
  1965
                      wellformed = SAnd (#wellformed args, wf)})
wenzelm@39339
  1966
                  end
wenzelm@39339
  1967
              end
wenzelm@39339
  1968
          | NONE =>  (* not an inductive datatype *)
wenzelm@39339
  1969
              NONE)
wenzelm@22567
  1970
      | interpret_term _ =  (* a (free or schematic) type variable *)
wenzelm@39339
  1971
          NONE
wenzelm@22567
  1972
  in
wenzelm@22567
  1973
    case AList.lookup (op =) terms t of
wenzelm@22567
  1974
      SOME intr =>
wenzelm@39339
  1975
        (* return an existing interpretation *)
wenzelm@39339
  1976
        SOME (intr, model, args)
wenzelm@22567
  1977
    | NONE =>
wenzelm@39339
  1978
        (case t of
wenzelm@39339
  1979
          Free (_, T) => interpret_term T
wenzelm@39339
  1980
        | Var (_, T) => interpret_term T
wenzelm@39339
  1981
        | Const (_, T) => interpret_term T
wenzelm@39339
  1982
        | _ => NONE)
wenzelm@22567
  1983
  end;
webertj@15547
  1984
wenzelm@39339
  1985
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  1986
  (interpretation * model * arguments) option *)
webertj@15547
  1987
wenzelm@39339
  1988
(* This function imposes an order on the elements of a datatype fragment  *)
wenzelm@39339
  1989
(* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
wenzelm@39339
  1990
(* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
wenzelm@39339
  1991
(* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
wenzelm@39339
  1992
(* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
wenzelm@39339
  1993
(* same for recursive datatypes, although the computation of indices gets *)
wenzelm@39339
  1994
(* a little tricky.                                                       *)
webertj@25014
  1995
wenzelm@39339
  1996
fun IDT_constructor_interpreter thy model args t =
wenzelm@22567
  1997
  let
webertj@25014
  1998
    (* returns a list of canonical representations for terms of the type 'T' *)
webertj@25014
  1999
    (* It would be nice if we could just use 'print' for this, but 'print'   *)
webertj@25014
  2000
    (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
webertj@25014
  2001
    (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
webertj@25014
  2002
    (* (Term.typ * int) list -> Term.typ -> Term.term list *)
webertj@25014
  2003
    fun canonical_terms typs T =
wenzelm@39339
  2004
          (case T of
wenzelm@39339
  2005
            Type ("fun", [T1, T2]) =>
wenzelm@39339
  2006
            (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
wenzelm@39339
  2007
            (* least not for 'T2'                                               *)
wenzelm@39339
  2008
            let
wenzelm@39339
  2009
              (* returns a list of lists, each one consisting of n (possibly *)
wenzelm@39339
  2010
              (* identical) elements from 'xs'                               *)
wenzelm@39339
  2011
              (* int -> 'a list -> 'a list list *)
wenzelm@39339
  2012
              fun pick_all 1 xs = map single xs
wenzelm@39339
  2013
                | pick_all n xs =
wenzelm@39339
  2014
                    let val rec_pick = pick_all (n-1) xs in
wenzelm@39339
  2015
                      maps (fn x => map (cons x) rec_pick) xs
wenzelm@39339
  2016
                    end
wenzelm@39339
  2017
              (* ["x1", ..., "xn"] *)
wenzelm@39339
  2018
              val terms1 = canonical_terms typs T1
wenzelm@39339
  2019
              (* ["y1", ..., "ym"] *)
wenzelm@39339
  2020
              val terms2 = canonical_terms typs T2
wenzelm@39339
  2021
              (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
wenzelm@39339
  2022
              (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
wenzelm@39339
  2023
              val functions = map (curry (op ~~) terms1)
wenzelm@39339
  2024
                (pick_all (length terms1) terms2)
wenzelm@39339
  2025
              (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
wenzelm@39339
  2026
              (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
wenzelm@39339
  2027
              val pairss = map (map HOLogic.mk_prod) functions
wenzelm@39339
  2028
              (* Term.typ *)
wenzelm@39339
  2029
              val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
wenzelm@39339
  2030
              val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
wenzelm@39339
  2031
              (* Term.term *)
wenzelm@39339
  2032
              val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
wenzelm@39339
  2033
              val HOLogic_insert    =
wenzelm@39339
  2034
                Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
wenzelm@39339
  2035
            in
wenzelm@39339
  2036
              (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
wenzelm@39339
  2037
              map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
wenzelm@39339
  2038
                HOLogic_empty_set) pairss
webertj@25014
  2039
            end
webertj@25014
  2040
      | Type (s, Ts) =>
wenzelm@39339
  2041
          (case Datatype.get_info thy s of
wenzelm@39339
  2042
            SOME info =>
wenzelm@39339
  2043
              (case AList.lookup (op =) typs T of
wenzelm@39339
  2044
                SOME 0 =>
wenzelm@39339
  2045
                  (* termination condition to avoid infinite recursion *)
wenzelm@39339
  2046
                  []  (* at depth 0, every IDT is empty *)
wenzelm@39339
  2047
              | _ =>
webertj@25014
  2048
                let
wenzelm@39339
  2049
                  val index = #index info
wenzelm@39339
  2050
                  val descr = #descr info
wenzelm@39339
  2051
                  val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39339
  2052
                  val typ_assoc = dtyps ~~ Ts
wenzelm@39339
  2053
                  (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39339
  2054
                  val _ =
wenzelm@39339
  2055
                    if Library.exists (fn d =>
wenzelm@39339
  2056
                      case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39339
  2057
                    then
wenzelm@39339
  2058
                      raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2059
                        "datatype argument (for type "
wenzelm@39339
  2060
                        ^ Syntax.string_of_typ_global thy T
wenzelm@39339
  2061
                        ^ ") is not a variable")
wenzelm@39339
  2062
                    else ()
wenzelm@39339
  2063
                  (* decrement depth for the IDT 'T' *)
wenzelm@39339
  2064
                  val typs' =
wenzelm@39339
  2065
                    (case AList.lookup (op =) typs T of NONE => typs
wenzelm@39339
  2066
                    | SOME n => AList.update (op =) (T, n-1) typs)
wenzelm@39339
  2067
                  fun constructor_terms terms [] = terms
wenzelm@39339
  2068
                    | constructor_terms terms (d::ds) =
wenzelm@39339
  2069
                        let
wenzelm@39339
  2070
                          val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39339
  2071
                          val d_terms = canonical_terms typs' dT
wenzelm@39339
  2072
                        in
wenzelm@39339
  2073
                          (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
wenzelm@39339
  2074
                          (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
wenzelm@39339
  2075
                          constructor_terms
wenzelm@39339
  2076
                            (map_product (curry op $) terms d_terms) ds
wenzelm@39339
  2077
                        end
webertj@25014
  2078
                in
wenzelm@39339
  2079
                  (* C_i ... < C_j ... if i < j *)
wenzelm@39339
  2080
                  maps (fn (cname, ctyps) =>
wenzelm@39339
  2081
                    let
wenzelm@39339
  2082
                      val cTerm = Const (cname,
wenzelm@39339
  2083
                        map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
wenzelm@39339
  2084
                    in
wenzelm@39339
  2085
                      constructor_terms [cTerm] ctyps
wenzelm@39339
  2086
                    end) constrs
wenzelm@39339
  2087
                end)
wenzelm@39339
  2088
          | NONE =>
wenzelm@39339
  2089
              (* not an inductive datatype; in this case the argument types in *)
wenzelm@39339
  2090
              (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
wenzelm@39339
  2091
              map (fn intr => print thy (typs, []) T intr (K false))
wenzelm@39339
  2092
                (make_constants thy (typs, []) T))
wenzelm@39339
  2093
      | _ =>  (* TFree ..., TVar ... *)
webertj@25014
  2094
          map (fn intr => print thy (typs, []) T intr (K false))
webertj@25014
  2095
            (make_constants thy (typs, []) T))
wenzelm@22567
  2096
    val (typs, terms) = model
wenzelm@22567
  2097
  in
wenzelm@22567
  2098
    case AList.lookup (op =) terms t of
wenzelm@22567
  2099
      SOME intr =>
wenzelm@39339
  2100
        (* return an existing interpretation *)
wenzelm@39339
  2101
        SOME (intr, model, args)
wenzelm@22567
  2102
    | NONE =>
wenzelm@39339
  2103
        (case t of
wenzelm@39339
  2104
          Const (s, T) =>
wenzelm@39339
  2105
            (case body_type T of
wenzelm@39339
  2106
              Type (s', Ts') =>
wenzelm@39339
  2107
                (case Datatype.get_info thy s' of
wenzelm@39339
  2108
                  SOME info =>  (* body type is an inductive datatype *)
wenzelm@22567
  2109
                    let
wenzelm@39339
  2110
                      val index               = #index info
wenzelm@39339
  2111
                      val descr               = #descr info
wenzelm@39339
  2112
                      val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39339
  2113
                      val typ_assoc           = dtyps ~~ Ts'
wenzelm@39339
  2114
                      (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39339
  2115
                      val _ = if Library.exists (fn d =>
wenzelm@39339
  2116
                          case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
webertj@25014
  2117
                        then
webertj@25014
  2118
                          raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2119
                            "datatype argument (for type "
wenzelm@39339
  2120
                            ^ Syntax.string_of_typ_global thy (Type (s', Ts'))
wenzelm@39339
  2121
                            ^ ") is not a variable")
webertj@25014
  2122
                        else ()
wenzelm@39339
  2123
                      (* split the constructors into those occuring before/after *)
wenzelm@39339
  2124
                      (* 'Const (s, T)'                                          *)
wenzelm@39339
  2125
                      val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
wenzelm@39339
  2126
                        not (cname = s andalso Sign.typ_instance thy (T,
wenzelm@39339
  2127
                          map (typ_of_dtyp descr typ_assoc) ctypes
wenzelm@39339
  2128
                            ---> Type (s', Ts')))) constrs
wenzelm@39339
  2129
                    in
wenzelm@39339
  2130
                      case constrs2 of
wenzelm@39339
  2131
                        [] =>
wenzelm@39339
  2132
                          (* 'Const (s, T)' is not a constructor of this datatype *)
wenzelm@39339
  2133
                          NONE
wenzelm@39339
  2134
                      | (_, ctypes)::cs =>
wenzelm@39339
  2135
                          let
wenzelm@39339
  2136
                            (* int option -- only /recursive/ IDTs have an associated *)
wenzelm@39339
  2137
                            (*               depth                                    *)
wenzelm@39339
  2138
                            val depth = AList.lookup (op =) typs (Type (s', Ts'))
wenzelm@39339
  2139
                            (* this should never happen: at depth 0, this IDT fragment *)
wenzelm@39339
  2140
                            (* is definitely empty, and in this case we don't need to  *)
wenzelm@39339
  2141
                            (* interpret its constructors                              *)
wenzelm@39339
  2142
                            val _ = (case depth of SOME 0 =>
wenzelm@33262
  2143
                                raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2144
                                  "depth is 0")
wenzelm@39339
  2145
                              | _ => ())
wenzelm@39339
  2146
                            val typs' = (case depth of NONE => typs | SOME n =>
wenzelm@39339
  2147
                              AList.update (op =) (Type (s', Ts'), n-1) typs)
wenzelm@39339
  2148
                            (* elements of the datatype come before elements generated *)
wenzelm@39339
  2149
                            (* by 'Const (s, T)' iff they are generated by a           *)
wenzelm@39339
  2150
                            (* constructor in constrs1                                 *)
wenzelm@39339
  2151
                            val offset = size_of_dtyp thy typs' descr typ_assoc constrs1
wenzelm@39339
  2152
                            (* compute the total (current) size of the datatype *)
wenzelm@39339
  2153
                            val total = offset +
wenzelm@39339
  2154
                              size_of_dtyp thy typs' descr typ_assoc constrs2
wenzelm@39339
  2155
                            (* sanity check *)
wenzelm@39339
  2156
                            val _ = if total <> size_of_type thy (typs, [])
wenzelm@39339
  2157
                              (Type (s', Ts')) then
wenzelm@39339
  2158
                                raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2159
                                  "total is not equal to current size")
wenzelm@39339
  2160
                              else ()
wenzelm@39339
  2161
                            (* returns an interpretation where everything is mapped to *)
wenzelm@39339
  2162
                            (* an "undefined" element of the datatype                  *)
wenzelm@39339
  2163
                            fun make_undef [] = Leaf (replicate total False)
wenzelm@39339
  2164
                              | make_undef (d::ds) =
wenzelm@39339
  2165
                                  let
wenzelm@39339
  2166
                                    (* compute the current size of the type 'd' *)
wenzelm@39339
  2167
                                    val dT   = typ_of_dtyp descr typ_assoc d
wenzelm@39339
  2168
                                    val size = size_of_type thy (typs, []) dT
wenzelm@39339
  2169
                                  in
wenzelm@39339
  2170
                                    Node (replicate size (make_undef ds))
wenzelm@39339
  2171
                                  end
wenzelm@39339
  2172
                            (* returns the interpretation for a constructor *)
wenzelm@39339
  2173
                            fun make_constr [] offset =
wenzelm@39339
  2174
                                  if offset < total then
wenzelm@39339
  2175
                                    (Leaf (replicate offset False @ True ::
wenzelm@39339
  2176
                                      (replicate (total - offset - 1) False)), offset + 1)
wenzelm@39339
  2177
                                  else
wenzelm@39339
  2178
                                    raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2179
                                      "offset >= total")
wenzelm@39339
  2180
                              | make_constr (d::ds) offset =
wenzelm@39339
  2181
                                  let
wenzelm@39339
  2182
                                    (* Term.typ *)
wenzelm@39339
  2183
                                    val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39339
  2184
                                    (* compute canonical term representations for all   *)
wenzelm@39339
  2185
                                    (* elements of the type 'd' (with the reduced depth *)
wenzelm@39339
  2186
                                    (* for the IDT)                                     *)
wenzelm@39339
  2187
                                    val terms' = canonical_terms typs' dT
wenzelm@39339
  2188
                                    (* sanity check *)
wenzelm@39339
  2189
                                    val _ =
wenzelm@39339
  2190
                                      if length terms' <> size_of_type thy (typs', []) dT
wenzelm@39339
  2191
                                      then
wenzelm@39339
  2192
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2193
                                          "length of terms' is not equal to old size")
wenzelm@39339
  2194
                                      else ()
wenzelm@39339
  2195
                                    (* compute canonical term representations for all   *)
wenzelm@39339
  2196
                                    (* elements of the type 'd' (with the current depth *)
wenzelm@39339
  2197
                                    (* for the IDT)                                     *)
wenzelm@39339
  2198
                                    val terms = canonical_terms typs dT
wenzelm@39339
  2199
                                    (* sanity check *)
wenzelm@39339
  2200
                                    val _ =
wenzelm@39339
  2201
                                      if length terms <> size_of_type thy (typs, []) dT
wenzelm@39339
  2202
                                      then
wenzelm@39339
  2203
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2204
                                          "length of terms is not equal to current size")
wenzelm@39339
  2205
                                      else ()
wenzelm@39339
  2206
                                    (* sanity check *)
wenzelm@39339
  2207
                                    val _ =
wenzelm@39339
  2208
                                      if length terms < length terms' then
wenzelm@39339
  2209
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2210
                                          "current size is less than old size")
wenzelm@39339
  2211
                                      else ()
wenzelm@39339
  2212
                                    (* sanity check: every element of terms' must also be *)
wenzelm@39339
  2213
                                    (*               present in terms                     *)
wenzelm@39339
  2214
                                    val _ =
wenzelm@39339
  2215
                                      if forall (member (op =) terms) terms' then ()
wenzelm@39339
  2216
                                      else
wenzelm@39339
  2217
                                        raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2218
                                          "element has disappeared")
wenzelm@39339
  2219
                                    (* sanity check: the order on elements of terms' is    *)
wenzelm@39339
  2220
                                    (*               the same in terms, for those elements *)
wenzelm@39339
  2221
                                    val _ =
wenzelm@39339
  2222
                                      let
wenzelm@39339
  2223
                                        fun search (x::xs) (y::ys) =
wenzelm@39339
  2224
                                              if x = y then search xs ys else search (x::xs) ys
wenzelm@39339
  2225
                                          | search (x::xs) [] =
wenzelm@39339
  2226
                                              raise REFUTE ("IDT_constructor_interpreter",
wenzelm@39339
  2227
                                                "element order not preserved")
wenzelm@39339
  2228
                                          | search [] _ = ()
wenzelm@39339
  2229
                                      in search terms' terms end
wenzelm@39339
  2230
                                    (* int * interpretation list *)
wenzelm@39339
  2231
                                    val (intrs, new_offset) =
wenzelm@39339
  2232
                                      fold_map (fn t_elem => fn off =>
wenzelm@39339
  2233
                                        (* if 't_elem' existed at the previous depth,    *)
wenzelm@39339
  2234
                                        (* proceed recursively, otherwise map the entire *)
wenzelm@39339
  2235
                                        (* subtree to "undefined"                        *)
wenzelm@39339
  2236
                                        if member (op =) terms' t_elem then
wenzelm@39339
  2237
                                          make_constr ds off
wenzelm@39339
  2238
                                        else
wenzelm@39339
  2239
                                          (make_undef ds, off))
wenzelm@39339
  2240
                                      terms offset
wenzelm@39339
  2241
                                  in
wenzelm@39339
  2242
                                    (Node intrs, new_offset)
wenzelm@39339
  2243
                                  end
wenzelm@39339
  2244
                          in
wenzelm@39339
  2245
                            SOME (fst (make_constr ctypes offset), model, args)
wenzelm@39339
  2246
                          end
wenzelm@22567
  2247
                    end
wenzelm@39339
  2248
                | NONE =>  (* body type is not an inductive datatype *)
wenzelm@39339
  2249
                    NONE)
wenzelm@39339
  2250
            | _ =>  (* body type is a (free or schematic) type variable *)
wenzelm@39339
  2251
              NONE)
wenzelm@39339
  2252
        | _ =>  (* term is not a constant *)
wenzelm@22567
  2253
          NONE)
wenzelm@22567
  2254
  end;
webertj@14807
  2255
wenzelm@39339
  2256
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2257
  (interpretation * model * arguments) option *)
webertj@14807
  2258
wenzelm@39339
  2259
(* Difficult code ahead.  Make sure you understand the                *)
wenzelm@39339
  2260
(* 'IDT_constructor_interpreter' and the order in which it enumerates *)
wenzelm@39339
  2261
(* elements of an IDT before you try to understand this function.     *)
webertj@15547
  2262
wenzelm@39339
  2263
fun IDT_recursion_interpreter thy model args t =
wenzelm@39339
  2264
  (* careful: here we descend arbitrarily deep into 't', possibly before *)
wenzelm@39339
  2265
  (* any other interpreter for atomic terms has had a chance to look at  *)
wenzelm@39339
  2266
  (* 't'                                                                 *)
wenzelm@39339
  2267
  case strip_comb t of
wenzelm@39339
  2268
    (Const (s, T), params) =>
wenzelm@22567
  2269
      (* iterate over all datatypes in 'thy' *)
wenzelm@22567
  2270
      Symtab.fold (fn (_, info) => fn result =>
wenzelm@22567
  2271
        case result of
wenzelm@22567
  2272
          SOME _ =>
wenzelm@39339
  2273
            result  (* just keep 'result' *)
wenzelm@22567
  2274
        | NONE =>
wenzelm@39339
  2275
            if member (op =) (#rec_names info) s then
wenzelm@39339
  2276
              (* we do have a recursion operator of one of the (mutually *)
wenzelm@39339
  2277
              (* recursive) datatypes given by 'info'                    *)
wenzelm@39339
  2278
              let
wenzelm@39339
  2279
                (* number of all constructors, including those of different  *)
wenzelm@39339
  2280
                (* (mutually recursive) datatypes within the same descriptor *)
wenzelm@39339
  2281
                val mconstrs_count =
wenzelm@39339
  2282
                  Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
wenzelm@39339
  2283
              in
wenzelm@39339
  2284
                if mconstrs_count < length params then
wenzelm@39339
  2285
                  (* too many actual parameters; for now we'll use the *)
wenzelm@39339
  2286
                  (* 'stlc_interpreter' to strip off one application   *)
wenzelm@39339
  2287
                  NONE
wenzelm@39339
  2288
                else if mconstrs_count > length params then
wenzelm@39339
  2289
                  (* too few actual parameters; we use eta expansion          *)
wenzelm@39339
  2290
                  (* Note that the resulting expansion of lambda abstractions *)
wenzelm@39339
  2291
                  (* by the 'stlc_interpreter' may be rather slow (depending  *)
wenzelm@39339
  2292
                  (* on the argument types and the size of the IDT, of        *)
wenzelm@39339
  2293
                  (* course).                                                 *)
wenzelm@39339
  2294
                  SOME (interpret thy model args (eta_expand t
wenzelm@39339
  2295
                    (mconstrs_count - length params)))
wenzelm@39339
  2296
                else  (* mconstrs_count = length params *)
wenzelm@39339
  2297
                  let
wenzelm@39339
  2298
                    (* interpret each parameter separately *)
wenzelm@39339
  2299
                    val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
wenzelm@39339
  2300
                      let
wenzelm@39339
  2301
                        val (i, m', a') = interpret thy m a p
wenzelm@39339
  2302
                      in
wenzelm@39339
  2303
                        (i, (m', a'))
wenzelm@39339
  2304
                      end) params (model, args)
wenzelm@39339
  2305
                    val (typs, _) = model'
wenzelm@39339
  2306
                    (* 'index' is /not/ necessarily the index of the IDT that *)
wenzelm@39339
  2307
                    (* the recursion operator is associated with, but merely  *)
wenzelm@39339
  2308
                    (* the index of some mutually recursive IDT               *)
wenzelm@39339
  2309
                    val index         = #index info
wenzelm@39339
  2310
                    val descr         = #descr info
wenzelm@39339
  2311
                    val (_, dtyps, _) = the (AList.lookup (op =) descr index)
wenzelm@39339
  2312
                    (* sanity check: we assume that the order of constructors *)
wenzelm@39339
  2313
                    (*               in 'descr' is the same as the order of   *)
wenzelm@39339
  2314
                    (*               corresponding parameters, otherwise the  *)
wenzelm@39339
  2315
                    (*               association code below won't match the   *)
wenzelm@39339
  2316
                    (*               right constructors/parameters; we also   *)
wenzelm@39339
  2317
                    (*               assume that the order of recursion       *)
wenzelm@39339
  2318
                    (*               operators in '#rec_names info' is the    *)
wenzelm@39339
  2319
                    (*               same as the order of corresponding       *)
wenzelm@39339
  2320
                    (*               datatypes in 'descr'                     *)
wenzelm@39339
  2321
                    val _ = if map fst descr <> (0 upto (length descr - 1)) then
wenzelm@39339
  2322
                        raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2323
                          "order of constructors and corresponding parameters/" ^
wenzelm@39339
  2324
                            "recursion operators and corresponding datatypes " ^
wenzelm@39339
  2325
                            "different?")
wenzelm@39339
  2326
                      else ()
wenzelm@39339
  2327
                    (* sanity check: every element in 'dtyps' must be a *)
wenzelm@39339
  2328
                    (*               'DtTFree'                          *)
wenzelm@39339
  2329
                    val _ =
wenzelm@39339
  2330
                      if Library.exists (fn d =>
wenzelm@39339
  2331
                        case d of Datatype_Aux.DtTFree _ => false
wenzelm@39339
  2332
                                | _ => true) dtyps
wenzelm@39339
  2333
                      then
wenzelm@39339
  2334
                        raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2335
                          "datatype argument is not a variable")
wenzelm@39339
  2336
                      else ()
wenzelm@39339
  2337
                    (* the type of a recursion operator is *)
wenzelm@39339
  2338
                    (* [T1, ..., Tn, IDT] ---> Tresult     *)
wenzelm@39339
  2339
                    val IDT = List.nth (binder_types T, mconstrs_count)
wenzelm@39339
  2340
                    (* by our assumption on the order of recursion operators *)
wenzelm@39339
  2341
                    (* and datatypes, this is the index of the datatype      *)
wenzelm@39339
  2342
                    (* corresponding to the given recursion operator         *)
wenzelm@39339
  2343
                    val idt_index = find_index (fn s' => s' = s) (#rec_names info)
wenzelm@39339
  2344
                    (* mutually recursive types must have the same type   *)
wenzelm@39339
  2345
                    (* parameters, unless the mutual recursion comes from *)
wenzelm@39339
  2346
                    (* indirect recursion                                 *)
wenzelm@39339
  2347
                    fun rec_typ_assoc acc [] = acc
wenzelm@39339
  2348
                      | rec_typ_assoc acc ((d, T)::xs) =
wenzelm@39339
  2349
                          (case AList.lookup op= acc d of
wenzelm@39339
  2350
                            NONE =>
wenzelm@39339
  2351
                              (case d of
wenzelm@39339
  2352
                                Datatype_Aux.DtTFree _ =>
wenzelm@39339
  2353
                                (* add the association, proceed *)
wenzelm@39339
  2354
                                rec_typ_assoc ((d, T)::acc) xs
wenzelm@39339
  2355
                              | Datatype_Aux.DtType (s, ds) =>
wenzelm@39339
  2356
                                  let
wenzelm@39339
  2357
                                    val (s', Ts) = dest_Type T
wenzelm@39339
  2358
                                  in
wenzelm@39339
  2359
                                    if s=s' then
wenzelm@39339
  2360
                                      rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
wenzelm@39339
  2361
                                    else
wenzelm@39339
  2362
                                      raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2363
                                        "DtType/Type mismatch")
wenzelm@39339
  2364
                                  end
wenzelm@39339
  2365
                              | Datatype_Aux.DtRec i =>
wenzelm@39339
  2366
                                  let
wenzelm@39339
  2367
                                    val (_, ds, _) = the (AList.lookup (op =) descr i)
wenzelm@39339
  2368
                                    val (_, Ts)    = dest_Type T
wenzelm@39339
  2369
                                  in
wenzelm@39339
  2370
                                    rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
wenzelm@39339
  2371
                                  end)
wenzelm@39339
  2372
                          | SOME T' =>
wenzelm@39339
  2373
                              if T=T' then
wenzelm@39339
  2374
                                (* ignore the association since it's already *)
wenzelm@39339
  2375
                                (* present, proceed                          *)
wenzelm@39339
  2376
                                rec_typ_assoc acc xs
wenzelm@39339
  2377
                              else
wenzelm@39339
  2378
                                raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2379
                                  "different type associations for the same dtyp"))
wenzelm@39339
  2380
                    val typ_assoc = filter
wenzelm@39339
  2381
                      (fn (Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
wenzelm@39339
  2382
                      (rec_typ_assoc []
wenzelm@39339
  2383
                        (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
wenzelm@39339
  2384
                    (* sanity check: typ_assoc must associate types to the   *)
wenzelm@39339
  2385
                    (*               elements of 'dtyps' (and only to those) *)
wenzelm@39339
  2386
                    val _ =
wenzelm@39339
  2387
                      if not (eq_set (op =) (dtyps, map fst typ_assoc))
wenzelm@39339
  2388
                      then
wenzelm@39339
  2389
                        raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2390
                          "type association has extra/missing elements")
wenzelm@39339
  2391
                      else ()
wenzelm@39339
  2392
                    (* interpret each constructor in the descriptor (including *)
wenzelm@39339
  2393
                    (* those of mutually recursive datatypes)                  *)
wenzelm@39339
  2394
                    (* (int * interpretation list) list *)
wenzelm@39339
  2395
                    val mc_intrs = map (fn (idx, (_, _, cs)) =>
wenzelm@39339
  2396
                      let
wenzelm@39339
  2397
                        val c_return_typ = typ_of_dtyp descr typ_assoc
wenzelm@39339
  2398
                          (Datatype_Aux.DtRec idx)
wenzelm@39339
  2399
                      in
wenzelm@39339
  2400
                        (idx, map (fn (cname, cargs) =>
wenzelm@39339
  2401
                          (#1 o interpret thy (typs, []) {maxvars=0,
wenzelm@39339
  2402
                            def_eq=false, next_idx=1, bounds=[],
wenzelm@39339
  2403
                            wellformed=True}) (Const (cname, map (typ_of_dtyp
wenzelm@39339
  2404
                            descr typ_assoc) cargs ---> c_return_typ))) cs)
wenzelm@39339
  2405
                      end) descr
wenzelm@39339
  2406
                    (* associate constructors with corresponding parameters *)
wenzelm@39339
  2407
                    (* (int * (interpretation * interpretation) list) list *)
wenzelm@39339
  2408
                    val (mc_p_intrs, p_intrs') = fold_map
wenzelm@39339
  2409
                      (fn (idx, c_intrs) => fn p_intrs' =>
webertj@25014
  2410
                        let
wenzelm@39339
  2411
                          val len = length c_intrs
webertj@25014
  2412
                        in
wenzelm@39339
  2413
                          ((idx, c_intrs ~~ List.take (p_intrs', len)),
wenzelm@39339
  2414
                            List.drop (p_intrs', len))
wenzelm@39339
  2415
                        end) mc_intrs p_intrs
wenzelm@39339
  2416
                    (* sanity check: no 'p_intr' may be left afterwards *)
wenzelm@39339
  2417
                    val _ =
wenzelm@39339
  2418
                      if p_intrs' <> [] then
wenzelm@39339
  2419
                        raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2420
                          "more parameter than constructor interpretations")
wenzelm@39339
  2421
                      else ()
wenzelm@39339
  2422
                    (* The recursion operator, applied to 'mconstrs_count'     *)
wenzelm@39339
  2423
                    (* arguments, is a function that maps every element of the *)
wenzelm@39339
  2424
                    (* inductive datatype to an element of some result type.   *)
wenzelm@39339
  2425
                    (* Recursion operators for mutually recursive IDTs are     *)
wenzelm@39339
  2426
                    (* translated simultaneously.                              *)
wenzelm@39339
  2427
                    (* Since the order on datatype elements is given by an     *)
wenzelm@39339
  2428
                    (* order on constructors (and then by the order on         *)
wenzelm@39339
  2429
                    (* argument tuples), we can simply copy corresponding      *)
wenzelm@39339
  2430
                    (* subtrees from 'p_intrs', in the order in which they are *)
wenzelm@39339
  2431
                    (* given.                                                  *)
wenzelm@39339
  2432
                    (* interpretation * interpretation -> interpretation list *)
wenzelm@39339
  2433
                    fun ci_pi (Leaf xs, pi) =
wenzelm@39339
  2434
                          (* if the constructor does not match the arguments to a *)
wenzelm@39339
  2435
                          (* defined element of the IDT, the corresponding value  *)
wenzelm@39339
  2436
                          (* of the parameter must be ignored                     *)
wenzelm@39339
  2437
                          if List.exists (equal True) xs then [pi] else []
wenzelm@39339
  2438
                      | ci_pi (Node xs, Node ys) = maps ci_pi (xs ~~ ys)
wenzelm@39339
  2439
                      | ci_pi (Node _, Leaf _) =
wenzelm@39339
  2440
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2441
                            "constructor takes more arguments than the " ^
wenzelm@39339
  2442
                              "associated parameter")
wenzelm@39339
  2443
                    (* (int * interpretation list) list *)
wenzelm@39339
  2444
                    val rec_operators = map (fn (idx, c_p_intrs) =>
wenzelm@39339
  2445
                      (idx, maps ci_pi c_p_intrs)) mc_p_intrs
wenzelm@39339
  2446
                    (* sanity check: every recursion operator must provide as  *)
wenzelm@39339
  2447
                    (*               many values as the corresponding datatype *)
wenzelm@39339
  2448
                    (*               has elements                              *)
wenzelm@39339
  2449
                    val _ = map (fn (idx, intrs) =>
wenzelm@39339
  2450
                      let
wenzelm@39339
  2451
                        val T = typ_of_dtyp descr typ_assoc
wenzelm@39339
  2452
                          (Datatype_Aux.DtRec idx)
wenzelm@39339
  2453
                      in
wenzelm@39339
  2454
                        if length intrs <> size_of_type thy (typs, []) T then
wenzelm@39339
  2455
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2456
                            "wrong number of interpretations for rec. operator")
wenzelm@39339
  2457
                        else ()
wenzelm@39339
  2458
                      end) rec_operators
wenzelm@39339
  2459
                    (* For non-recursive datatypes, we are pretty much done at *)
wenzelm@39339
  2460
                    (* this point.  For recursive datatypes however, we still  *)
wenzelm@39339
  2461
                    (* need to apply the interpretations in 'rec_operators' to *)
wenzelm@39339
  2462
                    (* (recursively obtained) interpretations for recursive    *)
wenzelm@39339
  2463
                    (* constructor arguments.  To do so more efficiently, we   *)
wenzelm@39339
  2464
                    (* copy 'rec_operators' into arrays first.  Each Boolean   *)
wenzelm@39339
  2465
                    (* indicates whether the recursive arguments have been     *)
wenzelm@39339
  2466
                    (* considered already.                                     *)
wenzelm@39339
  2467
                    (* (int * (bool * interpretation) Array.array) list *)
wenzelm@39339
  2468
                    val REC_OPERATORS = map (fn (idx, intrs) =>
wenzelm@39339
  2469
                      (idx, Array.fromList (map (pair false) intrs)))
wenzelm@39339
  2470
                      rec_operators
wenzelm@39339
  2471
                    (* takes an interpretation, and if some leaf of this     *)
wenzelm@39339
  2472
                    (* interpretation is the 'elem'-th element of the type,  *)
wenzelm@39339
  2473
                    (* the indices of the arguments leading to this leaf are *)
wenzelm@39339
  2474
                    (* returned                                              *)
wenzelm@39339
  2475
                    (* interpretation -> int -> int list option *)
wenzelm@39339
  2476
                    fun get_args (Leaf xs) elem =
wenzelm@39339
  2477
                          if find_index (fn x => x = True) xs = elem then
wenzelm@39339
  2478
                            SOME []
webertj@25014
  2479
                          else
wenzelm@39339
  2480
                            NONE
wenzelm@39339
  2481
                      | get_args (Node xs) elem =
wenzelm@39339
  2482
                          let
wenzelm@39339
  2483
                            (* interpretation list * int -> int list option *)
wenzelm@39339
  2484
                            fun search ([], _) =
wenzelm@39339
  2485
                              NONE
wenzelm@39339
  2486
                              | search (x::xs, n) =
wenzelm@39339
  2487
                              (case get_args x elem of
wenzelm@39339
  2488
                                SOME result => SOME (n::result)
wenzelm@39339
  2489
                              | NONE        => search (xs, n+1))
wenzelm@39339
  2490
                          in
wenzelm@39339
  2491
                            search (xs, 0)
wenzelm@39339
  2492
                          end
wenzelm@39339
  2493
                    (* returns the index of the constructor and indices for *)
wenzelm@39339
  2494
                    (* its arguments that generate the 'elem'-th element of *)
wenzelm@39339
  2495
                    (* the datatype given by 'idx'                          *)
wenzelm@39339
  2496
                    (* int -> int -> int * int list *)
wenzelm@39339
  2497
                    fun get_cargs idx elem =
webertj@25014
  2498
                      let
wenzelm@39339
  2499
                        (* int * interpretation list -> int * int list *)
wenzelm@39339
  2500
                        fun get_cargs_rec (_, []) =
wenzelm@39339
  2501
                              raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2502
                                "no matching constructor found for datatype element")
wenzelm@39339
  2503
                          | get_cargs_rec (n, x::xs) =
wenzelm@39339
  2504
                              (case get_args x elem of
wenzelm@39339
  2505
                                SOME args => (n, args)
wenzelm@39339
  2506
                              | NONE => get_cargs_rec (n+1, xs))
webertj@25014
  2507
                      in
wenzelm@39339
  2508
                        get_cargs_rec (0, the (AList.lookup (op =) mc_intrs idx))
wenzelm@39339
  2509
                      end
wenzelm@39339
  2510
                    (* computes one entry in 'REC_OPERATORS', and recursively *)
wenzelm@39339
  2511
                    (* all entries needed for it, where 'idx' gives the       *)
wenzelm@39339
  2512
                    (* datatype and 'elem' the element of it                  *)
wenzelm@39339
  2513
                    (* int -> int -> interpretation *)
wenzelm@39339
  2514
                    fun compute_array_entry idx elem =
wenzelm@39339
  2515
                      let
wenzelm@39339
  2516
                        val arr = the (AList.lookup (op =) REC_OPERATORS idx)
wenzelm@39339
  2517
                        val (flag, intr) = Array.sub (arr, elem)
wenzelm@39339
  2518
                      in
wenzelm@39339
  2519
                        if flag then
wenzelm@39339
  2520
                          (* simply return the previously computed result *)
wenzelm@39339
  2521
                          intr
wenzelm@39339
  2522
                        else
wenzelm@39339
  2523
                          (* we have to apply 'intr' to interpretations for all *)
wenzelm@39339
  2524
                          (* recursive arguments                                *)
wenzelm@39339
  2525
                          let
wenzelm@39339
  2526
                            (* int * int list *)
wenzelm@39339
  2527
                            val (c, args) = get_cargs idx elem
wenzelm@39339
  2528
                            (* find the indices of the constructor's /recursive/ *)
wenzelm@39339
  2529
                            (* arguments                                         *)
wenzelm@39339
  2530
                            val (_, _, constrs) = the (AList.lookup (op =) descr idx)
wenzelm@39339
  2531
                            val (_, dtyps)      = List.nth (constrs, c)
wenzelm@39339
  2532
                            val rec_dtyps_args  = filter
wenzelm@39339
  2533
                              (Datatype_Aux.is_rec_type o fst) (dtyps ~~ args)
wenzelm@39339
  2534
                            (* map those indices to interpretations *)
wenzelm@39339
  2535
                            val rec_dtyps_intrs = map (fn (dtyp, arg) =>
wenzelm@39339
  2536
                              let
wenzelm@39339
  2537
                                val dT     = typ_of_dtyp descr typ_assoc dtyp
wenzelm@39339
  2538
                                val consts = make_constants thy (typs, []) dT
wenzelm@39339
  2539
                                val arg_i  = List.nth (consts, arg)
wenzelm@39339
  2540
                              in
wenzelm@39339
  2541
                                (dtyp, arg_i)
wenzelm@39339
  2542
                              end) rec_dtyps_args
wenzelm@39339
  2543
                            (* takes the dtyp and interpretation of an element, *)
wenzelm@39339
  2544
                            (* and computes the interpretation for the          *)
wenzelm@39339
  2545
                            (* corresponding recursive argument                 *)
wenzelm@39339
  2546
                            fun rec_intr (Datatype_Aux.DtRec i) (Leaf xs) =
wenzelm@39339
  2547
                                  (* recursive argument is "rec_i params elem" *)
wenzelm@39339
  2548
                                  compute_array_entry i (find_index (fn x => x = True) xs)
wenzelm@39339
  2549
                              | rec_intr (Datatype_Aux.DtRec _) (Node _) =
wenzelm@39339
  2550
                                  raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2551
                                    "interpretation for IDT is a node")
wenzelm@39339
  2552
                              | rec_intr (Datatype_Aux.DtType ("fun", [dt1, dt2])) (Node xs) =
wenzelm@39339
  2553
                                  (* recursive argument is something like     *)
wenzelm@39339
  2554
                                  (* "\<lambda>x::dt1. rec_? params (elem x)" *)
wenzelm@39339
  2555
                                  Node (map (rec_intr dt2) xs)
wenzelm@39339
  2556
                              | rec_intr (Datatype_Aux.DtType ("fun", [_, _])) (Leaf _) =
wenzelm@39339
  2557
                                  raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2558
                                    "interpretation for function dtyp is a leaf")
wenzelm@39339
  2559
                              | rec_intr _ _ =
wenzelm@39339
  2560
                                  (* admissibility ensures that every recursive type *)
wenzelm@39339
  2561
                                  (* is of the form 'Dt_1 -> ... -> Dt_k ->          *)
wenzelm@39339
  2562
                                  (* (DtRec i)'                                      *)
wenzelm@39339
  2563
                                  raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2564
                                    "non-recursive codomain in recursive dtyp")
wenzelm@39339
  2565
                            (* obtain interpretations for recursive arguments *)
wenzelm@39339
  2566
                            (* interpretation list *)
wenzelm@39339
  2567
                            val arg_intrs = map (uncurry rec_intr) rec_dtyps_intrs
wenzelm@39339
  2568
                            (* apply 'intr' to all recursive arguments *)
wenzelm@39339
  2569
                            val result = fold (fn arg_i => fn i =>
wenzelm@39339
  2570
                              interpretation_apply (i, arg_i)) arg_intrs intr
wenzelm@39339
  2571
                            (* update 'REC_OPERATORS' *)
wenzelm@39339
  2572
                            val _ = Array.update (arr, elem, (true, result))
wenzelm@39339
  2573
                          in
wenzelm@39339
  2574
                            result
wenzelm@39339
  2575
                          end
wenzelm@39339
  2576
                      end
wenzelm@39339
  2577
                    val idt_size = Array.length (the (AList.lookup (op =) REC_OPERATORS idt_index))
wenzelm@39339
  2578
                    (* sanity check: the size of 'IDT' should be 'idt_size' *)
wenzelm@39339
  2579
                    val _ =
wenzelm@39339
  2580
                        if idt_size <> size_of_type thy (typs, []) IDT then
wenzelm@39339
  2581
                          raise REFUTE ("IDT_recursion_interpreter",
wenzelm@39339
  2582
                            "unexpected size of IDT (wrong type associated?)")
wenzelm@39339
  2583
                        else ()
wenzelm@39339
  2584
                    (* interpretation *)
wenzelm@39339
  2585
                    val rec_op = Node (map_range (compute_array_entry idt_index) idt_size)
webertj@25014
  2586
                  in
wenzelm@39339
  2587
                    SOME (rec_op, model', args')
webertj@25014
  2588
                  end
wenzelm@39339
  2589
              end
wenzelm@39339
  2590
            else
wenzelm@39339
  2591
              NONE  (* not a recursion operator of this datatype *)
haftmann@31784
  2592
        ) (Datatype.get_all thy) NONE
wenzelm@39339
  2593
  | _ =>  (* head of term is not a constant *)
wenzelm@39339
  2594
    NONE;
webertj@15547
  2595
wenzelm@39339
  2596
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2597
  (interpretation * model * arguments) option *)
webertj@15547
  2598
wenzelm@39339
  2599
fun set_interpreter thy model args t =
blanchet@29893
  2600
  let
blanchet@29893
  2601
    val (typs, terms) = model
blanchet@29893
  2602
  in
blanchet@29893
  2603
    case AList.lookup (op =) terms t of
blanchet@29893
  2604
      SOME intr =>
wenzelm@39339
  2605
        (* return an existing interpretation *)
wenzelm@39339
  2606
        SOME (intr, model, args)
blanchet@29893
  2607
    | NONE =>
wenzelm@39339
  2608
        (case t of
wenzelm@39339
  2609
        (* 'Collect' == identity *)
wenzelm@39339
  2610
          Const (@{const_name Collect}, _) $ t1 =>
wenzelm@39339
  2611
            SOME (interpret thy model args t1)
wenzelm@39339
  2612
        | Const (@{const_name Collect}, _) =>
wenzelm@39339
  2613
            SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  2614
        (* 'op :' == application *)
wenzelm@39339
  2615
        | Const (@{const_name Set.member}, _) $ t1 $ t2 =>
wenzelm@39339
  2616
            SOME (interpret thy model args (t2 $ t1))
wenzelm@39339
  2617
        | Const (@{const_name Set.member}, _) $ t1 =>
wenzelm@39339
  2618
            SOME (interpret thy model args (eta_expand t 1))
wenzelm@39339
  2619
        | Const (@{const_name Set.member}, _) =>
wenzelm@39339
  2620
            SOME (interpret thy model args (eta_expand t 2))
wenzelm@39339
  2621
        | _ => NONE)
blanchet@29893
  2622
  end;
blanchet@29893
  2623
wenzelm@39339
  2624
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2625
  (interpretation * model * arguments) option *)
blanchet@29893
  2626
wenzelm@39339
  2627
(* only an optimization: 'card' could in principle be interpreted with *)
wenzelm@39339
  2628
(* interpreters available already (using its definition), but the code *)
wenzelm@39339
  2629
(* below is more efficient                                             *)
webertj@14807
  2630
wenzelm@39339
  2631
fun Finite_Set_card_interpreter thy model args t =
wenzelm@39339
  2632
  case t of
wenzelm@39339
  2633
    Const (@{const_name Finite_Set.card},
wenzelm@39339
  2634
        Type ("fun", [Type ("fun", [T, @{typ bool}]), @{typ nat}])) =>
wenzelm@22567
  2635
      let
wenzelm@22567
  2636
        (* interpretation -> int *)
wenzelm@22567
  2637
        fun number_of_elements (Node xs) =
wenzelm@33262
  2638
            fold (fn x => fn n =>
wenzelm@33262
  2639
              if x = TT then
wenzelm@33262
  2640
                n + 1
wenzelm@33262
  2641
              else if x = FF then
wenzelm@33262
  2642
                n
wenzelm@33262
  2643
              else
wenzelm@33262
  2644
                raise REFUTE ("Finite_Set_card_interpreter",
wenzelm@33262
  2645
                  "interpretation for set type does not yield a Boolean"))
wenzelm@33262
  2646
              xs 0
wenzelm@22567
  2647
          | number_of_elements (Leaf _) =
wenzelm@39339
  2648
              raise REFUTE ("Finite_Set_card_interpreter",
wenzelm@39339
  2649
                "interpretation for set type is a leaf")
haftmann@37363
  2650
        val size_of_nat = size_of_type thy model (@{typ nat})
wenzelm@22567
  2651
        (* takes an interpretation for a set and returns an interpretation *)
webertj@25014
  2652
        (* for a 'nat' denoting the set's cardinality                      *)
wenzelm@22567
  2653
        (* interpretation -> interpretation *)
wenzelm@22567
  2654
        fun card i =
wenzelm@22567
  2655
          let
wenzelm@22567
  2656
            val n = number_of_elements i
wenzelm@22567
  2657
          in
wenzelm@39339
  2658
            if n < size_of_nat then
wenzelm@22567
  2659
              Leaf ((replicate n False) @ True ::
webertj@25014
  2660
                (replicate (size_of_nat-n-1) False))
wenzelm@22567
  2661
            else
webertj@25014
  2662
              Leaf (replicate size_of_nat False)
wenzelm@22567
  2663
          end
blanchet@30312
  2664
        val set_constants =
haftmann@38778
  2665
          make_constants thy model (Type ("fun", [T, HOLogic.boolT]))
wenzelm@22567
  2666
      in
webertj@25014
  2667
        SOME (Node (map card set_constants), model, args)
wenzelm@22567
  2668
      end
wenzelm@39339
  2669
  | _ => NONE;
webertj@14807
  2670
wenzelm@39339
  2671
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2672
  (interpretation * model * arguments) option *)
webertj@15547
  2673
wenzelm@39339
  2674
(* only an optimization: 'finite' could in principle be interpreted with  *)
wenzelm@39339
  2675
(* interpreters available already (using its definition), but the code    *)
wenzelm@39339
  2676
(* below is more efficient                                                *)
webertj@22093
  2677
wenzelm@39339
  2678
fun Finite_Set_finite_interpreter thy model args t =
wenzelm@39339
  2679
  case t of
wenzelm@39339
  2680
    Const (@{const_name Finite_Set.finite},
wenzelm@39339
  2681
      Type ("fun", [Type ("fun", [T, @{typ bool}]),
wenzelm@39339
  2682
                    @{typ bool}])) $ _ =>
wenzelm@22567
  2683
        (* we only consider finite models anyway, hence EVERY set is *)
wenzelm@22567
  2684
        (* "finite"                                                  *)
wenzelm@22567
  2685
        SOME (TT, model, args)
wenzelm@39339
  2686
  | Const (@{const_name Finite_Set.finite},
wenzelm@39339
  2687
      Type ("fun", [Type ("fun", [T, @{typ bool}]),
wenzelm@39339
  2688
                    @{typ bool}])) =>
wenzelm@22567
  2689
      let
blanchet@30312
  2690
        val size_of_set =
haftmann@38778
  2691
          size_of_type thy model (Type ("fun", [T, HOLogic.boolT]))
wenzelm@22567
  2692
      in
wenzelm@22567
  2693
        (* we only consider finite models anyway, hence EVERY set is *)
wenzelm@22567
  2694
        (* "finite"                                                  *)
webertj@25014
  2695
        SOME (Node (replicate size_of_set TT), model, args)
wenzelm@22567
  2696
      end
wenzelm@39339
  2697
  | _ => NONE;
webertj@22093
  2698
wenzelm@39339
  2699
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2700
  (interpretation * model * arguments) option *)
webertj@22093
  2701
wenzelm@39339
  2702
(* only an optimization: 'less' could in principle be interpreted with *)
wenzelm@39339
  2703
(* interpreters available already (using its definition), but the code     *)
wenzelm@39339
  2704
(* below is more efficient                                                 *)
webertj@15547
  2705
wenzelm@39339
  2706
fun Nat_less_interpreter thy model args t =
wenzelm@39339
  2707
  case t of
wenzelm@39339
  2708
    Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
haftmann@38778
  2709
        Type ("fun", [@{typ nat}, @{typ bool}])])) =>
wenzelm@22567
  2710
      let
haftmann@37363
  2711
        val size_of_nat = size_of_type thy model (@{typ nat})
webertj@25014
  2712
        (* the 'n'-th nat is not less than the first 'n' nats, while it *)
webertj@25014
  2713
        (* is less than the remaining 'size_of_nat - n' nats            *)
wenzelm@22567
  2714
        (* int -> interpretation *)
webertj@25014
  2715
        fun less n = Node ((replicate n FF) @ (replicate (size_of_nat - n) TT))
wenzelm@22567
  2716
      in
webertj@25014
  2717
        SOME (Node (map less (1 upto size_of_nat)), model, args)
wenzelm@22567
  2718
      end
wenzelm@39339
  2719
  | _ => NONE;
webertj@15547
  2720
wenzelm@39339
  2721
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2722
  (interpretation * model * arguments) option *)
webertj@15547
  2723
wenzelm@39339
  2724
(* only an optimization: 'plus' could in principle be interpreted with *)
wenzelm@39339
  2725
(* interpreters available already (using its definition), but the code     *)
wenzelm@39339
  2726
(* below is more efficient                                                 *)
webertj@15547
  2727
wenzelm@39339
  2728
fun Nat_plus_interpreter thy model args t =
wenzelm@39339
  2729
  case t of
wenzelm@39339
  2730
    Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
haftmann@37363
  2731
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@22567
  2732
      let
haftmann@37363
  2733
        val size_of_nat = size_of_type thy model (@{typ nat})
wenzelm@22567
  2734
        (* int -> int -> interpretation *)
wenzelm@22567
  2735
        fun plus m n =
wenzelm@22567
  2736
          let
webertj@25032
  2737
            val element = m + n
wenzelm@22567
  2738
          in
webertj@25032
  2739
            if element > size_of_nat - 1 then
webertj@25014
  2740
              Leaf (replicate size_of_nat False)
wenzelm@22567
  2741
            else
webertj@25032
  2742
              Leaf ((replicate element False) @ True ::
webertj@25032
  2743
                (replicate (size_of_nat - element - 1) False))
wenzelm@22567
  2744
          end
wenzelm@22567
  2745
      in
haftmann@33061
  2746
        SOME (Node (map_range (fn m => Node (map_range (plus m) size_of_nat)) size_of_nat),
haftmann@33061
  2747
          model, args)
wenzelm@22567
  2748
      end
wenzelm@39339
  2749
  | _ => NONE;
webertj@15547
  2750
wenzelm@39339
  2751
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2752
  (interpretation * model * arguments) option *)
webertj@15547
  2753
wenzelm@39339
  2754
(* only an optimization: 'minus' could in principle be interpreted *)
wenzelm@39339
  2755
(* with interpreters available already (using its definition), but the *)
wenzelm@39339
  2756
(* code below is more efficient                                        *)
webertj@15547
  2757
wenzelm@39339
  2758
fun Nat_minus_interpreter thy model args t =
wenzelm@39339
  2759
  case t of
wenzelm@39339
  2760
    Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
haftmann@37363
  2761
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@22567
  2762
      let
haftmann@37363
  2763
        val size_of_nat = size_of_type thy model (@{typ nat})
wenzelm@22567
  2764
        (* int -> int -> interpretation *)
wenzelm@22567
  2765
        fun minus m n =
wenzelm@22567
  2766
          let
webertj@25032
  2767
            val element = Int.max (m-n, 0)
wenzelm@22567
  2768
          in
webertj@25032
  2769
            Leaf ((replicate element False) @ True ::
webertj@25032
  2770
              (replicate (size_of_nat - element - 1) False))
wenzelm@22567
  2771
          end
wenzelm@22567
  2772
      in
haftmann@33061
  2773
        SOME (Node (map_range (fn m => Node (map_range (minus m) size_of_nat)) size_of_nat),
haftmann@33061
  2774
          model, args)
wenzelm@22567
  2775
      end
wenzelm@39339
  2776
  | _ => NONE;
webertj@15547
  2777
wenzelm@39339
  2778
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2779
  (interpretation * model * arguments) option *)
webertj@15547
  2780
wenzelm@39339
  2781
(* only an optimization: 'times' could in principle be interpreted *)
wenzelm@39339
  2782
(* with interpreters available already (using its definition), but the *)
wenzelm@39339
  2783
(* code below is more efficient                                        *)
webertj@15547
  2784
wenzelm@39339
  2785
fun Nat_times_interpreter thy model args t =
wenzelm@39339
  2786
  case t of
wenzelm@39339
  2787
    Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
haftmann@37363
  2788
        Type ("fun", [@{typ nat}, @{typ nat}])])) =>
wenzelm@22567
  2789
      let
haftmann@37363
  2790
        val size_of_nat = size_of_type thy model (@{typ nat})
wenzelm@22567
  2791
        (* nat -> nat -> interpretation *)
wenzelm@22567
  2792
        fun mult m n =
wenzelm@22567
  2793
          let
webertj@25032
  2794
            val element = m * n
wenzelm@22567
  2795
          in
webertj@25032
  2796
            if element > size_of_nat - 1 then
webertj@25014
  2797
              Leaf (replicate size_of_nat False)
wenzelm@22567
  2798
            else
webertj@25032
  2799
              Leaf ((replicate element False) @ True ::
webertj@25032
  2800
                (replicate (size_of_nat - element - 1) False))
wenzelm@22567
  2801
          end
wenzelm@22567
  2802
      in
haftmann@33061
  2803
        SOME (Node (map_range (fn m => Node (map_range (mult m) size_of_nat)) size_of_nat),
haftmann@33061
  2804
          model, args)
wenzelm@22567
  2805
      end
wenzelm@39339
  2806
  | _ => NONE;
webertj@15547
  2807
wenzelm@39339
  2808
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2809
  (interpretation * model * arguments) option *)
webertj@15767
  2810
wenzelm@39339
  2811
(* only an optimization: 'append' could in principle be interpreted with *)
wenzelm@39339
  2812
(* interpreters available already (using its definition), but the code   *)
wenzelm@39339
  2813
(* below is more efficient                                               *)
webertj@15767
  2814
wenzelm@39339
  2815
fun List_append_interpreter thy model args t =
wenzelm@39339
  2816
  case t of
wenzelm@39339
  2817
    Const (@{const_name List.append}, Type ("fun", [Type ("List.list", [T]), Type ("fun",
wenzelm@22567
  2818
        [Type ("List.list", [_]), Type ("List.list", [_])])])) =>
wenzelm@22567
  2819
      let
wenzelm@39339
  2820
        val size_elem = size_of_type thy model T
wenzelm@39339
  2821
        val size_list = size_of_type thy model (Type ("List.list", [T]))
webertj@25032
  2822
        (* maximal length of lists; 0 if we only consider the empty list *)
wenzelm@39339
  2823
        val list_length =
wenzelm@39339
  2824
          let
webertj@25032
  2825
            (* int -> int -> int -> int *)
webertj@25032
  2826
            fun list_length_acc len lists total =
webertj@25032
  2827
              if lists = total then
webertj@25032
  2828
                len
webertj@25032
  2829
              else if lists < total then
webertj@25032
  2830
                list_length_acc (len+1) (lists*size_elem) (total-lists)
webertj@25032
  2831
              else
webertj@25032
  2832
                raise REFUTE ("List_append_interpreter",
webertj@25032
  2833
                  "size_list not equal to 1 + size_elem + ... + " ^
webertj@25032
  2834
                    "size_elem^len, for some len")
webertj@25032
  2835
          in
webertj@25032
  2836
            list_length_acc 0 1 size_list
webertj@25032
  2837
          end
webertj@25032
  2838
        val elements = 0 upto (size_list-1)
webertj@25032
  2839
        (* FIXME: there should be a nice formula, which computes the same as *)
webertj@25032
  2840
        (*        the following, but without all this intermediate tree      *)
webertj@25032
  2841
        (*        length/offset stuff                                        *)
webertj@25032
  2842
        (* associate each list with its length and offset in a complete tree *)
webertj@25032
  2843
        (* of width 'size_elem' and depth 'length_list' (with 'size_list'    *)
webertj@25032
  2844
        (* nodes total)                                                      *)
webertj@25032
  2845
        (* (int * (int * int)) list *)
wenzelm@33262
  2846
        val (lenoff_lists, _) = fold_map (fn elem => fn (offsets, off) =>
webertj@25032
  2847
          (* corresponds to a pre-order traversal of the tree *)
wenzelm@22567
  2848
          let
webertj@25032
  2849
            val len = length offsets
webertj@25032
  2850
            (* associate the given element with len/off *)
webertj@25032
  2851
            val assoc = (elem, (len, off))
wenzelm@22567
  2852
          in
webertj@25032
  2853
            if len < list_length then
webertj@25032
  2854
              (* go to first child node *)
wenzelm@33262
  2855
              (assoc, (off :: offsets, off * size_elem))
webertj@25032
  2856
            else if off mod size_elem < size_elem - 1 then
webertj@25032
  2857
              (* go to next sibling node *)
wenzelm@33262
  2858
              (assoc, (offsets, off + 1))
webertj@25032
  2859
            else
webertj@25032
  2860
              (* go back up the stack until we find a level where we can go *)
webertj@25032
  2861
              (* to the next sibling node                                   *)
webertj@25032
  2862
              let
haftmann@33954
  2863
                val offsets' = dropwhile
webertj@25032
  2864
                  (fn off' => off' mod size_elem = size_elem - 1) offsets
webertj@25032
  2865
              in
webertj@25032
  2866
                case offsets' of
webertj@25032
  2867
                  [] =>
wenzelm@39339
  2868
                    (* we're at the last node in the tree; the next value *)
wenzelm@39339
  2869
                    (* won't be used anyway                               *)
wenzelm@39339
  2870
                    (assoc, ([], 0))
webertj@25032
  2871
                | off'::offs' =>
wenzelm@39339
  2872
                    (* go to next sibling node *)
wenzelm@39339
  2873
                    (assoc, (offs', off' + 1))
webertj@25032
  2874
              end
wenzelm@33262
  2875
          end) elements ([], 0)
webertj@25032
  2876
        (* we also need the reverse association (from length/offset to *)
webertj@25032
  2877
        (* index)                                                      *)
webertj@25032
  2878
        val lenoff'_lists = map Library.swap lenoff_lists
webertj@25032
  2879
        (* returns the interpretation for "(list no. m) @ (list no. n)" *)
wenzelm@22567
  2880
        (* nat -> nat -> interpretation *)
wenzelm@22567
  2881
        fun append m n =
wenzelm@22567
  2882
          let
wenzelm@29288
  2883
            val (len_m, off_m) = the (AList.lookup (op =) lenoff_lists m)
wenzelm@29288
  2884
            val (len_n, off_n) = the (AList.lookup (op =) lenoff_lists n)
webertj@25032
  2885
            val len_elem = len_m + len_n
wenzelm@39340
  2886
            val off_elem = off_m * Integer.pow len_n size_elem + off_n
wenzelm@22567
  2887
          in
wenzelm@39339
  2888
            case AList.lookup op= lenoff'_lists (len_elem, off_elem) of
webertj@25032
  2889
              NONE =>
wenzelm@39339
  2890
                (* undefined *)
wenzelm@39339
  2891
                Leaf (replicate size_list False)
webertj@25032
  2892
            | SOME element =>
wenzelm@39339
  2893
                Leaf ((replicate element False) @ True ::
wenzelm@39339
  2894
                  (replicate (size_list - element - 1) False))
wenzelm@22567
  2895
          end
wenzelm@22567
  2896
      in
webertj@25032
  2897
        SOME (Node (map (fn m => Node (map (append m) elements)) elements),
webertj@25032
  2898
          model, args)
wenzelm@22567
  2899
      end
wenzelm@39339
  2900
  | _ => NONE;
webertj@15767
  2901
blanchet@36130
  2902
(* UNSOUND
blanchet@36130
  2903
wenzelm@39339
  2904
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2905
  (interpretation * model * arguments) option *)
webertj@16050
  2906
wenzelm@39339
  2907
(* only an optimization: 'lfp' could in principle be interpreted with  *)
wenzelm@39339
  2908
(* interpreters available already (using its definition), but the code *)
wenzelm@39339
  2909
(* below is more efficient                                             *)
webertj@16050
  2910
wenzelm@39339
  2911
fun lfp_interpreter thy model args t =
wenzelm@39339
  2912
  case t of
wenzelm@39339
  2913
    Const (@{const_name lfp}, Type ("fun", [Type ("fun",
wenzelm@39339
  2914
      [Type ("fun", [T, @{typ bool}]),
wenzelm@39339
  2915
       Type ("fun", [_, @{typ bool}])]),
wenzelm@39339
  2916
       Type ("fun", [_, @{typ bool}])])) =>
wenzelm@22567
  2917
      let
webertj@25014
  2918
        val size_elem = size_of_type thy model T
wenzelm@22567
  2919
        (* the universe (i.e. the set that contains every element) *)
webertj@25014
  2920
        val i_univ = Node (replicate size_elem TT)
wenzelm@22567
  2921
        (* all sets with elements from type 'T' *)
blanchet@30312
  2922
        val i_sets =
haftmann@38778
  2923
          make_constants thy model (Type ("fun", [T, HOLogic.boolT]))
wenzelm@22567
  2924
        (* all functions that map sets to sets *)
webertj@25014
  2925
        val i_funs = make_constants thy model (Type ("fun",
haftmann@38778
  2926
          [Type ("fun", [T, @{typ bool}]),
haftmann@38778
  2927
           Type ("fun", [T, @{typ bool}])]))
wenzelm@22567
  2928
        (* "lfp(f) == Inter({u. f(u) <= u})" *)
wenzelm@22567
  2929
        (* interpretation * interpretation -> bool *)
wenzelm@22567
  2930
        fun is_subset (Node subs, Node sups) =
wenzelm@39339
  2931
              forall (fn (sub, sup) => (sub = FF) orelse (sup = TT)) (subs ~~ sups)
wenzelm@22567
  2932
          | is_subset (_, _) =
wenzelm@39339
  2933
              raise REFUTE ("lfp_interpreter",
wenzelm@39339
  2934
                "is_subset: interpretation for set is not a node")
wenzelm@22567
  2935
        (* interpretation * interpretation -> interpretation *)
wenzelm@22567
  2936
        fun intersection (Node xs, Node ys) =
wenzelm@39339
  2937
              Node (map (fn (x, y) => if x=TT andalso y=TT then TT else FF)
wenzelm@39339
  2938
                (xs ~~ ys))
wenzelm@22567
  2939
          | intersection (_, _) =
wenzelm@39339
  2940
              raise REFUTE ("lfp_interpreter",
wenzelm@39339
  2941
                "intersection: interpretation for set is not a node")
wenzelm@22567
  2942
        (* interpretation -> interpretaion *)
wenzelm@22567
  2943
        fun lfp (Node resultsets) =
wenzelm@39339
  2944
              fold (fn (set, resultset) => fn acc =>
wenzelm@39339
  2945
                if is_subset (resultset, set) then
wenzelm@39339
  2946
                  intersection (acc, set)
wenzelm@39339
  2947
                else
wenzelm@39339
  2948
                  acc) (i_sets ~~ resultsets) i_univ
wenzelm@22567
  2949
          | lfp _ =
wenzelm@39339
  2950
              raise REFUTE ("lfp_interpreter",
wenzelm@39339
  2951
                "lfp: interpretation for function is not a node")
wenzelm@22567
  2952
      in
wenzelm@22567
  2953
        SOME (Node (map lfp i_funs), model, args)
wenzelm@22567
  2954
      end
wenzelm@39339
  2955
  | _ => NONE;
webertj@16050
  2956
wenzelm@39339
  2957
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  2958
  (interpretation * model * arguments) option *)
webertj@16050
  2959
wenzelm@39339
  2960
(* only an optimization: 'gfp' could in principle be interpreted with  *)
wenzelm@39339
  2961
(* interpreters available already (using its definition), but the code *)
wenzelm@39339
  2962
(* below is more efficient                                             *)
webertj@16050
  2963
wenzelm@39339
  2964
fun gfp_interpreter thy model args t =
wenzelm@39339
  2965
  case t of
wenzelm@39339
  2966
    Const (@{const_name gfp}, Type ("fun", [Type ("fun",
wenzelm@39339
  2967
      [Type ("fun", [T, @{typ bool}]),
wenzelm@39339
  2968
       Type ("fun", [_, @{typ bool}])]),
wenzelm@39339
  2969
       Type ("fun", [_, @{typ bool}])])) =>
wenzelm@39339
  2970
    let
wenzelm@39339
  2971
      val size_elem = size_of_type thy model T
wenzelm@39339
  2972
      (* the universe (i.e. the set that contains every element) *)
wenzelm@39339
  2973
      val i_univ = Node (replicate size_elem TT)
wenzelm@39339
  2974
      (* all sets with elements from type 'T' *)
wenzelm@39339
  2975
      val i_sets =
wenzelm@39339
  2976
        make_constants thy model (Type ("fun", [T, HOLogic.boolT]))
wenzelm@39339
  2977
      (* all functions that map sets to sets *)
wenzelm@39339
  2978
      val i_funs = make_constants thy model (Type ("fun",
wenzelm@39339
  2979
        [Type ("fun", [T, HOLogic.boolT]),
wenzelm@39339
  2980
         Type ("fun", [T, HOLogic.boolT])]))
wenzelm@39339
  2981
      (* "gfp(f) == Union({u. u <= f(u)})" *)
wenzelm@39339
  2982
      (* interpretation * interpretation -> bool *)
wenzelm@39339
  2983
      fun is_subset (Node subs, Node sups) =
wenzelm@39339
  2984
            forall (fn (sub, sup) => (sub = FF) orelse (sup = TT))
wenzelm@39339
  2985
              (subs ~~ sups)
wenzelm@39339
  2986
        | is_subset (_, _) =
wenzelm@39339
  2987
            raise REFUTE ("gfp_interpreter",
wenzelm@39339
  2988
              "is_subset: interpretation for set is not a node")
wenzelm@39339
  2989
      (* interpretation * interpretation -> interpretation *)
wenzelm@39339
  2990
      fun union (Node xs, Node ys) =
wenzelm@22567
  2991
            Node (map (fn (x,y) => if x=TT orelse y=TT then TT else FF)
wenzelm@22567
  2992
                 (xs ~~ ys))
wenzelm@39339
  2993
        | union (_, _) =
wenzelm@39339
  2994
            raise REFUTE ("gfp_interpreter",
wenzelm@39339
  2995
              "union: interpretation for set is not a node")
wenzelm@39339
  2996
      (* interpretation -> interpretaion *)
wenzelm@39339
  2997
      fun gfp (Node resultsets) =
wenzelm@39339
  2998
            fold (fn (set, resultset) => fn acc =>
wenzelm@39339
  2999
              if is_subset (set, resultset) then
wenzelm@39339
  3000
                union (acc, set)
wenzelm@39339
  3001
              else
wenzelm@39339
  3002
                acc) (i_sets ~~ resultsets) i_univ
wenzelm@39339
  3003
        | gfp _ =
blanchet@29739
  3004
            raise REFUTE ("gfp_interpreter",
wenzelm@22567
  3005
              "gfp: interpretation for function is not a node")
wenzelm@39339
  3006
    in
wenzelm@39339
  3007
      SOME (Node (map gfp i_funs), model, args)
wenzelm@39339
  3008
    end
wenzelm@39339
  3009
  | _ => NONE;
blanchet@36130
  3010
*)
webertj@16050
  3011
wenzelm@39339
  3012
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  3013
  (interpretation * model * arguments) option *)
webertj@21267
  3014
wenzelm@39339
  3015
(* only an optimization: 'fst' could in principle be interpreted with  *)
wenzelm@39339
  3016
(* interpreters available already (using its definition), but the code *)
wenzelm@39339
  3017
(* below is more efficient                                             *)
webertj@21267
  3018
wenzelm@39339
  3019
fun Product_Type_fst_interpreter thy model args t =
wenzelm@39339
  3020
  case t of
wenzelm@39339
  3021
    Const (@{const_name fst}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
wenzelm@22567
  3022
      let
webertj@25014
  3023
        val constants_T = make_constants thy model T
wenzelm@39339
  3024
        val size_U = size_of_type thy model U
wenzelm@22567
  3025
      in
wenzelm@32952
  3026
        SOME (Node (maps (replicate size_U) constants_T), model, args)
wenzelm@22567
  3027
      end
wenzelm@39339
  3028
  | _ => NONE;
webertj@21267
  3029
wenzelm@39339
  3030
(* theory -> model -> arguments -> Term.term ->
wenzelm@39339
  3031
  (interpretation * model * arguments) option *)
webertj@21267
  3032
wenzelm@39339
  3033
(* only an optimization: 'snd' could in principle be interpreted with  *)
wenzelm@39339
  3034
(* interpreters available already (using its definition), but the code *)
wenzelm@39339
  3035
(* below is more efficient                                             *)
webertj@21267
  3036
wenzelm@39339
  3037
fun Product_Type_snd_interpreter thy model args t =
wenzelm@39339
  3038
  case t of
wenzelm@39339
  3039
    Const (@{const_name snd}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
wenzelm@22567
  3040
      let
wenzelm@39339
  3041
        val size_T = size_of_type thy model T
webertj@25014
  3042
        val constants_U = make_constants thy model U
wenzelm@22567
  3043
      in
wenzelm@32952
  3044
        SOME (Node (flat (replicate size_T constants_U)), model, args)
wenzelm@22567
  3045
      end
wenzelm@39339
  3046
  | _ => NONE;
webertj@21267
  3047
webertj@14807
  3048
webertj@14807
  3049
(* ------------------------------------------------------------------------- *)
webertj@14807
  3050
(* PRINTERS                                                                  *)
webertj@14807
  3051
(* ------------------------------------------------------------------------- *)
webertj@14807
  3052
wenzelm@39339
  3053
(* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
wenzelm@39339
  3054
  Term.term option *)
webertj@14807
  3055
wenzelm@39339
  3056
fun stlc_printer thy model T intr assignment =
wenzelm@22567
  3057
  let
wenzelm@22567
  3058
    (* string -> string *)
wenzelm@22567
  3059
    fun strip_leading_quote s =
wenzelm@22567
  3060
      (implode o (fn [] => [] | x::xs => if x="'" then xs else x::xs)
wenzelm@22567
  3061
        o explode) s
wenzelm@22567
  3062
    (* Term.typ -> string *)
wenzelm@39339
  3063
    fun string_of_typ (Type (s, _)) = s
wenzelm@39339
  3064
      | string_of_typ (TFree (x, _)) = strip_leading_quote x
wenzelm@22567
  3065
      | string_of_typ (TVar ((x,i), _)) =
wenzelm@39339
  3066
          strip_leading_quote x ^ string_of_int i
wenzelm@22567
  3067
    (* interpretation -> int *)
wenzelm@22567
  3068
    fun index_from_interpretation (Leaf xs) =
wenzelm@39339
  3069
          find_index (PropLogic.eval assignment) xs
wenzelm@22567
  3070
      | index_from_interpretation _ =
wenzelm@39339
  3071
          raise REFUTE ("stlc_printer",
wenzelm@39339
  3072
            "interpretation for ground type is not a leaf")
wenzelm@22567
  3073
  in
webertj@25014
  3074
    case T of
webertj@25014
  3075
      Type ("fun", [T1, T2]) =>
wenzelm@39339
  3076
        let
wenzelm@39339
  3077
          (* create all constants of type 'T1' *)
wenzelm@39339
  3078
          val constants = make_constants thy model T1
wenzelm@39339
  3079
          (* interpretation list *)
wenzelm@39339
  3080
          val results =
wenzelm@39339
  3081
            (case intr of
wenzelm@39339
  3082
              Node xs => xs
wenzelm@39339
  3083
            | _ => raise REFUTE ("stlc_printer",
wenzelm@39339
  3084
              "interpretation for function type is a leaf"))
wenzelm@39339
  3085
          (* Term.term list *)
wenzelm@39339
  3086
          val pairs = map (fn (arg, result) =>
wenzelm@39339
  3087
            HOLogic.mk_prod
wenzelm@39339
  3088
              (print thy model T1 arg assignment,
wenzelm@39339
  3089
               print thy model T2 result assignment))
wenzelm@39339
  3090
            (constants ~~ results)
wenzelm@39339
  3091
          (* Term.typ *)
wenzelm@39339
  3092
          val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
wenzelm@39339
  3093
          val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
wenzelm@39339
  3094
          (* Term.term *)
wenzelm@39339
  3095
          val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
wenzelm@39339
  3096
          val HOLogic_insert    =
wenzelm@39339
  3097
            Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
wenzelm@39339
  3098
        in
wenzelm@39339
  3099
          SOME (fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) pairs HOLogic_empty_set)
wenzelm@39339
  3100
        end
wenzelm@39339
  3101
    | Type ("prop", []) =>
wenzelm@39339
  3102
        (case index_from_interpretation intr of
wenzelm@39339
  3103
          ~1 => SOME (HOLogic.mk_Trueprop (Const (@{const_name undefined}, HOLogic.boolT)))
wenzelm@39339
  3104
        | 0  => SOME (HOLogic.mk_Trueprop HOLogic.true_const)
wenzelm@39339
  3105
        | 1  => SOME (HOLogic.mk_Trueprop HOLogic.false_const)
wenzelm@39339
  3106
        | _  => raise REFUTE ("stlc_interpreter",
wenzelm@39339
  3107
          "illegal interpretation for a propositional value"))
wenzelm@39339
  3108
    | Type _  =>
wenzelm@39339
  3109
        if index_from_interpretation intr = (~1) then
wenzelm@39339
  3110
          SOME (Const (@{const_name undefined}, T))
wenzelm@39339
  3111
        else
wenzelm@39339
  3112
          SOME (Const (string_of_typ T ^
wenzelm@39339
  3113
            string_of_int (index_from_interpretation intr), T))
wenzelm@39339
  3114
    | TFree _ =>
wenzelm@39339
  3115
        if index_from_interpretation intr = (~1) then
wenzelm@39339
  3116
          SOME (Const (@{const_name undefined}, T))
wenzelm@39339
  3117
        else
wenzelm@39339
  3118
          SOME (Const (string_of_typ T ^
wenzelm@39339
  3119
            string_of_int (index_from_interpretation intr), T))
wenzelm@39339
  3120
    | TVar _  =>
wenzelm@39339
  3121
        if index_from_interpretation intr = (~1) then
wenzelm@39339
  3122
          SOME (Const (@{const_name undefined}, T))
wenzelm@39339
  3123
        else
wenzelm@39339
  3124
          SOME (Const (string_of_typ T ^
wenzelm@39339
  3125
            string_of_int (index_from_interpretation intr), T))
wenzelm@22567
  3126
  end;
webertj@14350
  3127
wenzelm@39339
  3128
(* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
wenzelm@39339
  3129
  Term.term option *)
webertj@14350
  3130
wenzelm@39339
  3131
fun IDT_printer thy model T intr assignment =
wenzelm@39339
  3132
  (case T of
wenzelm@39339
  3133
    Type (s, Ts) =>
haftmann@31784
  3134
      (case Datatype.get_info thy s of
wenzelm@22567
  3135
        SOME info =>  (* inductive datatype *)
wenzelm@39339
  3136
          let
wenzelm@39339
  3137
            val (typs, _)           = model
wenzelm@39339
  3138
            val index               = #index info
wenzelm@39339
  3139
            val descr               = #descr info
wenzelm@39339
  3140
            val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@39339
  3141
            val typ_assoc           = dtyps ~~ Ts
wenzelm@39339
  3142
            (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
wenzelm@39339
  3143
            val _ =
wenzelm@39339
  3144
              if Library.exists (fn d =>
wenzelm@39339
  3145
                case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@39339
  3146
              then
wenzelm@39339
  3147
                raise REFUTE ("IDT_printer", "datatype argument (for type " ^
wenzelm@39339
  3148
                  Syntax.string_of_typ_global thy (Type (s, Ts)) ^ ") is not a variable")
wenzelm@39339
  3149
              else ()
wenzelm@39339
  3150
            (* the index of the element in the datatype *)
wenzelm@39339
  3151
            val element =
wenzelm@39339
  3152
              (case intr of
wenzelm@39339
  3153
                Leaf xs => find_index (PropLogic.eval assignment) xs
wenzelm@39339
  3154
              | Node _  => raise REFUTE ("IDT_printer",
wenzelm@39339
  3155
                "interpretation is not a leaf"))
wenzelm@39339
  3156
          in
wenzelm@39339
  3157
            if element < 0 then
wenzelm@39339
  3158
              SOME (Const (@{const_name undefined}, Type (s, Ts)))
wenzelm@39339
  3159
            else
wenzelm@22567
  3160
              let
wenzelm@39339
  3161
                (* takes a datatype constructor, and if for some arguments this  *)
wenzelm@39339
  3162
                (* constructor generates the datatype's element that is given by *)
wenzelm@39339
  3163
                (* 'element', returns the constructor (as a term) as well as the *)
wenzelm@39339
  3164
                (* indices of the arguments                                      *)
wenzelm@39339
  3165
                fun get_constr_args (cname, cargs) =
wenzelm@22567
  3166
                  let
wenzelm@39339
  3167
                    val cTerm      = Const (cname,
wenzelm@39339
  3168
                      map (typ_of_dtyp descr typ_assoc) cargs ---> Type (s, Ts))
wenzelm@39339
  3169
                    val (iC, _, _) = interpret thy (typs, []) {maxvars=0,
wenzelm@39339
  3170
                      def_eq=false, next_idx=1, bounds=[], wellformed=True} cTerm
wenzelm@39339
  3171
                    (* interpretation -> int list option *)
wenzelm@39339
  3172
                    fun get_args (Leaf xs) =
wenzelm@39339
  3173
                          if find_index (fn x => x = True) xs = element then
wenzelm@39339
  3174
                            SOME []
wenzelm@39339
  3175
                          else
wenzelm@39339
  3176
                            NONE
wenzelm@39339
  3177
                      | get_args (Node xs) =
wenzelm@39339
  3178
                          let
wenzelm@39339
  3179
                            (* interpretation * int -> int list option *)
wenzelm@39339
  3180
                            fun search ([], _) =
wenzelm@39339
  3181
                              NONE
wenzelm@39339
  3182
                              | search (x::xs, n) =
wenzelm@39339
  3183
                              (case get_args x of
wenzelm@39339
  3184
                                SOME result => SOME (n::result)
wenzelm@39339
  3185
                              | NONE        => search (xs, n+1))
wenzelm@39339
  3186
                          in
wenzelm@39339
  3187
                            search (xs, 0)
wenzelm@39339
  3188
                          end
wenzelm@22567
  3189
                  in
wenzelm@39339
  3190
                    Option.map (fn args => (cTerm, cargs, args)) (get_args iC)
wenzelm@22567
  3191
                  end
wenzelm@39339
  3192
                val (cTerm, cargs, args) =
wenzelm@39339
  3193
                  (* we could speed things up by computing the correct          *)
wenzelm@39339
  3194
                  (* constructor directly (rather than testing all              *)
wenzelm@39339
  3195
                  (* constructors), based on the order in which constructors    *)
wenzelm@39339
  3196
                  (* generate elements of datatypes; the current implementation *)
wenzelm@39339
  3197
                  (* of 'IDT_printer' however is independent of the internals   *)
wenzelm@39339
  3198
                  (* of 'IDT_constructor_interpreter'                           *)
wenzelm@39339
  3199
                  (case get_first get_constr_args constrs of
wenzelm@39339
  3200
                    SOME x => x
wenzelm@39339
  3201
                  | NONE   => raise REFUTE ("IDT_printer",
wenzelm@39339
  3202
                    "no matching constructor found for element " ^
wenzelm@39339
  3203
                    string_of_int element))
wenzelm@39339
  3204
                val argsTerms = map (fn (d, n) =>
wenzelm@39339
  3205
                  let
wenzelm@39339
  3206
                    val dT = typ_of_dtyp descr typ_assoc d
wenzelm@39339
  3207
                    (* we only need the n-th element of this list, so there   *)
wenzelm@39339
  3208
                    (* might be a more efficient implementation that does not *)
wenzelm@39339
  3209
                    (* generate all constants                                 *)
wenzelm@39339
  3210
                    val consts = make_constants thy (typs, []) dT
wenzelm@39339
  3211
                  in
wenzelm@39339
  3212
                    print thy (typs, []) dT (List.nth (consts, n)) assignment
wenzelm@39339
  3213
                  end) (cargs ~~ args)
wenzelm@22567
  3214
              in
wenzelm@39339
  3215
                SOME (list_comb (cTerm, argsTerms))
wenzelm@22567
  3216
              end
wenzelm@22567
  3217
          end
wenzelm@22567
  3218
      | NONE =>  (* not an inductive datatype *)
wenzelm@39339
  3219
          NONE)
wenzelm@39339
  3220
  | _ =>  (* a (free or schematic) type variable *)
webertj@25014
  3221
      NONE);
webertj@14456
  3222
webertj@14350
  3223
webertj@14350
  3224
(* ------------------------------------------------------------------------- *)
webertj@14456
  3225
(* use 'setup Refute.setup' in an Isabelle theory to initialize the 'Refute' *)
webertj@14456
  3226
(* structure                                                                 *)
webertj@14350
  3227
(* ------------------------------------------------------------------------- *)
webertj@14350
  3228
webertj@14350
  3229
(* ------------------------------------------------------------------------- *)
webertj@14456
  3230
(* Note: the interpreters and printers are used in reverse order; however,   *)
webertj@14456
  3231
(*       an interpreter that can handle non-atomic terms ends up being       *)
webertj@14807
  3232
(*       applied before the 'stlc_interpreter' breaks the term apart into    *)
webertj@14807
  3233
(*       subterms that are then passed to other interpreters!                *)
webertj@14350
  3234
(* ------------------------------------------------------------------------- *)
webertj@14350
  3235
wenzelm@39339
  3236
val setup =
wenzelm@39339
  3237
   add_interpreter "stlc"    stlc_interpreter #>
wenzelm@39339
  3238
   add_interpreter "Pure"    Pure_interpreter #>
wenzelm@39339
  3239
   add_interpreter "HOLogic" HOLogic_interpreter #>
wenzelm@39339
  3240
   add_interpreter "set"     set_interpreter #>
wenzelm@39339
  3241
   add_interpreter "IDT"             IDT_interpreter #>
wenzelm@39339
  3242
   add_interpreter "IDT_constructor" IDT_constructor_interpreter #>
wenzelm@39339
  3243
   add_interpreter "IDT_recursion"   IDT_recursion_interpreter #>
wenzelm@39339
  3244
   add_interpreter "Finite_Set.card"    Finite_Set_card_interpreter #>
wenzelm@39339
  3245
   add_interpreter "Finite_Set.finite"  Finite_Set_finite_interpreter #>
wenzelm@39339
  3246
   add_interpreter "Nat_Orderings.less" Nat_less_interpreter #>
wenzelm@39339
  3247
   add_interpreter "Nat_HOL.plus"       Nat_plus_interpreter #>
wenzelm@39339
  3248
   add_interpreter "Nat_HOL.minus"      Nat_minus_interpreter #>
wenzelm@39339
  3249
   add_interpreter "Nat_HOL.times"      Nat_times_interpreter #>
wenzelm@39339
  3250
   add_interpreter "List.append" List_append_interpreter #>
blanchet@36130
  3251
(* UNSOUND
wenzelm@39339
  3252
   add_interpreter "lfp" lfp_interpreter #>
wenzelm@39339
  3253
   add_interpreter "gfp" gfp_interpreter #>
blanchet@36130
  3254
*)
wenzelm@39339
  3255
   add_interpreter "Product_Type.fst" Product_Type_fst_interpreter #>
wenzelm@39339
  3256
   add_interpreter "Product_Type.snd" Product_Type_snd_interpreter #>
wenzelm@39339
  3257
   add_printer "stlc" stlc_printer #>
wenzelm@39339
  3258
   add_printer "IDT"  IDT_printer;
webertj@14350
  3259
wenzelm@39341
  3260
wenzelm@39341
  3261
wenzelm@39341
  3262
(** outer syntax commands 'refute' and 'refute_params' **)
wenzelm@39341
  3263
wenzelm@39341
  3264
(* argument parsing *)
wenzelm@39341
  3265
wenzelm@39341
  3266
(*optional list of arguments of the form [name1=value1, name2=value2, ...]*)
wenzelm@39341
  3267
wenzelm@39341
  3268
val scan_parm = Parse.name -- (Scan.optional (Parse.$$$ "=" |-- Parse.name) "true")
wenzelm@39341
  3269
val scan_parms = Scan.optional (Parse.$$$ "[" |-- Parse.list scan_parm --| Parse.$$$ "]") [];
wenzelm@39341
  3270
wenzelm@39341
  3271
wenzelm@39341
  3272
(* 'refute' command *)
wenzelm@39341
  3273
wenzelm@39341
  3274
val _ =
wenzelm@39341
  3275
  Outer_Syntax.improper_command "refute"
wenzelm@39341
  3276
    "try to find a model that refutes a given subgoal" Keyword.diag
wenzelm@39341
  3277
    (scan_parms -- Scan.optional Parse.nat 1 >>
wenzelm@39341
  3278
      (fn (parms, i) =>
wenzelm@39341
  3279
        Toplevel.keep (fn state =>
wenzelm@39341
  3280
          let
wenzelm@39341
  3281
            val ctxt = Toplevel.context_of state;
wenzelm@39341
  3282
            val {goal = st, ...} = Proof.raw_goal (Toplevel.proof_of state);
wenzelm@39341
  3283
          in refute_goal ctxt parms st i end)));
wenzelm@39341
  3284
wenzelm@39341
  3285
wenzelm@39341
  3286
(* 'refute_params' command *)
wenzelm@39341
  3287
wenzelm@39341
  3288
val _ =
wenzelm@39341
  3289
  Outer_Syntax.command "refute_params"
wenzelm@39341
  3290
    "show/store default parameters for the 'refute' command" Keyword.thy_decl
wenzelm@39341
  3291
    (scan_parms >> (fn parms =>
wenzelm@39341
  3292
      Toplevel.theory (fn thy =>
wenzelm@39341
  3293
        let
wenzelm@39341
  3294
          val thy' = fold set_default_param parms thy;
wenzelm@39341
  3295
          val output =
wenzelm@39341
  3296
            (case get_default_params thy' of
wenzelm@39341
  3297
              [] => "none"
wenzelm@39341
  3298
            | new_defaults => cat_lines (map (fn (x, y) => x ^ "=" ^ y) new_defaults));
wenzelm@39341
  3299
          val _ = writeln ("Default parameters for 'refute':\n" ^ output);
wenzelm@39341
  3300
        in thy' end)));
wenzelm@39341
  3301
wenzelm@39339
  3302
end;
wenzelm@39339
  3303