src/HOL/Library/refute.ML
author blanchet
Wed Sep 17 08:23:53 2014 +0200 (2014-09-17)
changeset 58354 04ac60da613e
parent 58322 f13f6e27d68e
child 58825 2065f49da190
permissions -rw-r--r--
support (finite values of) codatatypes in Quickcheck
     1 (*  Title:      HOL/Library/refute.ML
     2     Author:     Tjark Weber, TU Muenchen
     3 
     4 Finite model generation for HOL formulas, using a SAT solver.
     5 *)
     6 
     7 signature REFUTE =
     8 sig
     9 
    10   exception REFUTE of string * string
    11 
    12 (* ------------------------------------------------------------------------- *)
    13 (* Model/interpretation related code (translation HOL -> propositional logic *)
    14 (* ------------------------------------------------------------------------- *)
    15 
    16   type params
    17   type interpretation
    18   type model
    19   type arguments
    20 
    21   exception MAXVARS_EXCEEDED
    22 
    23   val add_interpreter : string -> (Proof.context -> model -> arguments -> term ->
    24     (interpretation * model * arguments) option) -> theory -> theory
    25   val add_printer : string -> (Proof.context -> model -> typ ->
    26     interpretation -> (int -> bool) -> term option) -> theory -> theory
    27 
    28   val interpret : Proof.context -> model -> arguments -> term ->
    29     (interpretation * model * arguments)
    30 
    31   val print : Proof.context -> model -> typ -> interpretation -> (int -> bool) -> term
    32   val print_model : Proof.context -> model -> (int -> bool) -> string
    33 
    34 (* ------------------------------------------------------------------------- *)
    35 (* Interface                                                                 *)
    36 (* ------------------------------------------------------------------------- *)
    37 
    38   val set_default_param  : (string * string) -> theory -> theory
    39   val get_default_param  : Proof.context -> string -> string option
    40   val get_default_params : Proof.context -> (string * string) list
    41   val actual_params      : Proof.context -> (string * string) list -> params
    42 
    43   val find_model :
    44     Proof.context -> params -> term list -> term -> bool -> string
    45 
    46   (* tries to find a model for a formula: *)
    47   val satisfy_term :
    48     Proof.context -> (string * string) list -> term list -> term -> string
    49   (* tries to find a model that refutes a formula: *)
    50   val refute_term :
    51     Proof.context -> (string * string) list -> term list -> term -> string
    52   val refute_goal :
    53     Proof.context -> (string * string) list -> thm -> int -> string
    54 
    55   val setup : theory -> theory
    56 
    57 (* ------------------------------------------------------------------------- *)
    58 (* Additional functions used by Nitpick (to be factored out)                 *)
    59 (* ------------------------------------------------------------------------- *)
    60 
    61   val get_classdef : theory -> string -> (string * term) option
    62   val norm_rhs : term -> term
    63   val get_def : theory -> string * typ -> (string * term) option
    64   val get_typedef : theory -> typ -> (string * term) option
    65   val is_IDT_constructor : theory -> string * typ -> bool
    66   val is_IDT_recursor : theory -> string * typ -> bool
    67   val is_const_of_class: theory -> string * typ -> bool
    68   val string_of_typ : typ -> string
    69 end;
    70 
    71 structure Refute : REFUTE =
    72 struct
    73 
    74 open Prop_Logic;
    75 
    76 (* We use 'REFUTE' only for internal error conditions that should    *)
    77 (* never occur in the first place (i.e. errors caused by bugs in our *)
    78 (* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
    79 (* 'error'.                                                          *)
    80 exception REFUTE of string * string;  (* ("in function", "cause") *)
    81 
    82 (* should be raised by an interpreter when more variables would be *)
    83 (* required than allowed by 'maxvars'                              *)
    84 exception MAXVARS_EXCEEDED;
    85 
    86 
    87 (* ------------------------------------------------------------------------- *)
    88 (* TREES                                                                     *)
    89 (* ------------------------------------------------------------------------- *)
    90 
    91 (* ------------------------------------------------------------------------- *)
    92 (* tree: implements an arbitrarily (but finitely) branching tree as a list   *)
    93 (*       of (lists of ...) elements                                          *)
    94 (* ------------------------------------------------------------------------- *)
    95 
    96 datatype 'a tree =
    97     Leaf of 'a
    98   | Node of ('a tree) list;
    99 
   100 fun tree_map f tr =
   101   case tr of
   102     Leaf x  => Leaf (f x)
   103   | Node xs => Node (map (tree_map f) xs);
   104 
   105 fun tree_pair (t1, t2) =
   106   case t1 of
   107     Leaf x =>
   108       (case t2 of
   109           Leaf y => Leaf (x,y)
   110         | Node _ => raise REFUTE ("tree_pair",
   111             "trees are of different height (second tree is higher)"))
   112   | Node xs =>
   113       (case t2 of
   114           (* '~~' will raise an exception if the number of branches in   *)
   115           (* both trees is different at the current node                 *)
   116           Node ys => Node (map tree_pair (xs ~~ ys))
   117         | Leaf _  => raise REFUTE ("tree_pair",
   118             "trees are of different height (first tree is higher)"));
   119 
   120 (* ------------------------------------------------------------------------- *)
   121 (* params: parameters that control the translation into a propositional      *)
   122 (*         formula/model generation                                          *)
   123 (*                                                                           *)
   124 (* The following parameters are supported (and required (!), except for      *)
   125 (* "sizes" and "expect"):                                                    *)
   126 (*                                                                           *)
   127 (* Name          Type    Description                                         *)
   128 (*                                                                           *)
   129 (* "sizes"       (string * int) list                                         *)
   130 (*                       Size of ground types (e.g. 'a=2), or depth of IDTs. *)
   131 (* "minsize"     int     If >0, minimal size of each ground type/IDT depth.  *)
   132 (* "maxsize"     int     If >0, maximal size of each ground type/IDT depth.  *)
   133 (* "maxvars"     int     If >0, use at most 'maxvars' Boolean variables      *)
   134 (*                       when transforming the term into a propositional     *)
   135 (*                       formula.                                            *)
   136 (* "maxtime"     int     If >0, terminate after at most 'maxtime' seconds.   *)
   137 (* "satsolver"   string  SAT solver to be used.                              *)
   138 (* "no_assms"    bool    If "true", assumptions in structured proofs are     *)
   139 (*                       not considered.                                     *)
   140 (* "expect"      string  Expected result ("genuine", "potential", "none", or *)
   141 (*                       "unknown").                                         *)
   142 (* ------------------------------------------------------------------------- *)
   143 
   144 type params =
   145   {
   146     sizes    : (string * int) list,
   147     minsize  : int,
   148     maxsize  : int,
   149     maxvars  : int,
   150     maxtime  : int,
   151     satsolver: string,
   152     no_assms : bool,
   153     expect   : string
   154   };
   155 
   156 (* ------------------------------------------------------------------------- *)
   157 (* interpretation: a term's interpretation is given by a variable of type    *)
   158 (*                 'interpretation'                                          *)
   159 (* ------------------------------------------------------------------------- *)
   160 
   161 type interpretation =
   162   prop_formula list tree;
   163 
   164 (* ------------------------------------------------------------------------- *)
   165 (* model: a model specifies the size of types and the interpretation of      *)
   166 (*        terms                                                              *)
   167 (* ------------------------------------------------------------------------- *)
   168 
   169 type model =
   170   (typ * int) list * (term * interpretation) list;
   171 
   172 (* ------------------------------------------------------------------------- *)
   173 (* arguments: additional arguments required during interpretation of terms   *)
   174 (* ------------------------------------------------------------------------- *)
   175 
   176 type arguments =
   177   {
   178     (* just passed unchanged from 'params': *)
   179     maxvars   : int,
   180     (* whether to use 'make_equality' or 'make_def_equality': *)
   181     def_eq    : bool,
   182     (* the following may change during the translation: *)
   183     next_idx  : int,
   184     bounds    : interpretation list,
   185     wellformed: prop_formula
   186   };
   187 
   188 structure Data = Theory_Data
   189 (
   190   type T =
   191     {interpreters: (string * (Proof.context -> model -> arguments -> term ->
   192       (interpretation * model * arguments) option)) list,
   193      printers: (string * (Proof.context -> model -> typ -> interpretation ->
   194       (int -> bool) -> term option)) list,
   195      parameters: string Symtab.table};
   196   val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
   197   val extend = I;
   198   fun merge
   199     ({interpreters = in1, printers = pr1, parameters = pa1},
   200      {interpreters = in2, printers = pr2, parameters = pa2}) : T =
   201     {interpreters = AList.merge (op =) (K true) (in1, in2),
   202      printers = AList.merge (op =) (K true) (pr1, pr2),
   203      parameters = Symtab.merge (op =) (pa1, pa2)};
   204 );
   205 
   206 val get_data = Data.get o Proof_Context.theory_of;
   207 
   208 
   209 (* ------------------------------------------------------------------------- *)
   210 (* interpret: interprets the term 't' using a suitable interpreter; returns  *)
   211 (*            the interpretation and a (possibly extended) model that keeps  *)
   212 (*            track of the interpretation of subterms                        *)
   213 (* ------------------------------------------------------------------------- *)
   214 
   215 fun interpret ctxt model args t =
   216   case get_first (fn (_, f) => f ctxt model args t)
   217       (#interpreters (get_data ctxt)) of
   218     NONE => raise REFUTE ("interpret",
   219       "no interpreter for term " ^ quote (Syntax.string_of_term ctxt t))
   220   | SOME x => x;
   221 
   222 (* ------------------------------------------------------------------------- *)
   223 (* print: converts the interpretation 'intr', which must denote a term of    *)
   224 (*        type 'T', into a term using a suitable printer                     *)
   225 (* ------------------------------------------------------------------------- *)
   226 
   227 fun print ctxt model T intr assignment =
   228   case get_first (fn (_, f) => f ctxt model T intr assignment)
   229       (#printers (get_data ctxt)) of
   230     NONE => raise REFUTE ("print",
   231       "no printer for type " ^ quote (Syntax.string_of_typ ctxt T))
   232   | SOME x => x;
   233 
   234 (* ------------------------------------------------------------------------- *)
   235 (* print_model: turns the model into a string, using a fixed interpretation  *)
   236 (*              (given by an assignment for Boolean variables) and suitable  *)
   237 (*              printers                                                     *)
   238 (* ------------------------------------------------------------------------- *)
   239 
   240 fun print_model ctxt model assignment =
   241   let
   242     val (typs, terms) = model
   243     val typs_msg =
   244       if null typs then
   245         "empty universe (no type variables in term)\n"
   246       else
   247         "Size of types: " ^ commas (map (fn (T, i) =>
   248           Syntax.string_of_typ ctxt T ^ ": " ^ string_of_int i) typs) ^ "\n"
   249     val show_consts_msg =
   250       if not (Config.get ctxt show_consts) andalso Library.exists (is_Const o fst) terms then
   251         "enable \"show_consts\" to show the interpretation of constants\n"
   252       else
   253         ""
   254     val terms_msg =
   255       if null terms then
   256         "empty interpretation (no free variables in term)\n"
   257       else
   258         cat_lines (map_filter (fn (t, intr) =>
   259           (* print constants only if 'show_consts' is true *)
   260           if Config.get ctxt show_consts orelse not (is_Const t) then
   261             SOME (Syntax.string_of_term ctxt t ^ ": " ^
   262               Syntax.string_of_term ctxt
   263                 (print ctxt model (Term.type_of t) intr assignment))
   264           else
   265             NONE) terms) ^ "\n"
   266   in
   267     typs_msg ^ show_consts_msg ^ terms_msg
   268   end;
   269 
   270 
   271 (* ------------------------------------------------------------------------- *)
   272 (* PARAMETER MANAGEMENT                                                      *)
   273 (* ------------------------------------------------------------------------- *)
   274 
   275 fun add_interpreter name f = Data.map (fn {interpreters, printers, parameters} =>
   276   case AList.lookup (op =) interpreters name of
   277     NONE => {interpreters = (name, f) :: interpreters,
   278       printers = printers, parameters = parameters}
   279   | SOME _ => error ("Interpreter " ^ name ^ " already declared"));
   280 
   281 fun add_printer name f = Data.map (fn {interpreters, printers, parameters} =>
   282   case AList.lookup (op =) printers name of
   283     NONE => {interpreters = interpreters,
   284       printers = (name, f) :: printers, parameters = parameters}
   285   | SOME _ => error ("Printer " ^ name ^ " already declared"));
   286 
   287 (* ------------------------------------------------------------------------- *)
   288 (* set_default_param: stores the '(name, value)' pair in Data's              *)
   289 (*                    parameter table                                        *)
   290 (* ------------------------------------------------------------------------- *)
   291 
   292 fun set_default_param (name, value) = Data.map
   293   (fn {interpreters, printers, parameters} =>
   294     {interpreters = interpreters, printers = printers,
   295       parameters = Symtab.update (name, value) parameters});
   296 
   297 (* ------------------------------------------------------------------------- *)
   298 (* get_default_param: retrieves the value associated with 'name' from        *)
   299 (*                    Data's parameter table                                 *)
   300 (* ------------------------------------------------------------------------- *)
   301 
   302 val get_default_param = Symtab.lookup o #parameters o get_data;
   303 
   304 (* ------------------------------------------------------------------------- *)
   305 (* get_default_params: returns a list of all '(name, value)' pairs that are  *)
   306 (*                     stored in Data's parameter table                      *)
   307 (* ------------------------------------------------------------------------- *)
   308 
   309 val get_default_params = Symtab.dest o #parameters o get_data;
   310 
   311 (* ------------------------------------------------------------------------- *)
   312 (* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
   313 (*      override the default parameters currently specified, and             *)
   314 (*      returns a record that can be passed to 'find_model'.                 *)
   315 (* ------------------------------------------------------------------------- *)
   316 
   317 fun actual_params ctxt override =
   318   let
   319     fun read_bool (parms, name) =
   320       case AList.lookup (op =) parms name of
   321         SOME "true" => true
   322       | SOME "false" => false
   323       | SOME s => error ("parameter " ^ quote name ^
   324           " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
   325       | NONE   => error ("parameter " ^ quote name ^
   326           " must be assigned a value")
   327     fun read_int (parms, name) =
   328       case AList.lookup (op =) parms name of
   329         SOME s =>
   330           (case Int.fromString s of
   331             SOME i => i
   332           | NONE   => error ("parameter " ^ quote name ^
   333             " (value is " ^ quote s ^ ") must be an integer value"))
   334       | NONE => error ("parameter " ^ quote name ^
   335           " must be assigned a value")
   336     fun read_string (parms, name) =
   337       case AList.lookup (op =) parms name of
   338         SOME s => s
   339       | NONE => error ("parameter " ^ quote name ^
   340         " must be assigned a value")
   341     (* 'override' first, defaults last: *)
   342     val allparams = override @ get_default_params ctxt
   343     val minsize = read_int (allparams, "minsize")
   344     val maxsize = read_int (allparams, "maxsize")
   345     val maxvars = read_int (allparams, "maxvars")
   346     val maxtime = read_int (allparams, "maxtime")
   347     val satsolver = read_string (allparams, "satsolver")
   348     val no_assms = read_bool (allparams, "no_assms")
   349     val expect = the_default "" (AList.lookup (op =) allparams "expect")
   350     (* all remaining parameters of the form "string=int" are collected in *)
   351     (* 'sizes'                                                            *)
   352     (* TODO: it is currently not possible to specify a size for a type    *)
   353     (*       whose name is one of the other parameters (e.g. 'maxvars')   *)
   354     (* (string * int) list *)
   355     val sizes = map_filter
   356       (fn (name, value) => Option.map (pair name) (Int.fromString value))
   357       (filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
   358         andalso name<>"maxvars" andalso name<>"maxtime"
   359         andalso name<>"satsolver" andalso name<>"no_assms") allparams)
   360   in
   361     {sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars,
   362       maxtime=maxtime, satsolver=satsolver, no_assms=no_assms, expect=expect}
   363   end;
   364 
   365 
   366 (* ------------------------------------------------------------------------- *)
   367 (* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
   368 (* ------------------------------------------------------------------------- *)
   369 
   370 fun typ_of_dtyp _ typ_assoc (Old_Datatype_Aux.DtTFree a) =
   371     the (AList.lookup (op =) typ_assoc (Old_Datatype_Aux.DtTFree a))
   372   | typ_of_dtyp descr typ_assoc (Old_Datatype_Aux.DtType (s, Us)) =
   373     Type (s, map (typ_of_dtyp descr typ_assoc) Us)
   374   | typ_of_dtyp descr typ_assoc (Old_Datatype_Aux.DtRec i) =
   375     let val (s, ds, _) = the (AList.lookup (op =) descr i) in
   376       Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   377     end
   378 
   379 val close_form = ATP_Util.close_form
   380 val monomorphic_term = ATP_Util.monomorphic_term
   381 val specialize_type = ATP_Util.specialize_type
   382 
   383 (* ------------------------------------------------------------------------- *)
   384 (* is_const_of_class: returns 'true' iff 'Const (s, T)' is a constant that   *)
   385 (*                    denotes membership to an axiomatic type class          *)
   386 (* ------------------------------------------------------------------------- *)
   387 
   388 fun is_const_of_class thy (s, _) =
   389   let
   390     val class_const_names = map Logic.const_of_class (Sign.all_classes thy)
   391   in
   392     (* I'm not quite sure if checking the name 's' is sufficient, *)
   393     (* or if we should also check the type 'T'.                   *)
   394     member (op =) class_const_names s
   395   end;
   396 
   397 (* ------------------------------------------------------------------------- *)
   398 (* is_IDT_constructor: returns 'true' iff 'Const (s, T)' is the constructor  *)
   399 (*                     of an inductive datatype in 'thy'                     *)
   400 (* ------------------------------------------------------------------------- *)
   401 
   402 fun is_IDT_constructor thy (s, T) =
   403   (case body_type T of
   404     Type (s', _) =>
   405       (case BNF_LFP_Compat.get_constrs thy s' of
   406         SOME constrs =>
   407           List.exists (fn (cname, cty) =>
   408             cname = s andalso Sign.typ_instance thy (T, cty)) constrs
   409       | NONE => false)
   410   | _  => false);
   411 
   412 (* ------------------------------------------------------------------------- *)
   413 (* is_IDT_recursor: returns 'true' iff 'Const (s, T)' is the recursion       *)
   414 (*                  operator of an inductive datatype in 'thy'               *)
   415 (* ------------------------------------------------------------------------- *)
   416 
   417 fun is_IDT_recursor thy (s, _) =
   418   let
   419     val rec_names = Symtab.fold (append o #rec_names o snd) (BNF_LFP_Compat.get_all thy []) []
   420   in
   421     (* I'm not quite sure if checking the name 's' is sufficient, *)
   422     (* or if we should also check the type 'T'.                   *)
   423     member (op =) rec_names s
   424   end;
   425 
   426 (* ------------------------------------------------------------------------- *)
   427 (* norm_rhs: maps  f ?t1 ... ?tn == rhs  to  %t1...tn. rhs                   *)
   428 (* ------------------------------------------------------------------------- *)
   429 
   430 fun norm_rhs eqn =
   431   let
   432     fun lambda (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
   433       | lambda v t = raise TERM ("lambda", [v, t])
   434     val (lhs, rhs) = Logic.dest_equals eqn
   435     val (_, args) = Term.strip_comb lhs
   436   in
   437     fold lambda (rev args) rhs
   438   end
   439 
   440 (* ------------------------------------------------------------------------- *)
   441 (* get_def: looks up the definition of a constant                            *)
   442 (* ------------------------------------------------------------------------- *)
   443 
   444 fun get_def thy (s, T) =
   445   let
   446     fun get_def_ax [] = NONE
   447       | get_def_ax ((axname, ax) :: axioms) =
   448           (let
   449             val (lhs, _) = Logic.dest_equals ax  (* equations only *)
   450             val c        = Term.head_of lhs
   451             val (s', T') = Term.dest_Const c
   452           in
   453             if s=s' then
   454               let
   455                 val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
   456                 val ax'      = monomorphic_term typeSubs ax
   457                 val rhs      = norm_rhs ax'
   458               in
   459                 SOME (axname, rhs)
   460               end
   461             else
   462               get_def_ax axioms
   463           end handle ERROR _         => get_def_ax axioms
   464                    | TERM _          => get_def_ax axioms
   465                    | Type.TYPE_MATCH => get_def_ax axioms)
   466   in
   467     get_def_ax (Theory.all_axioms_of thy)
   468   end;
   469 
   470 (* ------------------------------------------------------------------------- *)
   471 (* get_typedef: looks up the definition of a type, as created by "typedef"   *)
   472 (* ------------------------------------------------------------------------- *)
   473 
   474 fun get_typedef thy T =
   475   let
   476     fun get_typedef_ax [] = NONE
   477       | get_typedef_ax ((axname, ax) :: axioms) =
   478           (let
   479             fun type_of_type_definition (Const (s', T')) =
   480                   if s'= @{const_name type_definition} then
   481                     SOME T'
   482                   else
   483                     NONE
   484               | type_of_type_definition (Free _) = NONE
   485               | type_of_type_definition (Var _) = NONE
   486               | type_of_type_definition (Bound _) = NONE
   487               | type_of_type_definition (Abs (_, _, body)) =
   488                   type_of_type_definition body
   489               | type_of_type_definition (t1 $ t2) =
   490                   (case type_of_type_definition t1 of
   491                     SOME x => SOME x
   492                   | NONE => type_of_type_definition t2)
   493           in
   494             case type_of_type_definition ax of
   495               SOME T' =>
   496                 let
   497                   val T'' = domain_type (domain_type T')
   498                   val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
   499                 in
   500                   SOME (axname, monomorphic_term typeSubs ax)
   501                 end
   502             | NONE => get_typedef_ax axioms
   503           end handle ERROR _         => get_typedef_ax axioms
   504                    | TERM _          => get_typedef_ax axioms
   505                    | Type.TYPE_MATCH => get_typedef_ax axioms)
   506   in
   507     get_typedef_ax (Theory.all_axioms_of thy)
   508   end;
   509 
   510 (* ------------------------------------------------------------------------- *)
   511 (* get_classdef: looks up the defining axiom for an axiomatic type class, as *)
   512 (*               created by the "axclass" command                            *)
   513 (* ------------------------------------------------------------------------- *)
   514 
   515 fun get_classdef thy class =
   516   let
   517     val axname = class ^ "_class_def"
   518   in
   519     Option.map (pair axname)
   520       (AList.lookup (op =) (Theory.all_axioms_of thy) axname)
   521   end;
   522 
   523 (* ------------------------------------------------------------------------- *)
   524 (* unfold_defs: unfolds all defined constants in a term 't', beta-eta        *)
   525 (*              normalizes the result term; certain constants are not        *)
   526 (*              unfolded (cf. 'collect_axioms' and the various interpreters  *)
   527 (*              below): if the interpretation respects a definition anyway,  *)
   528 (*              that definition does not need to be unfolded                 *)
   529 (* ------------------------------------------------------------------------- *)
   530 
   531 (* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
   532 (*       normalization; this would save some unfolding for terms where    *)
   533 (*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
   534 (*       the other hand, this would cause additional work for terms where *)
   535 (*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
   536 
   537 fun unfold_defs thy t =
   538   let
   539     fun unfold_loop t =
   540       case t of
   541       (* Pure *)
   542         Const (@{const_name Pure.all}, _) => t
   543       | Const (@{const_name Pure.eq}, _) => t
   544       | Const (@{const_name Pure.imp}, _) => t
   545       | Const (@{const_name Pure.type}, _) => t  (* axiomatic type classes *)
   546       (* HOL *)
   547       | Const (@{const_name Trueprop}, _) => t
   548       | Const (@{const_name Not}, _) => t
   549       | (* redundant, since 'True' is also an IDT constructor *)
   550         Const (@{const_name True}, _) => t
   551       | (* redundant, since 'False' is also an IDT constructor *)
   552         Const (@{const_name False}, _) => t
   553       | Const (@{const_name undefined}, _) => t
   554       | Const (@{const_name The}, _) => t
   555       | Const (@{const_name Hilbert_Choice.Eps}, _) => t
   556       | Const (@{const_name All}, _) => t
   557       | Const (@{const_name Ex}, _) => t
   558       | Const (@{const_name HOL.eq}, _) => t
   559       | Const (@{const_name HOL.conj}, _) => t
   560       | Const (@{const_name HOL.disj}, _) => t
   561       | Const (@{const_name HOL.implies}, _) => t
   562       (* sets *)
   563       | Const (@{const_name Collect}, _) => t
   564       | Const (@{const_name Set.member}, _) => t
   565       (* other optimizations *)
   566       | Const (@{const_name Finite_Set.card}, _) => t
   567       | Const (@{const_name Finite_Set.finite}, _) => t
   568       | Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
   569           Type ("fun", [@{typ nat}, @{typ bool}])])) => t
   570       | Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
   571           Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   572       | Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
   573           Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   574       | Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
   575           Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   576       | Const (@{const_name append}, _) => t
   577       | Const (@{const_name fst}, _) => t
   578       | Const (@{const_name snd}, _) => t
   579       (* simply-typed lambda calculus *)
   580       | Const (s, T) =>
   581           (if is_IDT_constructor thy (s, T)
   582             orelse is_IDT_recursor thy (s, T) then
   583             t  (* do not unfold IDT constructors/recursors *)
   584           (* unfold the constant if there is a defining equation *)
   585           else
   586             case get_def thy (s, T) of
   587               SOME ((*axname*) _, rhs) =>
   588               (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
   589               (* occurs on the right-hand side of the equation, i.e. in  *)
   590               (* 'rhs', we must not use this equation to unfold, because *)
   591               (* that would loop.  Here would be the right place to      *)
   592               (* check this.  However, getting this really right seems   *)
   593               (* difficult because the user may state arbitrary axioms,  *)
   594               (* which could interact with overloading to create loops.  *)
   595               ((*tracing (" unfolding: " ^ axname);*)
   596                unfold_loop rhs)
   597             | NONE => t)
   598       | Free _ => t
   599       | Var _ => t
   600       | Bound _ => t
   601       | Abs (s, T, body) => Abs (s, T, unfold_loop body)
   602       | t1 $ t2 => (unfold_loop t1) $ (unfold_loop t2)
   603     val result = Envir.beta_eta_contract (unfold_loop t)
   604   in
   605     result
   606   end;
   607 
   608 (* ------------------------------------------------------------------------- *)
   609 (* collect_axioms: collects (monomorphic, universally quantified, unfolded   *)
   610 (*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
   611 (* ------------------------------------------------------------------------- *)
   612 
   613 (* Note: to make the collection of axioms more easily extensible, this    *)
   614 (*       function could be based on user-supplied "axiom collectors",     *)
   615 (*       similar to 'interpret'/interpreters or 'print'/printers          *)
   616 
   617 (* Note: currently we use "inverse" functions to the definitional         *)
   618 (*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
   619 (*       "typedef", "definition".  A more general approach could consider *)
   620 (*       *every* axiom of the theory and collect it if it has a constant/ *)
   621 (*       type/typeclass in common with the term 't'.                      *)
   622 
   623 (* Which axioms are "relevant" for a particular term/type goes hand in    *)
   624 (* hand with the interpretation of that term/type by its interpreter (see *)
   625 (* way below): if the interpretation respects an axiom anyway, the axiom  *)
   626 (* does not need to be added as a constraint here.                        *)
   627 
   628 (* To avoid collecting the same axiom multiple times, we use an           *)
   629 (* accumulator 'axs' which contains all axioms collected so far.          *)
   630 
   631 local
   632 
   633 fun get_axiom thy xname =
   634   Name_Space.check (Context.Theory thy) (Theory.axiom_table thy) (xname, Position.none);
   635 
   636 val the_eq_trivial = get_axiom @{theory HOL} "the_eq_trivial";
   637 val someI = get_axiom @{theory Hilbert_Choice} "someI";
   638 
   639 in
   640 
   641 fun collect_axioms ctxt t =
   642   let
   643     val thy = Proof_Context.theory_of ctxt
   644     val _ = tracing "Adding axioms..."
   645     fun collect_this_axiom (axname, ax) axs =
   646       let
   647         val ax' = unfold_defs thy ax
   648       in
   649         if member (op aconv) axs ax' then axs
   650         else (tracing axname; collect_term_axioms ax' (ax' :: axs))
   651       end
   652     and collect_sort_axioms T axs =
   653       let
   654         val sort =
   655           (case T of
   656             TFree (_, sort) => sort
   657           | TVar (_, sort)  => sort
   658           | _ => raise REFUTE ("collect_axioms",
   659               "type " ^ Syntax.string_of_typ ctxt T ^ " is not a variable"))
   660         (* obtain axioms for all superclasses *)
   661         val superclasses = sort @ maps (Sign.super_classes thy) sort
   662         (* merely an optimization, because 'collect_this_axiom' disallows *)
   663         (* duplicate axioms anyway:                                       *)
   664         val superclasses = distinct (op =) superclasses
   665         val class_axioms = maps (fn class => map (fn ax =>
   666           ("<" ^ class ^ ">", Thm.prop_of ax))
   667           (#axioms (Axclass.get_info thy class) handle ERROR _ => []))
   668           superclasses
   669         (* replace the (at most one) schematic type variable in each axiom *)
   670         (* by the actual type 'T'                                          *)
   671         val monomorphic_class_axioms = map (fn (axname, ax) =>
   672           (case Term.add_tvars ax [] of
   673             [] => (axname, ax)
   674           | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
   675           | _ =>
   676             raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
   677               Syntax.string_of_term ctxt ax ^
   678               ") contains more than one type variable")))
   679           class_axioms
   680       in
   681         fold collect_this_axiom monomorphic_class_axioms axs
   682       end
   683     and collect_type_axioms T axs =
   684       case T of
   685       (* simple types *)
   686         Type (@{type_name prop}, []) => axs
   687       | Type (@{type_name fun}, [T1, T2]) => collect_type_axioms T2 (collect_type_axioms T1 axs)
   688       | Type (@{type_name set}, [T1]) => collect_type_axioms T1 axs
   689       (* axiomatic type classes *)
   690       | Type (@{type_name itself}, [T1]) => collect_type_axioms T1 axs
   691       | Type (s, Ts) =>
   692         (case BNF_LFP_Compat.get_info thy [] s of
   693           SOME _ =>  (* inductive datatype *)
   694             (* only collect relevant type axioms for the argument types *)
   695             fold collect_type_axioms Ts axs
   696         | NONE =>
   697           (case get_typedef thy T of
   698             SOME (axname, ax) =>
   699               collect_this_axiom (axname, ax) axs
   700           | NONE =>
   701             (* unspecified type, perhaps introduced with "typedecl" *)
   702             (* at least collect relevant type axioms for the argument types *)
   703             fold collect_type_axioms Ts axs))
   704       (* axiomatic type classes *)
   705       | TFree _ => collect_sort_axioms T axs
   706       (* axiomatic type classes *)
   707       | TVar _ => collect_sort_axioms T axs
   708     and collect_term_axioms t axs =
   709       case t of
   710       (* Pure *)
   711         Const (@{const_name Pure.all}, _) => axs
   712       | Const (@{const_name Pure.eq}, _) => axs
   713       | Const (@{const_name Pure.imp}, _) => axs
   714       (* axiomatic type classes *)
   715       | Const (@{const_name Pure.type}, T) => collect_type_axioms T axs
   716       (* HOL *)
   717       | Const (@{const_name Trueprop}, _) => axs
   718       | Const (@{const_name Not}, _) => axs
   719       (* redundant, since 'True' is also an IDT constructor *)
   720       | Const (@{const_name True}, _) => axs
   721       (* redundant, since 'False' is also an IDT constructor *)
   722       | Const (@{const_name False}, _) => axs
   723       | Const (@{const_name undefined}, T) => collect_type_axioms T axs
   724       | Const (@{const_name The}, T) =>
   725           let
   726             val ax = specialize_type thy (@{const_name The}, T) (#2 the_eq_trivial)
   727           in
   728             collect_this_axiom (#1 the_eq_trivial, ax) axs
   729           end
   730       | Const (@{const_name Hilbert_Choice.Eps}, T) =>
   731           let
   732             val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T) (#2 someI)
   733           in
   734             collect_this_axiom (#1 someI, ax) axs
   735           end
   736       | Const (@{const_name All}, T) => collect_type_axioms T axs
   737       | Const (@{const_name Ex}, T) => collect_type_axioms T axs
   738       | Const (@{const_name HOL.eq}, T) => collect_type_axioms T axs
   739       | Const (@{const_name HOL.conj}, _) => axs
   740       | Const (@{const_name HOL.disj}, _) => axs
   741       | Const (@{const_name HOL.implies}, _) => axs
   742       (* sets *)
   743       | Const (@{const_name Collect}, T) => collect_type_axioms T axs
   744       | Const (@{const_name Set.member}, T) => collect_type_axioms T axs
   745       (* other optimizations *)
   746       | Const (@{const_name Finite_Set.card}, T) => collect_type_axioms T axs
   747       | Const (@{const_name Finite_Set.finite}, T) =>
   748         collect_type_axioms T axs
   749       | Const (@{const_name Orderings.less}, T as Type ("fun", [@{typ nat},
   750         Type ("fun", [@{typ nat}, @{typ bool}])])) =>
   751           collect_type_axioms T axs
   752       | Const (@{const_name Groups.plus}, T as Type ("fun", [@{typ nat},
   753         Type ("fun", [@{typ nat}, @{typ nat}])])) =>
   754           collect_type_axioms T axs
   755       | Const (@{const_name Groups.minus}, T as Type ("fun", [@{typ nat},
   756         Type ("fun", [@{typ nat}, @{typ nat}])])) =>
   757           collect_type_axioms T axs
   758       | Const (@{const_name Groups.times}, T as Type ("fun", [@{typ nat},
   759         Type ("fun", [@{typ nat}, @{typ nat}])])) =>
   760           collect_type_axioms T axs
   761       | Const (@{const_name append}, T) => collect_type_axioms T axs
   762       | Const (@{const_name fst}, T) => collect_type_axioms T axs
   763       | Const (@{const_name snd}, T) => collect_type_axioms T axs
   764       (* simply-typed lambda calculus *)
   765       | Const (s, T) =>
   766           if is_const_of_class thy (s, T) then
   767             (* axiomatic type classes: add "OFCLASS(?'a::c, c_class)" *)
   768             (* and the class definition                               *)
   769             let
   770               val class = Logic.class_of_const s
   771               val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]), class)
   772               val ax_in = SOME (specialize_type thy (s, T) of_class)
   773                 (* type match may fail due to sort constraints *)
   774                 handle Type.TYPE_MATCH => NONE
   775               val ax_1 = Option.map (fn ax => (Syntax.string_of_term ctxt ax, ax)) ax_in
   776               val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
   777             in
   778               collect_type_axioms T (fold collect_this_axiom (map_filter I [ax_1, ax_2]) axs)
   779             end
   780           else if is_IDT_constructor thy (s, T)
   781             orelse is_IDT_recursor thy (s, T)
   782           then
   783             (* only collect relevant type axioms *)
   784             collect_type_axioms T axs
   785           else
   786             (* other constants should have been unfolded, with some *)
   787             (* exceptions: e.g. Abs_xxx/Rep_xxx functions for       *)
   788             (* typedefs, or type-class related constants            *)
   789             (* only collect relevant type axioms *)
   790             collect_type_axioms T axs
   791       | Free (_, T) => collect_type_axioms T axs
   792       | Var (_, T) => collect_type_axioms T axs
   793       | Bound _ => axs
   794       | Abs (_, T, body) => collect_term_axioms body (collect_type_axioms T axs)
   795       | t1 $ t2 => collect_term_axioms t2 (collect_term_axioms t1 axs)
   796     val result = map close_form (collect_term_axioms t [])
   797     val _ = tracing " ...done."
   798   in
   799     result
   800   end;
   801 
   802 end;
   803 
   804 (* ------------------------------------------------------------------------- *)
   805 (* ground_types: collects all ground types in a term (including argument     *)
   806 (*               types of other types), suppressing duplicates.  Does not    *)
   807 (*               return function types, set types, non-recursive IDTs, or    *)
   808 (*               'propT'.  For IDTs, also the argument types of constructors *)
   809 (*               and all mutually recursive IDTs are considered.             *)
   810 (* ------------------------------------------------------------------------- *)
   811 
   812 fun ground_types ctxt t =
   813   let
   814     val thy = Proof_Context.theory_of ctxt
   815     fun collect_types T acc =
   816       (case T of
   817         Type (@{type_name fun}, [T1, T2]) => collect_types T1 (collect_types T2 acc)
   818       | Type (@{type_name prop}, []) => acc
   819       | Type (@{type_name set}, [T1]) => collect_types T1 acc
   820       | Type (s, Ts) =>
   821           (case BNF_LFP_Compat.get_info thy [] s of
   822             SOME info =>  (* inductive datatype *)
   823               let
   824                 val index = #index info
   825                 val descr = #descr info
   826                 val (_, typs, _) = the (AList.lookup (op =) descr index)
   827                 val typ_assoc = typs ~~ Ts
   828                 (* sanity check: every element in 'dtyps' must be a *)
   829                 (* 'DtTFree'                                        *)
   830                 val _ = if Library.exists (fn d =>
   831                   case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) typs then
   832                   raise REFUTE ("ground_types", "datatype argument (for type "
   833                     ^ Syntax.string_of_typ ctxt T ^ ") is not a variable")
   834                 else ()
   835                 (* required for mutually recursive datatypes; those need to   *)
   836                 (* be added even if they are an instance of an otherwise non- *)
   837                 (* recursive datatype                                         *)
   838                 fun collect_dtyp d acc =
   839                   let
   840                     val dT = typ_of_dtyp descr typ_assoc d
   841                   in
   842                     case d of
   843                       Old_Datatype_Aux.DtTFree _ =>
   844                       collect_types dT acc
   845                     | Old_Datatype_Aux.DtType (_, ds) =>
   846                       collect_types dT (fold_rev collect_dtyp ds acc)
   847                     | Old_Datatype_Aux.DtRec i =>
   848                       if member (op =) acc dT then
   849                         acc  (* prevent infinite recursion *)
   850                       else
   851                         let
   852                           val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
   853                           (* if the current type is a recursive IDT (i.e. a depth *)
   854                           (* is required), add it to 'acc'                        *)
   855                           val acc_dT = if Library.exists (fn (_, ds) =>
   856                             Library.exists Old_Datatype_Aux.is_rec_type ds) dconstrs then
   857                               insert (op =) dT acc
   858                             else acc
   859                           (* collect argument types *)
   860                           val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
   861                           (* collect constructor types *)
   862                           val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
   863                         in
   864                           acc_dconstrs
   865                         end
   866                   end
   867               in
   868                 (* argument types 'Ts' could be added here, but they are also *)
   869                 (* added by 'collect_dtyp' automatically                      *)
   870                 collect_dtyp (Old_Datatype_Aux.DtRec index) acc
   871               end
   872           | NONE =>
   873             (* not an inductive datatype, e.g. defined via "typedef" or *)
   874             (* "typedecl"                                               *)
   875             insert (op =) T (fold collect_types Ts acc))
   876       | TFree _ => insert (op =) T acc
   877       | TVar _ => insert (op =) T acc)
   878   in
   879     fold_types collect_types t []
   880   end;
   881 
   882 (* ------------------------------------------------------------------------- *)
   883 (* string_of_typ: (rather naive) conversion from types to strings, used to   *)
   884 (*                look up the size of a type in 'sizes'.  Parameterized      *)
   885 (*                types with different parameters (e.g. "'a list" vs. "bool  *)
   886 (*                list") are identified.                                     *)
   887 (* ------------------------------------------------------------------------- *)
   888 
   889 fun string_of_typ (Type (s, _))     = s
   890   | string_of_typ (TFree (s, _))    = s
   891   | string_of_typ (TVar ((s,_), _)) = s;
   892 
   893 (* ------------------------------------------------------------------------- *)
   894 (* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
   895 (*                 'minsize' to every type for which no size is specified in *)
   896 (*                 'sizes'                                                   *)
   897 (* ------------------------------------------------------------------------- *)
   898 
   899 fun first_universe xs sizes minsize =
   900   let
   901     fun size_of_typ T =
   902       case AList.lookup (op =) sizes (string_of_typ T) of
   903         SOME n => n
   904       | NONE => minsize
   905   in
   906     map (fn T => (T, size_of_typ T)) xs
   907   end;
   908 
   909 (* ------------------------------------------------------------------------- *)
   910 (* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
   911 (*                types), where the minimal size of a type is given by       *)
   912 (*                'minsize', the maximal size is given by 'maxsize', and a   *)
   913 (*                type may have a fixed size given in 'sizes'                *)
   914 (* ------------------------------------------------------------------------- *)
   915 
   916 fun next_universe xs sizes minsize maxsize =
   917   let
   918     (* creates the "first" list of length 'len', where the sum of all list *)
   919     (* elements is 'sum', and the length of the list is 'len'              *)
   920     fun make_first _ 0 sum =
   921           if sum = 0 then
   922             SOME []
   923           else
   924             NONE
   925       | make_first max len sum =
   926           if sum <= max orelse max < 0 then
   927             Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
   928           else
   929             Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
   930     (* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
   931     (* all list elements x (unless 'max'<0)                                *)
   932     fun next _ _ _ [] =
   933           NONE
   934       | next max len sum [x] =
   935           (* we've reached the last list element, so there's no shift possible *)
   936           make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
   937       | next max len sum (x1::x2::xs) =
   938           if x1>0 andalso (x2<max orelse max<0) then
   939             (* we can shift *)
   940             SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
   941           else
   942             (* continue search *)
   943             next max (len+1) (sum+x1) (x2::xs)
   944     (* only consider those types for which the size is not fixed *)
   945     val mutables = filter_out (AList.defined (op =) sizes o string_of_typ o fst) xs
   946     (* subtract 'minsize' from every size (will be added again at the end) *)
   947     val diffs = map (fn (_, n) => n-minsize) mutables
   948   in
   949     case next (maxsize-minsize) 0 0 diffs of
   950       SOME diffs' =>
   951         (* merge with those types for which the size is fixed *)
   952         SOME (fst (fold_map (fn (T, _) => fn ds =>
   953           case AList.lookup (op =) sizes (string_of_typ T) of
   954           (* return the fixed size *)
   955             SOME n => ((T, n), ds)
   956           (* consume the head of 'ds', add 'minsize' *)
   957           | NONE   => ((T, minsize + hd ds), tl ds))
   958           xs diffs'))
   959     | NONE => NONE
   960   end;
   961 
   962 (* ------------------------------------------------------------------------- *)
   963 (* toTrue: converts the interpretation of a Boolean value to a propositional *)
   964 (*         formula that is true iff the interpretation denotes "true"        *)
   965 (* ------------------------------------------------------------------------- *)
   966 
   967 fun toTrue (Leaf [fm, _]) = fm
   968   | toTrue _ = raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
   969 
   970 (* ------------------------------------------------------------------------- *)
   971 (* toFalse: converts the interpretation of a Boolean value to a              *)
   972 (*          propositional formula that is true iff the interpretation        *)
   973 (*          denotes "false"                                                  *)
   974 (* ------------------------------------------------------------------------- *)
   975 
   976 fun toFalse (Leaf [_, fm]) = fm
   977   | toFalse _ = raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
   978 
   979 (* ------------------------------------------------------------------------- *)
   980 (* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
   981 (*             applies a SAT solver, and (in case a model is found) displays *)
   982 (*             the model to the user by calling 'print_model'                *)
   983 (* {...}     : parameters that control the translation/model generation      *)
   984 (* assm_ts   : assumptions to be considered unless "no_assms" is specified   *)
   985 (* t         : term to be translated into a propositional formula            *)
   986 (* negate    : if true, find a model that makes 't' false (rather than true) *)
   987 (* ------------------------------------------------------------------------- *)
   988 
   989 fun find_model ctxt
   990     {sizes, minsize, maxsize, maxvars, maxtime, satsolver, no_assms, expect}
   991     assm_ts t negate =
   992   let
   993     val thy = Proof_Context.theory_of ctxt
   994     fun check_expect outcome_code =
   995       if expect = "" orelse outcome_code = expect then outcome_code
   996       else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
   997     fun wrapper () =
   998       let
   999         val timer = Timer.startRealTimer ()
  1000         val t =
  1001           if no_assms then t
  1002           else if negate then Logic.list_implies (assm_ts, t)
  1003           else Logic.mk_conjunction_list (t :: assm_ts)
  1004         val u = unfold_defs thy t
  1005         val _ = tracing ("Unfolded term: " ^ Syntax.string_of_term ctxt u)
  1006         val axioms = collect_axioms ctxt u
  1007         val types = fold (union (op =) o ground_types ctxt) (u :: axioms) []
  1008         val _ = tracing ("Ground types: "
  1009           ^ (if null types then "none."
  1010              else commas (map (Syntax.string_of_typ ctxt) types)))
  1011         (* we can only consider fragments of recursive IDTs, so we issue a  *)
  1012         (* warning if the formula contains a recursive IDT                  *)
  1013         (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
  1014         val maybe_spurious = Library.exists (fn
  1015             Type (s, _) =>
  1016               (case BNF_LFP_Compat.get_info thy [] s of
  1017                 SOME info =>  (* inductive datatype *)
  1018                   let
  1019                     val index           = #index info
  1020                     val descr           = #descr info
  1021                     val (_, _, constrs) = the (AList.lookup (op =) descr index)
  1022                   in
  1023                     (* recursive datatype? *)
  1024                     Library.exists (fn (_, ds) =>
  1025                       Library.exists Old_Datatype_Aux.is_rec_type ds) constrs
  1026                   end
  1027               | NONE => false)
  1028           | _ => false) types
  1029         val _ =
  1030           if maybe_spurious then
  1031             warning ("Term contains a recursive datatype; "
  1032               ^ "countermodel(s) may be spurious!")
  1033           else
  1034             ()
  1035         fun find_model_loop universe =
  1036           let
  1037             val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
  1038             val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
  1039                     orelse raise TimeLimit.TimeOut
  1040             val init_model = (universe, [])
  1041             val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
  1042               bounds = [], wellformed = True}
  1043             val _ = tracing ("Translating term (sizes: "
  1044               ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
  1045             (* translate 'u' and all axioms *)
  1046             val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
  1047               let
  1048                 val (i, m', a') = interpret ctxt m a t'
  1049               in
  1050                 (* set 'def_eq' to 'true' *)
  1051                 (i, (m', {maxvars = #maxvars a', def_eq = true,
  1052                   next_idx = #next_idx a', bounds = #bounds a',
  1053                   wellformed = #wellformed a'}))
  1054               end) (u :: axioms) (init_model, init_args)
  1055             (* make 'u' either true or false, and make all axioms true, and *)
  1056             (* add the well-formedness side condition                       *)
  1057             val fm_u = (if negate then toFalse else toTrue) (hd intrs)
  1058             val fm_ax = Prop_Logic.all (map toTrue (tl intrs))
  1059             val fm = Prop_Logic.all [#wellformed args, fm_ax, fm_u]
  1060             val _ =
  1061               (if member (op =) ["cdclite"] satsolver then
  1062                 warning ("Using SAT solver " ^ quote satsolver ^
  1063                          "; for better performance, consider installing an \
  1064                          \external solver.")
  1065                else ());
  1066             val solver =
  1067               SAT_Solver.invoke_solver satsolver
  1068               handle Option.Option =>
  1069                      error ("Unknown SAT solver: " ^ quote satsolver ^
  1070                             ". Available solvers: " ^
  1071                             commas (map (quote o fst) (SAT_Solver.get_solvers ())) ^ ".")
  1072           in
  1073             Output.urgent_message "Invoking SAT solver...";
  1074             (case solver fm of
  1075               SAT_Solver.SATISFIABLE assignment =>
  1076                 (Output.urgent_message ("Model found:\n" ^ print_model ctxt model
  1077                   (fn i => case assignment i of SOME b => b | NONE => true));
  1078                  if maybe_spurious then "potential" else "genuine")
  1079             | SAT_Solver.UNSATISFIABLE _ =>
  1080                 (Output.urgent_message "No model exists.";
  1081                 case next_universe universe sizes minsize maxsize of
  1082                   SOME universe' => find_model_loop universe'
  1083                 | NONE => (Output.urgent_message
  1084                     "Search terminated, no larger universe within the given limits.";
  1085                     "none"))
  1086             | SAT_Solver.UNKNOWN =>
  1087                 (Output.urgent_message "No model found.";
  1088                 case next_universe universe sizes minsize maxsize of
  1089                   SOME universe' => find_model_loop universe'
  1090                 | NONE => (Output.urgent_message
  1091                   "Search terminated, no larger universe within the given limits.";
  1092                   "unknown"))) handle SAT_Solver.NOT_CONFIGURED =>
  1093               (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
  1094                "unknown")
  1095           end
  1096           handle MAXVARS_EXCEEDED =>
  1097             (Output.urgent_message ("Search terminated, number of Boolean variables ("
  1098               ^ string_of_int maxvars ^ " allowed) exceeded.");
  1099               "unknown")
  1100 
  1101         val outcome_code = find_model_loop (first_universe types sizes minsize)
  1102       in
  1103         check_expect outcome_code
  1104       end
  1105   in
  1106     (* some parameter sanity checks *)
  1107     minsize>=1 orelse
  1108       error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
  1109     maxsize>=1 orelse
  1110       error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
  1111     maxsize>=minsize orelse
  1112       error ("\"maxsize\" (=" ^ string_of_int maxsize ^
  1113       ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
  1114     maxvars>=0 orelse
  1115       error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
  1116     maxtime>=0 orelse
  1117       error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
  1118     (* enter loop with or without time limit *)
  1119     Output.urgent_message ("Trying to find a model that "
  1120       ^ (if negate then "refutes" else "satisfies") ^ ": "
  1121       ^ Syntax.string_of_term ctxt t);
  1122     if maxtime > 0 then (
  1123       TimeLimit.timeLimit (Time.fromSeconds maxtime)
  1124         wrapper ()
  1125       handle TimeLimit.TimeOut =>
  1126         (Output.urgent_message ("Search terminated, time limit (" ^
  1127             string_of_int maxtime
  1128             ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
  1129          check_expect "unknown")
  1130     ) else wrapper ()
  1131   end;
  1132 
  1133 
  1134 (* ------------------------------------------------------------------------- *)
  1135 (* INTERFACE, PART 2: FINDING A MODEL                                        *)
  1136 (* ------------------------------------------------------------------------- *)
  1137 
  1138 (* ------------------------------------------------------------------------- *)
  1139 (* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
  1140 (* params      : list of '(name, value)' pairs used to override default      *)
  1141 (*               parameters                                                  *)
  1142 (* ------------------------------------------------------------------------- *)
  1143 
  1144 fun satisfy_term ctxt params assm_ts t =
  1145   find_model ctxt (actual_params ctxt params) assm_ts t false;
  1146 
  1147 (* ------------------------------------------------------------------------- *)
  1148 (* refute_term: calls 'find_model' to find a model that refutes 't'          *)
  1149 (* params     : list of '(name, value)' pairs used to override default       *)
  1150 (*              parameters                                                   *)
  1151 (* ------------------------------------------------------------------------- *)
  1152 
  1153 fun refute_term ctxt params assm_ts t =
  1154   let
  1155     (* disallow schematic type variables, since we cannot properly negate  *)
  1156     (* terms containing them (their logical meaning is that there EXISTS a *)
  1157     (* type s.t. ...; to refute such a formula, we would have to show that *)
  1158     (* for ALL types, not ...)                                             *)
  1159     val _ = null (Term.add_tvars t []) orelse
  1160       error "Term to be refuted contains schematic type variables"
  1161 
  1162     (* existential closure over schematic variables *)
  1163     val vars = sort_wrt (fst o fst) (Term.add_vars t [])
  1164     (* Term.term *)
  1165     val ex_closure = fold (fn ((x, i), T) => fn t' =>
  1166       HOLogic.exists_const T $
  1167         Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
  1168     (* Note: If 't' is of type 'propT' (rather than 'boolT'), applying   *)
  1169     (* 'HOLogic.exists_const' is not type-correct.  However, this is not *)
  1170     (* really a problem as long as 'find_model' still interprets the     *)
  1171     (* resulting term correctly, without checking its type.              *)
  1172 
  1173     (* replace outermost universally quantified variables by Free's:     *)
  1174     (* refuting a term with Free's is generally faster than refuting a   *)
  1175     (* term with (nested) quantifiers, because quantifiers are expanded, *)
  1176     (* while the SAT solver searches for an interpretation for Free's.   *)
  1177     (* Also we get more information back that way, namely an             *)
  1178     (* interpretation which includes values for the (formerly)           *)
  1179     (* quantified variables.                                             *)
  1180     (* maps  !!x1...xn. !xk...xm. t   to   t  *)
  1181     fun strip_all_body (Const (@{const_name Pure.all}, _) $ Abs (_, _, t)) =
  1182           strip_all_body t
  1183       | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
  1184           strip_all_body t
  1185       | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
  1186           strip_all_body t
  1187       | strip_all_body t = t
  1188     (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
  1189     fun strip_all_vars (Const (@{const_name Pure.all}, _) $ Abs (a, T, t)) =
  1190           (a, T) :: strip_all_vars t
  1191       | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
  1192           strip_all_vars t
  1193       | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
  1194           (a, T) :: strip_all_vars t
  1195       | strip_all_vars _ = [] : (string * typ) list
  1196     val strip_t = strip_all_body ex_closure
  1197     val frees = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
  1198     val subst_t = Term.subst_bounds (map Free frees, strip_t)
  1199   in
  1200     find_model ctxt (actual_params ctxt params) assm_ts subst_t true
  1201   end;
  1202 
  1203 (* ------------------------------------------------------------------------- *)
  1204 (* refute_goal                                                               *)
  1205 (* ------------------------------------------------------------------------- *)
  1206 
  1207 fun refute_goal ctxt params th i =
  1208   let
  1209     val t = th |> prop_of
  1210   in
  1211     if Logic.count_prems t = 0 then
  1212       (Output.urgent_message "No subgoal!"; "none")
  1213     else
  1214       let
  1215         val assms = map term_of (Assumption.all_assms_of ctxt)
  1216         val (t, frees) = Logic.goal_params t i
  1217       in
  1218         refute_term ctxt params assms (subst_bounds (frees, t))
  1219       end
  1220   end
  1221 
  1222 
  1223 (* ------------------------------------------------------------------------- *)
  1224 (* INTERPRETERS: Auxiliary Functions                                         *)
  1225 (* ------------------------------------------------------------------------- *)
  1226 
  1227 (* ------------------------------------------------------------------------- *)
  1228 (* make_constants: returns all interpretations for type 'T' that consist of  *)
  1229 (*                 unit vectors with 'True'/'False' only (no Boolean         *)
  1230 (*                 variables)                                                *)
  1231 (* ------------------------------------------------------------------------- *)
  1232 
  1233 fun make_constants ctxt model T =
  1234   let
  1235     (* returns a list with all unit vectors of length n *)
  1236     fun unit_vectors n =
  1237       let
  1238         (* returns the k-th unit vector of length n *)
  1239         fun unit_vector (k, n) =
  1240           Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
  1241         fun unit_vectors_loop k =
  1242           if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
  1243       in
  1244         unit_vectors_loop 1
  1245       end
  1246     (* returns a list of lists, each one consisting of n (possibly *)
  1247     (* identical) elements from 'xs'                               *)
  1248     fun pick_all 1 xs = map single xs
  1249       | pick_all n xs =
  1250           let val rec_pick = pick_all (n - 1) xs in
  1251             maps (fn x => map (cons x) rec_pick) xs
  1252           end
  1253     (* returns all constant interpretations that have the same tree *)
  1254     (* structure as the interpretation argument                     *)
  1255     fun make_constants_intr (Leaf xs) = unit_vectors (length xs)
  1256       | make_constants_intr (Node xs) = map Node (pick_all (length xs)
  1257           (make_constants_intr (hd xs)))
  1258     (* obtain the interpretation for a variable of type 'T' *)
  1259     val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
  1260       bounds=[], wellformed=True} (Free ("dummy", T))
  1261   in
  1262     make_constants_intr i
  1263   end;
  1264 
  1265 (* ------------------------------------------------------------------------- *)
  1266 (* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
  1267 (*               (make_constants T)', but implemented more efficiently)      *)
  1268 (* ------------------------------------------------------------------------- *)
  1269 
  1270 (* returns 0 for an empty ground type or a function type with empty      *)
  1271 (* codomain, but fails for a function type with empty domain --          *)
  1272 (* admissibility of datatype constructor argument types (see "Inductive  *)
  1273 (* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
  1274 (* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
  1275 (* never occur as the domain of a function type that is the type of a    *)
  1276 (* constructor argument                                                  *)
  1277 
  1278 fun size_of_type ctxt model T =
  1279   let
  1280     (* returns the number of elements that have the same tree structure as a *)
  1281     (* given interpretation                                                  *)
  1282     fun size_of_intr (Leaf xs) = length xs
  1283       | size_of_intr (Node xs) = Integer.pow (length xs) (size_of_intr (hd xs))
  1284     (* obtain the interpretation for a variable of type 'T' *)
  1285     val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
  1286       bounds=[], wellformed=True} (Free ("dummy", T))
  1287   in
  1288     size_of_intr i
  1289   end;
  1290 
  1291 (* ------------------------------------------------------------------------- *)
  1292 (* TT/FF: interpretations that denote "true" or "false", respectively        *)
  1293 (* ------------------------------------------------------------------------- *)
  1294 
  1295 val TT = Leaf [True, False];
  1296 
  1297 val FF = Leaf [False, True];
  1298 
  1299 (* ------------------------------------------------------------------------- *)
  1300 (* make_equality: returns an interpretation that denotes (extensional)       *)
  1301 (*                equality of two interpretations                            *)
  1302 (* - two interpretations are 'equal' iff they are both defined and denote    *)
  1303 (*   the same value                                                          *)
  1304 (* - two interpretations are 'not_equal' iff they are both defined at least  *)
  1305 (*   partially, and a defined part denotes different values                  *)
  1306 (* - a completely undefined interpretation is neither 'equal' nor            *)
  1307 (*   'not_equal' to another interpretation                                   *)
  1308 (* ------------------------------------------------------------------------- *)
  1309 
  1310 (* We could in principle represent '=' on a type T by a particular        *)
  1311 (* interpretation.  However, the size of that interpretation is quadratic *)
  1312 (* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
  1313 (* 'i2' directly is more efficient than constructing the interpretation   *)
  1314 (* for equality on T first, and "applying" this interpretation to 'i1'    *)
  1315 (* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
  1316 
  1317 fun make_equality (i1, i2) =
  1318   let
  1319     fun equal (i1, i2) =
  1320       (case i1 of
  1321         Leaf xs =>
  1322           (case i2 of
  1323             Leaf ys => Prop_Logic.dot_product (xs, ys)  (* defined and equal *)
  1324           | Node _  => raise REFUTE ("make_equality",
  1325             "second interpretation is higher"))
  1326       | Node xs =>
  1327           (case i2 of
  1328             Leaf _  => raise REFUTE ("make_equality",
  1329             "first interpretation is higher")
  1330           | Node ys => Prop_Logic.all (map equal (xs ~~ ys))))
  1331     fun not_equal (i1, i2) =
  1332       (case i1 of
  1333         Leaf xs =>
  1334           (case i2 of
  1335             (* defined and not equal *)
  1336             Leaf ys => Prop_Logic.all ((Prop_Logic.exists xs)
  1337             :: (Prop_Logic.exists ys)
  1338             :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
  1339           | Node _  => raise REFUTE ("make_equality",
  1340             "second interpretation is higher"))
  1341       | Node xs =>
  1342           (case i2 of
  1343             Leaf _  => raise REFUTE ("make_equality",
  1344             "first interpretation is higher")
  1345           | Node ys => Prop_Logic.exists (map not_equal (xs ~~ ys))))
  1346   in
  1347     (* a value may be undefined; therefore 'not_equal' is not just the *)
  1348     (* negation of 'equal'                                             *)
  1349     Leaf [equal (i1, i2), not_equal (i1, i2)]
  1350   end;
  1351 
  1352 (* ------------------------------------------------------------------------- *)
  1353 (* make_def_equality: returns an interpretation that denotes (extensional)   *)
  1354 (*                    equality of two interpretations                        *)
  1355 (* This function treats undefined/partially defined interpretations          *)
  1356 (* different from 'make_equality': two undefined interpretations are         *)
  1357 (* considered equal, while a defined interpretation is considered not equal  *)
  1358 (* to an undefined interpretation.                                           *)
  1359 (* ------------------------------------------------------------------------- *)
  1360 
  1361 fun make_def_equality (i1, i2) =
  1362   let
  1363     fun equal (i1, i2) =
  1364       (case i1 of
  1365         Leaf xs =>
  1366           (case i2 of
  1367             (* defined and equal, or both undefined *)
  1368             Leaf ys => SOr (Prop_Logic.dot_product (xs, ys),
  1369             SAnd (Prop_Logic.all (map SNot xs), Prop_Logic.all (map SNot ys)))
  1370           | Node _  => raise REFUTE ("make_def_equality",
  1371             "second interpretation is higher"))
  1372       | Node xs =>
  1373           (case i2 of
  1374             Leaf _  => raise REFUTE ("make_def_equality",
  1375             "first interpretation is higher")
  1376           | Node ys => Prop_Logic.all (map equal (xs ~~ ys))))
  1377     val eq = equal (i1, i2)
  1378   in
  1379     Leaf [eq, SNot eq]
  1380   end;
  1381 
  1382 (* ------------------------------------------------------------------------- *)
  1383 (* interpretation_apply: returns an interpretation that denotes the result   *)
  1384 (*                       of applying the function denoted by 'i1' to the     *)
  1385 (*                       argument denoted by 'i2'                            *)
  1386 (* ------------------------------------------------------------------------- *)
  1387 
  1388 fun interpretation_apply (i1, i2) =
  1389   let
  1390     fun interpretation_disjunction (tr1,tr2) =
  1391       tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
  1392         (tree_pair (tr1,tr2))
  1393     fun prop_formula_times_interpretation (fm,tr) =
  1394       tree_map (map (fn x => SAnd (fm,x))) tr
  1395     fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
  1396           prop_formula_times_interpretation (fm,tr)
  1397       | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
  1398           interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
  1399             prop_formula_list_dot_product_interpretation_list (fms,trees))
  1400       | prop_formula_list_dot_product_interpretation_list (_,_) =
  1401           raise REFUTE ("interpretation_apply", "empty list (in dot product)")
  1402     (* returns a list of lists, each one consisting of one element from each *)
  1403     (* element of 'xss'                                                      *)
  1404     fun pick_all [xs] = map single xs
  1405       | pick_all (xs::xss) =
  1406           let val rec_pick = pick_all xss in
  1407             maps (fn x => map (cons x) rec_pick) xs
  1408           end
  1409       | pick_all _ = raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
  1410     fun interpretation_to_prop_formula_list (Leaf xs) = xs
  1411       | interpretation_to_prop_formula_list (Node trees) =
  1412           map Prop_Logic.all (pick_all
  1413             (map interpretation_to_prop_formula_list trees))
  1414   in
  1415     case i1 of
  1416       Leaf _ =>
  1417         raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
  1418     | Node xs =>
  1419         prop_formula_list_dot_product_interpretation_list
  1420           (interpretation_to_prop_formula_list i2, xs)
  1421   end;
  1422 
  1423 (* ------------------------------------------------------------------------- *)
  1424 (* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
  1425 (* ------------------------------------------------------------------------- *)
  1426 
  1427 fun eta_expand t i =
  1428   let
  1429     val Ts = Term.binder_types (Term.fastype_of t)
  1430     val t' = Term.incr_boundvars i t
  1431   in
  1432     fold_rev (fn T => fn term => Abs ("<eta_expand>", T, term))
  1433       (List.take (Ts, i))
  1434       (Term.list_comb (t', map Bound (i-1 downto 0)))
  1435   end;
  1436 
  1437 (* ------------------------------------------------------------------------- *)
  1438 (* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
  1439 (*               is the sum (over its constructors) of the product (over     *)
  1440 (*               their arguments) of the size of the argument types          *)
  1441 (* ------------------------------------------------------------------------- *)
  1442 
  1443 fun size_of_dtyp ctxt typ_sizes descr typ_assoc constructors =
  1444   Integer.sum (map (fn (_, dtyps) =>
  1445     Integer.prod (map (size_of_type ctxt (typ_sizes, []) o
  1446       (typ_of_dtyp descr typ_assoc)) dtyps))
  1447         constructors);
  1448 
  1449 
  1450 (* ------------------------------------------------------------------------- *)
  1451 (* INTERPRETERS: Actual Interpreters                                         *)
  1452 (* ------------------------------------------------------------------------- *)
  1453 
  1454 (* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
  1455 (* variables, function types, and propT                                  *)
  1456 
  1457 fun stlc_interpreter ctxt model args t =
  1458   let
  1459     val (typs, terms) = model
  1460     val {maxvars, def_eq, next_idx, bounds, wellformed} = args
  1461     fun interpret_groundterm T =
  1462       let
  1463         fun interpret_groundtype () =
  1464           let
  1465             (* the model must specify a size for ground types *)
  1466             val size =
  1467               if T = Term.propT then 2
  1468               else the (AList.lookup (op =) typs T)
  1469             val next = next_idx + size
  1470             (* check if 'maxvars' is large enough *)
  1471             val _ = (if next - 1 > maxvars andalso maxvars > 0 then
  1472               raise MAXVARS_EXCEEDED else ())
  1473             val fms  = map BoolVar (next_idx upto (next_idx + size - 1))
  1474             val intr = Leaf fms
  1475             fun one_of_two_false [] = True
  1476               | one_of_two_false (x::xs) = SAnd (Prop_Logic.all (map (fn x' =>
  1477                   SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1478             val wf = one_of_two_false fms
  1479           in
  1480             (* extend the model, increase 'next_idx', add well-formedness *)
  1481             (* condition                                                  *)
  1482             SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  1483               def_eq = def_eq, next_idx = next, bounds = bounds,
  1484               wellformed = SAnd (wellformed, wf)})
  1485           end
  1486       in
  1487         case T of
  1488           Type ("fun", [T1, T2]) =>
  1489             let
  1490               (* we create 'size_of_type ... T1' different copies of the        *)
  1491               (* interpretation for 'T2', which are then combined into a single *)
  1492               (* new interpretation                                             *)
  1493               (* make fresh copies, with different variable indices *)
  1494               (* 'idx': next variable index                         *)
  1495               (* 'n'  : number of copies                            *)
  1496               fun make_copies idx 0 = (idx, [], True)
  1497                 | make_copies idx n =
  1498                     let
  1499                       val (copy, _, new_args) = interpret ctxt (typs, [])
  1500                         {maxvars = maxvars, def_eq = false, next_idx = idx,
  1501                         bounds = [], wellformed = True} (Free ("dummy", T2))
  1502                       val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
  1503                     in
  1504                       (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
  1505                     end
  1506               val (next, copies, wf) = make_copies next_idx
  1507                 (size_of_type ctxt model T1)
  1508               (* combine copies into a single interpretation *)
  1509               val intr = Node copies
  1510             in
  1511               (* extend the model, increase 'next_idx', add well-formedness *)
  1512               (* condition                                                  *)
  1513               SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  1514                 def_eq = def_eq, next_idx = next, bounds = bounds,
  1515                 wellformed = SAnd (wellformed, wf)})
  1516             end
  1517         | Type _  => interpret_groundtype ()
  1518         | TFree _ => interpret_groundtype ()
  1519         | TVar  _ => interpret_groundtype ()
  1520       end
  1521   in
  1522     case AList.lookup (op =) terms t of
  1523       SOME intr =>
  1524         (* return an existing interpretation *)
  1525         SOME (intr, model, args)
  1526     | NONE =>
  1527         (case t of
  1528           Const (_, T) => interpret_groundterm T
  1529         | Free (_, T) => interpret_groundterm T
  1530         | Var (_, T) => interpret_groundterm T
  1531         | Bound i => SOME (nth (#bounds args) i, model, args)
  1532         | Abs (_, T, body) =>
  1533             let
  1534               (* create all constants of type 'T' *)
  1535               val constants = make_constants ctxt model T
  1536               (* interpret the 'body' separately for each constant *)
  1537               val (bodies, (model', args')) = fold_map
  1538                 (fn c => fn (m, a) =>
  1539                   let
  1540                     (* add 'c' to 'bounds' *)
  1541                     val (i', m', a') = interpret ctxt m {maxvars = #maxvars a,
  1542                       def_eq = #def_eq a, next_idx = #next_idx a,
  1543                       bounds = (c :: #bounds a), wellformed = #wellformed a} body
  1544                   in
  1545                     (* keep the new model m' and 'next_idx' and 'wellformed', *)
  1546                     (* but use old 'bounds'                                   *)
  1547                     (i', (m', {maxvars = maxvars, def_eq = def_eq,
  1548                       next_idx = #next_idx a', bounds = bounds,
  1549                       wellformed = #wellformed a'}))
  1550                   end)
  1551                 constants (model, args)
  1552             in
  1553               SOME (Node bodies, model', args')
  1554             end
  1555         | t1 $ t2 =>
  1556             let
  1557               (* interpret 't1' and 't2' separately *)
  1558               val (intr1, model1, args1) = interpret ctxt model args t1
  1559               val (intr2, model2, args2) = interpret ctxt model1 args1 t2
  1560             in
  1561               SOME (interpretation_apply (intr1, intr2), model2, args2)
  1562             end)
  1563   end;
  1564 
  1565 fun Pure_interpreter ctxt model args t =
  1566   case t of
  1567     Const (@{const_name Pure.all}, _) $ t1 =>
  1568       let
  1569         val (i, m, a) = interpret ctxt model args t1
  1570       in
  1571         case i of
  1572           Node xs =>
  1573             (* 3-valued logic *)
  1574             let
  1575               val fmTrue  = Prop_Logic.all (map toTrue xs)
  1576               val fmFalse = Prop_Logic.exists (map toFalse xs)
  1577             in
  1578               SOME (Leaf [fmTrue, fmFalse], m, a)
  1579             end
  1580         | _ =>
  1581           raise REFUTE ("Pure_interpreter",
  1582             "\"Pure.all\" is followed by a non-function")
  1583       end
  1584   | Const (@{const_name Pure.all}, _) =>
  1585       SOME (interpret ctxt model args (eta_expand t 1))
  1586   | Const (@{const_name Pure.eq}, _) $ t1 $ t2 =>
  1587       let
  1588         val (i1, m1, a1) = interpret ctxt model args t1
  1589         val (i2, m2, a2) = interpret ctxt m1 a1 t2
  1590       in
  1591         (* we use either 'make_def_equality' or 'make_equality' *)
  1592         SOME ((if #def_eq args then make_def_equality else make_equality)
  1593           (i1, i2), m2, a2)
  1594       end
  1595   | Const (@{const_name Pure.eq}, _) $ _ =>
  1596       SOME (interpret ctxt model args (eta_expand t 1))
  1597   | Const (@{const_name Pure.eq}, _) =>
  1598       SOME (interpret ctxt model args (eta_expand t 2))
  1599   | Const (@{const_name Pure.imp}, _) $ t1 $ t2 =>
  1600       (* 3-valued logic *)
  1601       let
  1602         val (i1, m1, a1) = interpret ctxt model args t1
  1603         val (i2, m2, a2) = interpret ctxt m1 a1 t2
  1604         val fmTrue = Prop_Logic.SOr (toFalse i1, toTrue i2)
  1605         val fmFalse = Prop_Logic.SAnd (toTrue i1, toFalse i2)
  1606       in
  1607         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1608       end
  1609   | Const (@{const_name Pure.imp}, _) $ _ =>
  1610       SOME (interpret ctxt model args (eta_expand t 1))
  1611   | Const (@{const_name Pure.imp}, _) =>
  1612       SOME (interpret ctxt model args (eta_expand t 2))
  1613   | _ => NONE;
  1614 
  1615 fun HOLogic_interpreter ctxt model args t =
  1616 (* Providing interpretations directly is more efficient than unfolding the *)
  1617 (* logical constants.  In HOL however, logical constants can themselves be *)
  1618 (* arguments.  They are then translated using eta-expansion.               *)
  1619   case t of
  1620     Const (@{const_name Trueprop}, _) =>
  1621       SOME (Node [TT, FF], model, args)
  1622   | Const (@{const_name Not}, _) =>
  1623       SOME (Node [FF, TT], model, args)
  1624   (* redundant, since 'True' is also an IDT constructor *)
  1625   | Const (@{const_name True}, _) =>
  1626       SOME (TT, model, args)
  1627   (* redundant, since 'False' is also an IDT constructor *)
  1628   | Const (@{const_name False}, _) =>
  1629       SOME (FF, model, args)
  1630   | Const (@{const_name All}, _) $ t1 =>  (* similar to "Pure.all" *)
  1631       let
  1632         val (i, m, a) = interpret ctxt model args t1
  1633       in
  1634         case i of
  1635           Node xs =>
  1636             (* 3-valued logic *)
  1637             let
  1638               val fmTrue = Prop_Logic.all (map toTrue xs)
  1639               val fmFalse = Prop_Logic.exists (map toFalse xs)
  1640             in
  1641               SOME (Leaf [fmTrue, fmFalse], m, a)
  1642             end
  1643         | _ =>
  1644           raise REFUTE ("HOLogic_interpreter",
  1645             "\"All\" is followed by a non-function")
  1646       end
  1647   | Const (@{const_name All}, _) =>
  1648       SOME (interpret ctxt model args (eta_expand t 1))
  1649   | Const (@{const_name Ex}, _) $ t1 =>
  1650       let
  1651         val (i, m, a) = interpret ctxt model args t1
  1652       in
  1653         case i of
  1654           Node xs =>
  1655             (* 3-valued logic *)
  1656             let
  1657               val fmTrue = Prop_Logic.exists (map toTrue xs)
  1658               val fmFalse = Prop_Logic.all (map toFalse xs)
  1659             in
  1660               SOME (Leaf [fmTrue, fmFalse], m, a)
  1661             end
  1662         | _ =>
  1663           raise REFUTE ("HOLogic_interpreter",
  1664             "\"Ex\" is followed by a non-function")
  1665       end
  1666   | Const (@{const_name Ex}, _) =>
  1667       SOME (interpret ctxt model args (eta_expand t 1))
  1668   | Const (@{const_name HOL.eq}, _) $ t1 $ t2 =>  (* similar to Pure.eq *)
  1669       let
  1670         val (i1, m1, a1) = interpret ctxt model args t1
  1671         val (i2, m2, a2) = interpret ctxt m1 a1 t2
  1672       in
  1673         SOME (make_equality (i1, i2), m2, a2)
  1674       end
  1675   | Const (@{const_name HOL.eq}, _) $ _ =>
  1676       SOME (interpret ctxt model args (eta_expand t 1))
  1677   | Const (@{const_name HOL.eq}, _) =>
  1678       SOME (interpret ctxt model args (eta_expand t 2))
  1679   | Const (@{const_name HOL.conj}, _) $ t1 $ t2 =>
  1680       (* 3-valued logic *)
  1681       let
  1682         val (i1, m1, a1) = interpret ctxt model args t1
  1683         val (i2, m2, a2) = interpret ctxt m1 a1 t2
  1684         val fmTrue = Prop_Logic.SAnd (toTrue i1, toTrue i2)
  1685         val fmFalse = Prop_Logic.SOr (toFalse i1, toFalse i2)
  1686       in
  1687         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1688       end
  1689   | Const (@{const_name HOL.conj}, _) $ _ =>
  1690       SOME (interpret ctxt model args (eta_expand t 1))
  1691   | Const (@{const_name HOL.conj}, _) =>
  1692       SOME (interpret ctxt model args (eta_expand t 2))
  1693       (* this would make "undef" propagate, even for formulae like *)
  1694       (* "False & undef":                                          *)
  1695       (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
  1696   | Const (@{const_name HOL.disj}, _) $ t1 $ t2 =>
  1697       (* 3-valued logic *)
  1698       let
  1699         val (i1, m1, a1) = interpret ctxt model args t1
  1700         val (i2, m2, a2) = interpret ctxt m1 a1 t2
  1701         val fmTrue = Prop_Logic.SOr (toTrue i1, toTrue i2)
  1702         val fmFalse = Prop_Logic.SAnd (toFalse i1, toFalse i2)
  1703       in
  1704         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1705       end
  1706   | Const (@{const_name HOL.disj}, _) $ _ =>
  1707       SOME (interpret ctxt model args (eta_expand t 1))
  1708   | Const (@{const_name HOL.disj}, _) =>
  1709       SOME (interpret ctxt model args (eta_expand t 2))
  1710       (* this would make "undef" propagate, even for formulae like *)
  1711       (* "True | undef":                                           *)
  1712       (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
  1713   | Const (@{const_name HOL.implies}, _) $ t1 $ t2 =>  (* similar to Pure.imp *)
  1714       (* 3-valued logic *)
  1715       let
  1716         val (i1, m1, a1) = interpret ctxt model args t1
  1717         val (i2, m2, a2) = interpret ctxt m1 a1 t2
  1718         val fmTrue = Prop_Logic.SOr (toFalse i1, toTrue i2)
  1719         val fmFalse = Prop_Logic.SAnd (toTrue i1, toFalse i2)
  1720       in
  1721         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1722       end
  1723   | Const (@{const_name HOL.implies}, _) $ _ =>
  1724       SOME (interpret ctxt model args (eta_expand t 1))
  1725   | Const (@{const_name HOL.implies}, _) =>
  1726       SOME (interpret ctxt model args (eta_expand t 2))
  1727       (* this would make "undef" propagate, even for formulae like *)
  1728       (* "False --> undef":                                        *)
  1729       (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
  1730   | _ => NONE;
  1731 
  1732 (* interprets variables and constants whose type is an IDT (this is        *)
  1733 (* relatively easy and merely requires us to compute the size of the IDT); *)
  1734 (* constructors of IDTs however are properly interpreted by                *)
  1735 (* 'IDT_constructor_interpreter'                                           *)
  1736 
  1737 fun IDT_interpreter ctxt model args t =
  1738   let
  1739     val thy = Proof_Context.theory_of ctxt
  1740     val (typs, terms) = model
  1741     fun interpret_term (Type (s, Ts)) =
  1742           (case BNF_LFP_Compat.get_info thy [] s of
  1743             SOME info =>  (* inductive datatype *)
  1744               let
  1745                 (* only recursive IDTs have an associated depth *)
  1746                 val depth = AList.lookup (op =) typs (Type (s, Ts))
  1747                 (* sanity check: depth must be at least 0 *)
  1748                 val _ =
  1749                   (case depth of SOME n =>
  1750                     if n < 0 then
  1751                       raise REFUTE ("IDT_interpreter", "negative depth")
  1752                     else ()
  1753                   | _ => ())
  1754               in
  1755                 (* termination condition to avoid infinite recursion *)
  1756                 if depth = (SOME 0) then
  1757                   (* return a leaf of size 0 *)
  1758                   SOME (Leaf [], model, args)
  1759                 else
  1760                   let
  1761                     val index               = #index info
  1762                     val descr               = #descr info
  1763                     val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  1764                     val typ_assoc           = dtyps ~~ Ts
  1765                     (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1766                     val _ =
  1767                       if Library.exists (fn d =>
  1768                         case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  1769                       then
  1770                         raise REFUTE ("IDT_interpreter",
  1771                           "datatype argument (for type "
  1772                           ^ Syntax.string_of_typ ctxt (Type (s, Ts))
  1773                           ^ ") is not a variable")
  1774                       else ()
  1775                     (* if the model specifies a depth for the current type, *)
  1776                     (* decrement it to avoid infinite recursion             *)
  1777                     val typs' = case depth of NONE => typs | SOME n =>
  1778                       AList.update (op =) (Type (s, Ts), n-1) typs
  1779                     (* recursively compute the size of the datatype *)
  1780                     val size     = size_of_dtyp ctxt typs' descr typ_assoc constrs
  1781                     val next_idx = #next_idx args
  1782                     val next     = next_idx+size
  1783                     (* check if 'maxvars' is large enough *)
  1784                     val _        = (if next-1 > #maxvars args andalso
  1785                       #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
  1786                     val fms      = map BoolVar (next_idx upto (next_idx+size-1))
  1787                     val intr     = Leaf fms
  1788                     fun one_of_two_false [] = True
  1789                       | one_of_two_false (x::xs) = SAnd (Prop_Logic.all (map (fn x' =>
  1790                           SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1791                     val wf = one_of_two_false fms
  1792                   in
  1793                     (* extend the model, increase 'next_idx', add well-formedness *)
  1794                     (* condition                                                  *)
  1795                     SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
  1796                       def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
  1797                       wellformed = SAnd (#wellformed args, wf)})
  1798                   end
  1799               end
  1800           | NONE =>  (* not an inductive datatype *)
  1801               NONE)
  1802       | interpret_term _ =  (* a (free or schematic) type variable *)
  1803           NONE
  1804   in
  1805     case AList.lookup (op =) terms t of
  1806       SOME intr =>
  1807         (* return an existing interpretation *)
  1808         SOME (intr, model, args)
  1809     | NONE =>
  1810         (case t of
  1811           Free (_, T) => interpret_term T
  1812         | Var (_, T) => interpret_term T
  1813         | Const (_, T) => interpret_term T
  1814         | _ => NONE)
  1815   end;
  1816 
  1817 (* This function imposes an order on the elements of a datatype fragment  *)
  1818 (* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
  1819 (* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
  1820 (* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
  1821 (* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
  1822 (* same for recursive datatypes, although the computation of indices gets *)
  1823 (* a little tricky.                                                       *)
  1824 
  1825 fun IDT_constructor_interpreter ctxt model args t =
  1826   let
  1827     val thy = Proof_Context.theory_of ctxt
  1828     (* returns a list of canonical representations for terms of the type 'T' *)
  1829     (* It would be nice if we could just use 'print' for this, but 'print'   *)
  1830     (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
  1831     (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
  1832     fun canonical_terms typs T =
  1833           (case T of
  1834             Type ("fun", [T1, T2]) =>
  1835             (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
  1836             (* least not for 'T2'                                               *)
  1837             let
  1838               (* returns a list of lists, each one consisting of n (possibly *)
  1839               (* identical) elements from 'xs'                               *)
  1840               fun pick_all 1 xs = map single xs
  1841                 | pick_all n xs =
  1842                     let val rec_pick = pick_all (n-1) xs in
  1843                       maps (fn x => map (cons x) rec_pick) xs
  1844                     end
  1845               (* ["x1", ..., "xn"] *)
  1846               val terms1 = canonical_terms typs T1
  1847               (* ["y1", ..., "ym"] *)
  1848               val terms2 = canonical_terms typs T2
  1849               (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
  1850               (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
  1851               val functions = map (curry (op ~~) terms1)
  1852                 (pick_all (length terms1) terms2)
  1853               (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
  1854               (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
  1855               val pairss = map (map HOLogic.mk_prod) functions
  1856               val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  1857               val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  1858               val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  1859               val HOLogic_insert    =
  1860                 Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  1861             in
  1862               (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
  1863               map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
  1864                 HOLogic_empty_set) pairss
  1865             end
  1866       | Type (s, Ts) =>
  1867           (case BNF_LFP_Compat.get_info thy [] s of
  1868             SOME info =>
  1869               (case AList.lookup (op =) typs T of
  1870                 SOME 0 =>
  1871                   (* termination condition to avoid infinite recursion *)
  1872                   []  (* at depth 0, every IDT is empty *)
  1873               | _ =>
  1874                 let
  1875                   val index = #index info
  1876                   val descr = #descr info
  1877                   val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  1878                   val typ_assoc = dtyps ~~ Ts
  1879                   (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1880                   val _ =
  1881                     if Library.exists (fn d =>
  1882                       case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  1883                     then
  1884                       raise REFUTE ("IDT_constructor_interpreter",
  1885                         "datatype argument (for type "
  1886                         ^ Syntax.string_of_typ ctxt T
  1887                         ^ ") is not a variable")
  1888                     else ()
  1889                   (* decrement depth for the IDT 'T' *)
  1890                   val typs' =
  1891                     (case AList.lookup (op =) typs T of NONE => typs
  1892                     | SOME n => AList.update (op =) (T, n-1) typs)
  1893                   fun constructor_terms terms [] = terms
  1894                     | constructor_terms terms (d::ds) =
  1895                         let
  1896                           val dT = typ_of_dtyp descr typ_assoc d
  1897                           val d_terms = canonical_terms typs' dT
  1898                         in
  1899                           (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
  1900                           (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
  1901                           constructor_terms
  1902                             (map_product (curry op $) terms d_terms) ds
  1903                         end
  1904                 in
  1905                   (* C_i ... < C_j ... if i < j *)
  1906                   maps (fn (cname, ctyps) =>
  1907                     let
  1908                       val cTerm = Const (cname,
  1909                         map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
  1910                     in
  1911                       constructor_terms [cTerm] ctyps
  1912                     end) constrs
  1913                 end)
  1914           | NONE =>
  1915               (* not an inductive datatype; in this case the argument types in *)
  1916               (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
  1917               map (fn intr => print ctxt (typs, []) T intr (K false))
  1918                 (make_constants ctxt (typs, []) T))
  1919       | _ =>  (* TFree ..., TVar ... *)
  1920           map (fn intr => print ctxt (typs, []) T intr (K false))
  1921             (make_constants ctxt (typs, []) T))
  1922     val (typs, terms) = model
  1923   in
  1924     case AList.lookup (op =) terms t of
  1925       SOME intr =>
  1926         (* return an existing interpretation *)
  1927         SOME (intr, model, args)
  1928     | NONE =>
  1929         (case t of
  1930           Const (s, T) =>
  1931             (case body_type T of
  1932               Type (s', Ts') =>
  1933                 (case BNF_LFP_Compat.get_info thy [] s' of
  1934                   SOME info =>  (* body type is an inductive datatype *)
  1935                     let
  1936                       val index               = #index info
  1937                       val descr               = #descr info
  1938                       val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  1939                       val typ_assoc           = dtyps ~~ Ts'
  1940                       (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1941                       val _ = if Library.exists (fn d =>
  1942                           case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  1943                         then
  1944                           raise REFUTE ("IDT_constructor_interpreter",
  1945                             "datatype argument (for type "
  1946                             ^ Syntax.string_of_typ ctxt (Type (s', Ts'))
  1947                             ^ ") is not a variable")
  1948                         else ()
  1949                       (* split the constructors into those occurring before/after *)
  1950                       (* 'Const (s, T)'                                          *)
  1951                       val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
  1952                         not (cname = s andalso Sign.typ_instance thy (T,
  1953                           map (typ_of_dtyp descr typ_assoc) ctypes
  1954                             ---> Type (s', Ts')))) constrs
  1955                     in
  1956                       case constrs2 of
  1957                         [] =>
  1958                           (* 'Const (s, T)' is not a constructor of this datatype *)
  1959                           NONE
  1960                       | (_, ctypes)::_ =>
  1961                           let
  1962                             (* only /recursive/ IDTs have an associated depth *)
  1963                             val depth = AList.lookup (op =) typs (Type (s', Ts'))
  1964                             (* this should never happen: at depth 0, this IDT fragment *)
  1965                             (* is definitely empty, and in this case we don't need to  *)
  1966                             (* interpret its constructors                              *)
  1967                             val _ = (case depth of SOME 0 =>
  1968                                 raise REFUTE ("IDT_constructor_interpreter",
  1969                                   "depth is 0")
  1970                               | _ => ())
  1971                             val typs' = (case depth of NONE => typs | SOME n =>
  1972                               AList.update (op =) (Type (s', Ts'), n-1) typs)
  1973                             (* elements of the datatype come before elements generated *)
  1974                             (* by 'Const (s, T)' iff they are generated by a           *)
  1975                             (* constructor in constrs1                                 *)
  1976                             val offset = size_of_dtyp ctxt typs' descr typ_assoc constrs1
  1977                             (* compute the total (current) size of the datatype *)
  1978                             val total = offset +
  1979                               size_of_dtyp ctxt typs' descr typ_assoc constrs2
  1980                             (* sanity check *)
  1981                             val _ = if total <> size_of_type ctxt (typs, [])
  1982                               (Type (s', Ts')) then
  1983                                 raise REFUTE ("IDT_constructor_interpreter",
  1984                                   "total is not equal to current size")
  1985                               else ()
  1986                             (* returns an interpretation where everything is mapped to *)
  1987                             (* an "undefined" element of the datatype                  *)
  1988                             fun make_undef [] = Leaf (replicate total False)
  1989                               | make_undef (d::ds) =
  1990                                   let
  1991                                     (* compute the current size of the type 'd' *)
  1992                                     val dT   = typ_of_dtyp descr typ_assoc d
  1993                                     val size = size_of_type ctxt (typs, []) dT
  1994                                   in
  1995                                     Node (replicate size (make_undef ds))
  1996                                   end
  1997                             (* returns the interpretation for a constructor *)
  1998                             fun make_constr [] offset =
  1999                                   if offset < total then
  2000                                     (Leaf (replicate offset False @ True ::
  2001                                       (replicate (total - offset - 1) False)), offset + 1)
  2002                                   else
  2003                                     raise REFUTE ("IDT_constructor_interpreter",
  2004                                       "offset >= total")
  2005                               | make_constr (d::ds) offset =
  2006                                   let
  2007                                     val dT = typ_of_dtyp descr typ_assoc d
  2008                                     (* compute canonical term representations for all   *)
  2009                                     (* elements of the type 'd' (with the reduced depth *)
  2010                                     (* for the IDT)                                     *)
  2011                                     val terms' = canonical_terms typs' dT
  2012                                     (* sanity check *)
  2013                                     val _ =
  2014                                       if length terms' <> size_of_type ctxt (typs', []) dT
  2015                                       then
  2016                                         raise REFUTE ("IDT_constructor_interpreter",
  2017                                           "length of terms' is not equal to old size")
  2018                                       else ()
  2019                                     (* compute canonical term representations for all   *)
  2020                                     (* elements of the type 'd' (with the current depth *)
  2021                                     (* for the IDT)                                     *)
  2022                                     val terms = canonical_terms typs dT
  2023                                     (* sanity check *)
  2024                                     val _ =
  2025                                       if length terms <> size_of_type ctxt (typs, []) dT
  2026                                       then
  2027                                         raise REFUTE ("IDT_constructor_interpreter",
  2028                                           "length of terms is not equal to current size")
  2029                                       else ()
  2030                                     (* sanity check *)
  2031                                     val _ =
  2032                                       if length terms < length terms' then
  2033                                         raise REFUTE ("IDT_constructor_interpreter",
  2034                                           "current size is less than old size")
  2035                                       else ()
  2036                                     (* sanity check: every element of terms' must also be *)
  2037                                     (*               present in terms                     *)
  2038                                     val _ =
  2039                                       if forall (member (op =) terms) terms' then ()
  2040                                       else
  2041                                         raise REFUTE ("IDT_constructor_interpreter",
  2042                                           "element has disappeared")
  2043                                     (* sanity check: the order on elements of terms' is    *)
  2044                                     (*               the same in terms, for those elements *)
  2045                                     val _ =
  2046                                       let
  2047                                         fun search (x::xs) (y::ys) =
  2048                                               if x = y then search xs ys else search (x::xs) ys
  2049                                           | search (_::_) [] =
  2050                                               raise REFUTE ("IDT_constructor_interpreter",
  2051                                                 "element order not preserved")
  2052                                           | search [] _ = ()
  2053                                       in search terms' terms end
  2054                                     val (intrs, new_offset) =
  2055                                       fold_map (fn t_elem => fn off =>
  2056                                         (* if 't_elem' existed at the previous depth,    *)
  2057                                         (* proceed recursively, otherwise map the entire *)
  2058                                         (* subtree to "undefined"                        *)
  2059                                         if member (op =) terms' t_elem then
  2060                                           make_constr ds off
  2061                                         else
  2062                                           (make_undef ds, off))
  2063                                       terms offset
  2064                                   in
  2065                                     (Node intrs, new_offset)
  2066                                   end
  2067                           in
  2068                             SOME (fst (make_constr ctypes offset), model, args)
  2069                           end
  2070                     end
  2071                 | NONE =>  (* body type is not an inductive datatype *)
  2072                     NONE)
  2073             | _ =>  (* body type is a (free or schematic) type variable *)
  2074               NONE)
  2075         | _ =>  (* term is not a constant *)
  2076           NONE)
  2077   end;
  2078 
  2079 (* Difficult code ahead.  Make sure you understand the                *)
  2080 (* 'IDT_constructor_interpreter' and the order in which it enumerates *)
  2081 (* elements of an IDT before you try to understand this function.     *)
  2082 
  2083 fun IDT_recursion_interpreter ctxt model args t =
  2084   let
  2085     val thy = Proof_Context.theory_of ctxt
  2086   in
  2087     (* careful: here we descend arbitrarily deep into 't', possibly before *)
  2088     (* any other interpreter for atomic terms has had a chance to look at  *)
  2089     (* 't'                                                                 *)
  2090     case strip_comb t of
  2091       (Const (s, T), params) =>
  2092         (* iterate over all datatypes in 'thy' *)
  2093         Symtab.fold (fn (_, info) => fn result =>
  2094           case result of
  2095             SOME _ =>
  2096               result  (* just keep 'result' *)
  2097           | NONE =>
  2098               if member (op =) (#rec_names info) s then
  2099                 (* we do have a recursion operator of one of the (mutually *)
  2100                 (* recursive) datatypes given by 'info'                    *)
  2101                 let
  2102                   (* number of all constructors, including those of different  *)
  2103                   (* (mutually recursive) datatypes within the same descriptor *)
  2104                   val mconstrs_count =
  2105                     Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
  2106                 in
  2107                   if mconstrs_count < length params then
  2108                     (* too many actual parameters; for now we'll use the *)
  2109                     (* 'stlc_interpreter' to strip off one application   *)
  2110                     NONE
  2111                   else if mconstrs_count > length params then
  2112                     (* too few actual parameters; we use eta expansion          *)
  2113                     (* Note that the resulting expansion of lambda abstractions *)
  2114                     (* by the 'stlc_interpreter' may be rather slow (depending  *)
  2115                     (* on the argument types and the size of the IDT, of        *)
  2116                     (* course).                                                 *)
  2117                     SOME (interpret ctxt model args (eta_expand t
  2118                       (mconstrs_count - length params)))
  2119                   else  (* mconstrs_count = length params *)
  2120                     let
  2121                       (* interpret each parameter separately *)
  2122                       val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
  2123                         let
  2124                           val (i, m', a') = interpret ctxt m a p
  2125                         in
  2126                           (i, (m', a'))
  2127                         end) params (model, args)
  2128                       val (typs, _) = model'
  2129                       (* 'index' is /not/ necessarily the index of the IDT that *)
  2130                       (* the recursion operator is associated with, but merely  *)
  2131                       (* the index of some mutually recursive IDT               *)
  2132                       val index         = #index info
  2133                       val descr         = #descr info
  2134                       val (_, dtyps, _) = the (AList.lookup (op =) descr index)
  2135                       (* sanity check: we assume that the order of constructors *)
  2136                       (*               in 'descr' is the same as the order of   *)
  2137                       (*               corresponding parameters, otherwise the  *)
  2138                       (*               association code below won't match the   *)
  2139                       (*               right constructors/parameters; we also   *)
  2140                       (*               assume that the order of recursion       *)
  2141                       (*               operators in '#rec_names info' is the    *)
  2142                       (*               same as the order of corresponding       *)
  2143                       (*               datatypes in 'descr'                     *)
  2144                       val _ = if map fst descr <> (0 upto (length descr - 1)) then
  2145                           raise REFUTE ("IDT_recursion_interpreter",
  2146                             "order of constructors and corresponding parameters/" ^
  2147                               "recursion operators and corresponding datatypes " ^
  2148                               "different?")
  2149                         else ()
  2150                       (* sanity check: every element in 'dtyps' must be a *)
  2151                       (*               'DtTFree'                          *)
  2152                       val _ =
  2153                         if Library.exists (fn d =>
  2154                           case d of Old_Datatype_Aux.DtTFree _ => false
  2155                                   | _ => true) dtyps
  2156                         then
  2157                           raise REFUTE ("IDT_recursion_interpreter",
  2158                             "datatype argument is not a variable")
  2159                         else ()
  2160                       (* the type of a recursion operator is *)
  2161                       (* [T1, ..., Tn, IDT] ---> Tresult     *)
  2162                       val IDT = nth (binder_types T) mconstrs_count
  2163                       (* by our assumption on the order of recursion operators *)
  2164                       (* and datatypes, this is the index of the datatype      *)
  2165                       (* corresponding to the given recursion operator         *)
  2166                       val idt_index = find_index (fn s' => s' = s) (#rec_names info)
  2167                       (* mutually recursive types must have the same type   *)
  2168                       (* parameters, unless the mutual recursion comes from *)
  2169                       (* indirect recursion                                 *)
  2170                       fun rec_typ_assoc acc [] = acc
  2171                         | rec_typ_assoc acc ((d, T)::xs) =
  2172                             (case AList.lookup op= acc d of
  2173                               NONE =>
  2174                                 (case d of
  2175                                   Old_Datatype_Aux.DtTFree _ =>
  2176                                   (* add the association, proceed *)
  2177                                   rec_typ_assoc ((d, T)::acc) xs
  2178                                 | Old_Datatype_Aux.DtType (s, ds) =>
  2179                                     let
  2180                                       val (s', Ts) = dest_Type T
  2181                                     in
  2182                                       if s=s' then
  2183                                         rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  2184                                       else
  2185                                         raise REFUTE ("IDT_recursion_interpreter",
  2186                                           "DtType/Type mismatch")
  2187                                     end
  2188                                 | Old_Datatype_Aux.DtRec i =>
  2189                                     let
  2190                                       val (_, ds, _) = the (AList.lookup (op =) descr i)
  2191                                       val (_, Ts)    = dest_Type T
  2192                                     in
  2193                                       rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  2194                                     end)
  2195                             | SOME T' =>
  2196                                 if T=T' then
  2197                                   (* ignore the association since it's already *)
  2198                                   (* present, proceed                          *)
  2199                                   rec_typ_assoc acc xs
  2200                                 else
  2201                                   raise REFUTE ("IDT_recursion_interpreter",
  2202                                     "different type associations for the same dtyp"))
  2203                       val typ_assoc = filter
  2204                         (fn (Old_Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
  2205                         (rec_typ_assoc []
  2206                           (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
  2207                       (* sanity check: typ_assoc must associate types to the   *)
  2208                       (*               elements of 'dtyps' (and only to those) *)
  2209                       val _ =
  2210                         if not (eq_set (op =) (dtyps, map fst typ_assoc))
  2211                         then
  2212                           raise REFUTE ("IDT_recursion_interpreter",
  2213                             "type association has extra/missing elements")
  2214                         else ()
  2215                       (* interpret each constructor in the descriptor (including *)
  2216                       (* those of mutually recursive datatypes)                  *)
  2217                       (* (int * interpretation list) list *)
  2218                       val mc_intrs = map (fn (idx, (_, _, cs)) =>
  2219                         let
  2220                           val c_return_typ = typ_of_dtyp descr typ_assoc
  2221                             (Old_Datatype_Aux.DtRec idx)
  2222                         in
  2223                           (idx, map (fn (cname, cargs) =>
  2224                             (#1 o interpret ctxt (typs, []) {maxvars=0,
  2225                               def_eq=false, next_idx=1, bounds=[],
  2226                               wellformed=True}) (Const (cname, map (typ_of_dtyp
  2227                               descr typ_assoc) cargs ---> c_return_typ))) cs)
  2228                         end) descr
  2229                       (* associate constructors with corresponding parameters *)
  2230                       (* (int * (interpretation * interpretation) list) list *)
  2231                       val (mc_p_intrs, p_intrs') = fold_map
  2232                         (fn (idx, c_intrs) => fn p_intrs' =>
  2233                           let
  2234                             val len = length c_intrs
  2235                           in
  2236                             ((idx, c_intrs ~~ List.take (p_intrs', len)),
  2237                               List.drop (p_intrs', len))
  2238                           end) mc_intrs p_intrs
  2239                       (* sanity check: no 'p_intr' may be left afterwards *)
  2240                       val _ =
  2241                         if p_intrs' <> [] then
  2242                           raise REFUTE ("IDT_recursion_interpreter",
  2243                             "more parameter than constructor interpretations")
  2244                         else ()
  2245                       (* The recursion operator, applied to 'mconstrs_count'     *)
  2246                       (* arguments, is a function that maps every element of the *)
  2247                       (* inductive datatype to an element of some result type.   *)
  2248                       (* Recursion operators for mutually recursive IDTs are     *)
  2249                       (* translated simultaneously.                              *)
  2250                       (* Since the order on datatype elements is given by an     *)
  2251                       (* order on constructors (and then by the order on         *)
  2252                       (* argument tuples), we can simply copy corresponding      *)
  2253                       (* subtrees from 'p_intrs', in the order in which they are *)
  2254                       (* given.                                                  *)
  2255                       fun ci_pi (Leaf xs, pi) =
  2256                             (* if the constructor does not match the arguments to a *)
  2257                             (* defined element of the IDT, the corresponding value  *)
  2258                             (* of the parameter must be ignored                     *)
  2259                             if List.exists (equal True) xs then [pi] else []
  2260                         | ci_pi (Node xs, Node ys) = maps ci_pi (xs ~~ ys)
  2261                         | ci_pi (Node _, Leaf _) =
  2262                             raise REFUTE ("IDT_recursion_interpreter",
  2263                               "constructor takes more arguments than the " ^
  2264                                 "associated parameter")
  2265                       val rec_operators = map (fn (idx, c_p_intrs) =>
  2266                         (idx, maps ci_pi c_p_intrs)) mc_p_intrs
  2267                       (* sanity check: every recursion operator must provide as  *)
  2268                       (*               many values as the corresponding datatype *)
  2269                       (*               has elements                              *)
  2270                       val _ = map (fn (idx, intrs) =>
  2271                         let
  2272                           val T = typ_of_dtyp descr typ_assoc
  2273                             (Old_Datatype_Aux.DtRec idx)
  2274                         in
  2275                           if length intrs <> size_of_type ctxt (typs, []) T then
  2276                             raise REFUTE ("IDT_recursion_interpreter",
  2277                               "wrong number of interpretations for rec. operator")
  2278                           else ()
  2279                         end) rec_operators
  2280                       (* For non-recursive datatypes, we are pretty much done at *)
  2281                       (* this point.  For recursive datatypes however, we still  *)
  2282                       (* need to apply the interpretations in 'rec_operators' to *)
  2283                       (* (recursively obtained) interpretations for recursive    *)
  2284                       (* constructor arguments.  To do so more efficiently, we   *)
  2285                       (* copy 'rec_operators' into arrays first.  Each Boolean   *)
  2286                       (* indicates whether the recursive arguments have been     *)
  2287                       (* considered already.                                     *)
  2288                       val REC_OPERATORS = map (fn (idx, intrs) =>
  2289                         (idx, Array.fromList (map (pair false) intrs)))
  2290                         rec_operators
  2291                       (* takes an interpretation, and if some leaf of this     *)
  2292                       (* interpretation is the 'elem'-th element of the type,  *)
  2293                       (* the indices of the arguments leading to this leaf are *)
  2294                       (* returned                                              *)
  2295                       fun get_args (Leaf xs) elem =
  2296                             if find_index (fn x => x = True) xs = elem then
  2297                               SOME []
  2298                             else
  2299                               NONE
  2300                         | get_args (Node xs) elem =
  2301                             let
  2302                               fun search ([], _) =
  2303                                 NONE
  2304                                 | search (x::xs, n) =
  2305                                 (case get_args x elem of
  2306                                   SOME result => SOME (n::result)
  2307                                 | NONE        => search (xs, n+1))
  2308                             in
  2309                               search (xs, 0)
  2310                             end
  2311                       (* returns the index of the constructor and indices for *)
  2312                       (* its arguments that generate the 'elem'-th element of *)
  2313                       (* the datatype given by 'idx'                          *)
  2314                       fun get_cargs idx elem =
  2315                         let
  2316                           fun get_cargs_rec (_, []) =
  2317                                 raise REFUTE ("IDT_recursion_interpreter",
  2318                                   "no matching constructor found for datatype element")
  2319                             | get_cargs_rec (n, x::xs) =
  2320                                 (case get_args x elem of
  2321                                   SOME args => (n, args)
  2322                                 | NONE => get_cargs_rec (n+1, xs))
  2323                         in
  2324                           get_cargs_rec (0, the (AList.lookup (op =) mc_intrs idx))
  2325                         end
  2326                       (* computes one entry in 'REC_OPERATORS', and recursively *)
  2327                       (* all entries needed for it, where 'idx' gives the       *)
  2328                       (* datatype and 'elem' the element of it                  *)
  2329                       fun compute_array_entry idx elem =
  2330                         let
  2331                           val arr = the (AList.lookup (op =) REC_OPERATORS idx)
  2332                           val (flag, intr) = Array.sub (arr, elem)
  2333                         in
  2334                           if flag then
  2335                             (* simply return the previously computed result *)
  2336                             intr
  2337                           else
  2338                             (* we have to apply 'intr' to interpretations for all *)
  2339                             (* recursive arguments                                *)
  2340                             let
  2341                               val (c, args) = get_cargs idx elem
  2342                               (* find the indices of the constructor's /recursive/ *)
  2343                               (* arguments                                         *)
  2344                               val (_, _, constrs) = the (AList.lookup (op =) descr idx)
  2345                               val (_, dtyps) = nth constrs c
  2346                               val rec_dtyps_args = filter
  2347                                 (Old_Datatype_Aux.is_rec_type o fst) (dtyps ~~ args)
  2348                               (* map those indices to interpretations *)
  2349                               val rec_dtyps_intrs = map (fn (dtyp, arg) =>
  2350                                 let
  2351                                   val dT = typ_of_dtyp descr typ_assoc dtyp
  2352                                   val consts = make_constants ctxt (typs, []) dT
  2353                                   val arg_i = nth consts arg
  2354                                 in
  2355                                   (dtyp, arg_i)
  2356                                 end) rec_dtyps_args
  2357                               (* takes the dtyp and interpretation of an element, *)
  2358                               (* and computes the interpretation for the          *)
  2359                               (* corresponding recursive argument                 *)
  2360                               fun rec_intr (Old_Datatype_Aux.DtRec i) (Leaf xs) =
  2361                                     (* recursive argument is "rec_i params elem" *)
  2362                                     compute_array_entry i (find_index (fn x => x = True) xs)
  2363                                 | rec_intr (Old_Datatype_Aux.DtRec _) (Node _) =
  2364                                     raise REFUTE ("IDT_recursion_interpreter",
  2365                                       "interpretation for IDT is a node")
  2366                                 | rec_intr (Old_Datatype_Aux.DtType ("fun", [_, dt2])) (Node xs) =
  2367                                     (* recursive argument is something like     *)
  2368                                     (* "\<lambda>x::dt1. rec_? params (elem x)" *)
  2369                                     Node (map (rec_intr dt2) xs)
  2370                                 | rec_intr (Old_Datatype_Aux.DtType ("fun", [_, _])) (Leaf _) =
  2371                                     raise REFUTE ("IDT_recursion_interpreter",
  2372                                       "interpretation for function dtyp is a leaf")
  2373                                 | rec_intr _ _ =
  2374                                     (* admissibility ensures that every recursive type *)
  2375                                     (* is of the form 'Dt_1 -> ... -> Dt_k ->          *)
  2376                                     (* (DtRec i)'                                      *)
  2377                                     raise REFUTE ("IDT_recursion_interpreter",
  2378                                       "non-recursive codomain in recursive dtyp")
  2379                               (* obtain interpretations for recursive arguments *)
  2380                               (* interpretation list *)
  2381                               val arg_intrs = map (uncurry rec_intr) rec_dtyps_intrs
  2382                               (* apply 'intr' to all recursive arguments *)
  2383                               val result = fold (fn arg_i => fn i =>
  2384                                 interpretation_apply (i, arg_i)) arg_intrs intr
  2385                               (* update 'REC_OPERATORS' *)
  2386                               val _ = Array.update (arr, elem, (true, result))
  2387                             in
  2388                               result
  2389                             end
  2390                         end
  2391                       val idt_size = Array.length (the (AList.lookup (op =) REC_OPERATORS idt_index))
  2392                       (* sanity check: the size of 'IDT' should be 'size_idt' *)
  2393                       val _ =
  2394                           if idt_size <> size_of_type ctxt (typs, []) IDT then
  2395                             raise REFUTE ("IDT_recursion_interpreter",
  2396                               "unexpected size of IDT (wrong type associated?)")
  2397                           else ()
  2398                       val rec_op = Node (map_range (compute_array_entry idt_index) idt_size)
  2399                     in
  2400                       SOME (rec_op, model', args')
  2401                     end
  2402                 end
  2403               else
  2404                 NONE  (* not a recursion operator of this datatype *)
  2405           ) (BNF_LFP_Compat.get_all thy []) NONE
  2406     | _ =>  (* head of term is not a constant *)
  2407       NONE
  2408   end;
  2409 
  2410 fun set_interpreter ctxt model args t =
  2411   let
  2412     val (typs, terms) = model
  2413   in
  2414     case AList.lookup (op =) terms t of
  2415       SOME intr =>
  2416         (* return an existing interpretation *)
  2417         SOME (intr, model, args)
  2418     | NONE =>
  2419         (case t of
  2420           Free (x, Type (@{type_name set}, [T])) =>
  2421           let
  2422             val (intr, _, args') =
  2423               interpret ctxt (typs, []) args (Free (x, T --> HOLogic.boolT))
  2424           in
  2425             SOME (intr, (typs, (t, intr)::terms), args')
  2426           end
  2427         | Var ((x, i), Type (@{type_name set}, [T])) =>
  2428           let
  2429             val (intr, _, args') =
  2430               interpret ctxt (typs, []) args (Var ((x,i), T --> HOLogic.boolT))
  2431           in
  2432             SOME (intr, (typs, (t, intr)::terms), args')
  2433           end
  2434         | Const (s, Type (@{type_name set}, [T])) =>
  2435           let
  2436             val (intr, _, args') =
  2437               interpret ctxt (typs, []) args (Const (s, T --> HOLogic.boolT))
  2438           in
  2439             SOME (intr, (typs, (t, intr)::terms), args')
  2440           end
  2441         (* 'Collect' == identity *)
  2442         | Const (@{const_name Collect}, _) $ t1 =>
  2443             SOME (interpret ctxt model args t1)
  2444         | Const (@{const_name Collect}, _) =>
  2445             SOME (interpret ctxt model args (eta_expand t 1))
  2446         (* 'op :' == application *)
  2447         | Const (@{const_name Set.member}, _) $ t1 $ t2 =>
  2448             SOME (interpret ctxt model args (t2 $ t1))
  2449         | Const (@{const_name Set.member}, _) $ _ =>
  2450             SOME (interpret ctxt model args (eta_expand t 1))
  2451         | Const (@{const_name Set.member}, _) =>
  2452             SOME (interpret ctxt model args (eta_expand t 2))
  2453         | _ => NONE)
  2454   end;
  2455 
  2456 (* only an optimization: 'card' could in principle be interpreted with *)
  2457 (* interpreters available already (using its definition), but the code *)
  2458 (* below is more efficient                                             *)
  2459 
  2460 fun Finite_Set_card_interpreter ctxt model args t =
  2461   case t of
  2462     Const (@{const_name Finite_Set.card},
  2463         Type ("fun", [Type (@{type_name set}, [T]), @{typ nat}])) =>
  2464       let
  2465         fun number_of_elements (Node xs) =
  2466             fold (fn x => fn n =>
  2467               if x = TT then
  2468                 n + 1
  2469               else if x = FF then
  2470                 n
  2471               else
  2472                 raise REFUTE ("Finite_Set_card_interpreter",
  2473                   "interpretation for set type does not yield a Boolean"))
  2474               xs 0
  2475           | number_of_elements (Leaf _) =
  2476               raise REFUTE ("Finite_Set_card_interpreter",
  2477                 "interpretation for set type is a leaf")
  2478         val size_of_nat = size_of_type ctxt model (@{typ nat})
  2479         (* takes an interpretation for a set and returns an interpretation *)
  2480         (* for a 'nat' denoting the set's cardinality                      *)
  2481         fun card i =
  2482           let
  2483             val n = number_of_elements i
  2484           in
  2485             if n < size_of_nat then
  2486               Leaf ((replicate n False) @ True ::
  2487                 (replicate (size_of_nat-n-1) False))
  2488             else
  2489               Leaf (replicate size_of_nat False)
  2490           end
  2491         val set_constants = make_constants ctxt model (HOLogic.mk_setT T)
  2492       in
  2493         SOME (Node (map card set_constants), model, args)
  2494       end
  2495   | _ => NONE;
  2496 
  2497 (* only an optimization: 'finite' could in principle be interpreted with  *)
  2498 (* interpreters available already (using its definition), but the code    *)
  2499 (* below is more efficient                                                *)
  2500 
  2501 fun Finite_Set_finite_interpreter ctxt model args t =
  2502   case t of
  2503     Const (@{const_name Finite_Set.finite},
  2504            Type ("fun", [_, @{typ bool}])) $ _ =>
  2505         (* we only consider finite models anyway, hence EVERY set is *)
  2506         (* "finite"                                                  *)
  2507         SOME (TT, model, args)
  2508   | Const (@{const_name Finite_Set.finite},
  2509            Type ("fun", [set_T, @{typ bool}])) =>
  2510       let
  2511         val size_of_set = size_of_type ctxt model set_T
  2512       in
  2513         (* we only consider finite models anyway, hence EVERY set is *)
  2514         (* "finite"                                                  *)
  2515         SOME (Node (replicate size_of_set TT), model, args)
  2516       end
  2517   | _ => NONE;
  2518 
  2519 (* only an optimization: 'less' could in principle be interpreted with *)
  2520 (* interpreters available already (using its definition), but the code     *)
  2521 (* below is more efficient                                                 *)
  2522 
  2523 fun Nat_less_interpreter ctxt model args t =
  2524   case t of
  2525     Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
  2526         Type ("fun", [@{typ nat}, @{typ bool}])])) =>
  2527       let
  2528         val size_of_nat = size_of_type ctxt model (@{typ nat})
  2529         (* the 'n'-th nat is not less than the first 'n' nats, while it *)
  2530         (* is less than the remaining 'size_of_nat - n' nats            *)
  2531         fun less n = Node ((replicate n FF) @ (replicate (size_of_nat - n) TT))
  2532       in
  2533         SOME (Node (map less (1 upto size_of_nat)), model, args)
  2534       end
  2535   | _ => NONE;
  2536 
  2537 (* only an optimization: 'plus' could in principle be interpreted with *)
  2538 (* interpreters available already (using its definition), but the code     *)
  2539 (* below is more efficient                                                 *)
  2540 
  2541 fun Nat_plus_interpreter ctxt model args t =
  2542   case t of
  2543     Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
  2544         Type ("fun", [@{typ nat}, @{typ nat}])])) =>
  2545       let
  2546         val size_of_nat = size_of_type ctxt model (@{typ nat})
  2547         fun plus m n =
  2548           let
  2549             val element = m + n
  2550           in
  2551             if element > size_of_nat - 1 then
  2552               Leaf (replicate size_of_nat False)
  2553             else
  2554               Leaf ((replicate element False) @ True ::
  2555                 (replicate (size_of_nat - element - 1) False))
  2556           end
  2557       in
  2558         SOME (Node (map_range (fn m => Node (map_range (plus m) size_of_nat)) size_of_nat),
  2559           model, args)
  2560       end
  2561   | _ => NONE;
  2562 
  2563 (* only an optimization: 'minus' could in principle be interpreted *)
  2564 (* with interpreters available already (using its definition), but the *)
  2565 (* code below is more efficient                                        *)
  2566 
  2567 fun Nat_minus_interpreter ctxt model args t =
  2568   case t of
  2569     Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
  2570         Type ("fun", [@{typ nat}, @{typ nat}])])) =>
  2571       let
  2572         val size_of_nat = size_of_type ctxt model (@{typ nat})
  2573         fun minus m n =
  2574           let
  2575             val element = Int.max (m-n, 0)
  2576           in
  2577             Leaf ((replicate element False) @ True ::
  2578               (replicate (size_of_nat - element - 1) False))
  2579           end
  2580       in
  2581         SOME (Node (map_range (fn m => Node (map_range (minus m) size_of_nat)) size_of_nat),
  2582           model, args)
  2583       end
  2584   | _ => NONE;
  2585 
  2586 (* only an optimization: 'times' could in principle be interpreted *)
  2587 (* with interpreters available already (using its definition), but the *)
  2588 (* code below is more efficient                                        *)
  2589 
  2590 fun Nat_times_interpreter ctxt model args t =
  2591   case t of
  2592     Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
  2593         Type ("fun", [@{typ nat}, @{typ nat}])])) =>
  2594       let
  2595         val size_of_nat = size_of_type ctxt model (@{typ nat})
  2596         fun mult m n =
  2597           let
  2598             val element = m * n
  2599           in
  2600             if element > size_of_nat - 1 then
  2601               Leaf (replicate size_of_nat False)
  2602             else
  2603               Leaf ((replicate element False) @ True ::
  2604                 (replicate (size_of_nat - element - 1) False))
  2605           end
  2606       in
  2607         SOME (Node (map_range (fn m => Node (map_range (mult m) size_of_nat)) size_of_nat),
  2608           model, args)
  2609       end
  2610   | _ => NONE;
  2611 
  2612 (* only an optimization: 'append' could in principle be interpreted with *)
  2613 (* interpreters available already (using its definition), but the code   *)
  2614 (* below is more efficient                                               *)
  2615 
  2616 fun List_append_interpreter ctxt model args t =
  2617   case t of
  2618     Const (@{const_name append},
  2619       Type (@{type_name fun}, [Type (@{type_name list}, [T]),
  2620         Type (@{type_name fun}, [Type (@{type_name list}, [_]), Type (@{type_name list}, [_])])])) =>
  2621       let
  2622         val size_elem = size_of_type ctxt model T
  2623         val size_list = size_of_type ctxt model (Type (@{type_name list}, [T]))
  2624         (* maximal length of lists; 0 if we only consider the empty list *)
  2625         val list_length =
  2626           let
  2627             fun list_length_acc len lists total =
  2628               if lists = total then
  2629                 len
  2630               else if lists < total then
  2631                 list_length_acc (len+1) (lists*size_elem) (total-lists)
  2632               else
  2633                 raise REFUTE ("List_append_interpreter",
  2634                   "size_list not equal to 1 + size_elem + ... + " ^
  2635                     "size_elem^len, for some len")
  2636           in
  2637             list_length_acc 0 1 size_list
  2638           end
  2639         val elements = 0 upto (size_list-1)
  2640         (* FIXME: there should be a nice formula, which computes the same as *)
  2641         (*        the following, but without all this intermediate tree      *)
  2642         (*        length/offset stuff                                        *)
  2643         (* associate each list with its length and offset in a complete tree *)
  2644         (* of width 'size_elem' and depth 'length_list' (with 'size_list'    *)
  2645         (* nodes total)                                                      *)
  2646         (* (int * (int * int)) list *)
  2647         val (lenoff_lists, _) = fold_map (fn elem => fn (offsets, off) =>
  2648           (* corresponds to a pre-order traversal of the tree *)
  2649           let
  2650             val len = length offsets
  2651             (* associate the given element with len/off *)
  2652             val assoc = (elem, (len, off))
  2653           in
  2654             if len < list_length then
  2655               (* go to first child node *)
  2656               (assoc, (off :: offsets, off * size_elem))
  2657             else if off mod size_elem < size_elem - 1 then
  2658               (* go to next sibling node *)
  2659               (assoc, (offsets, off + 1))
  2660             else
  2661               (* go back up the stack until we find a level where we can go *)
  2662               (* to the next sibling node                                   *)
  2663               let
  2664                 val offsets' = snd (take_prefix
  2665                   (fn off' => off' mod size_elem = size_elem - 1) offsets)
  2666               in
  2667                 case offsets' of
  2668                   [] =>
  2669                     (* we're at the last node in the tree; the next value *)
  2670                     (* won't be used anyway                               *)
  2671                     (assoc, ([], 0))
  2672                 | off'::offs' =>
  2673                     (* go to next sibling node *)
  2674                     (assoc, (offs', off' + 1))
  2675               end
  2676           end) elements ([], 0)
  2677         (* we also need the reverse association (from length/offset to *)
  2678         (* index)                                                      *)
  2679         val lenoff'_lists = map Library.swap lenoff_lists
  2680         (* returns the interpretation for "(list no. m) @ (list no. n)" *)
  2681         fun append m n =
  2682           let
  2683             val (len_m, off_m) = the (AList.lookup (op =) lenoff_lists m)
  2684             val (len_n, off_n) = the (AList.lookup (op =) lenoff_lists n)
  2685             val len_elem = len_m + len_n
  2686             val off_elem = off_m * Integer.pow len_n size_elem + off_n
  2687           in
  2688             case AList.lookup op= lenoff'_lists (len_elem, off_elem) of
  2689               NONE =>
  2690                 (* undefined *)
  2691                 Leaf (replicate size_list False)
  2692             | SOME element =>
  2693                 Leaf ((replicate element False) @ True ::
  2694                   (replicate (size_list - element - 1) False))
  2695           end
  2696       in
  2697         SOME (Node (map (fn m => Node (map (append m) elements)) elements),
  2698           model, args)
  2699       end
  2700   | _ => NONE;
  2701 
  2702 (* only an optimization: 'fst' could in principle be interpreted with  *)
  2703 (* interpreters available already (using its definition), but the code *)
  2704 (* below is more efficient                                             *)
  2705 
  2706 fun Product_Type_fst_interpreter ctxt model args t =
  2707   case t of
  2708     Const (@{const_name fst}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
  2709       let
  2710         val constants_T = make_constants ctxt model T
  2711         val size_U = size_of_type ctxt model U
  2712       in
  2713         SOME (Node (maps (replicate size_U) constants_T), model, args)
  2714       end
  2715   | _ => NONE;
  2716 
  2717 (* only an optimization: 'snd' could in principle be interpreted with  *)
  2718 (* interpreters available already (using its definition), but the code *)
  2719 (* below is more efficient                                             *)
  2720 
  2721 fun Product_Type_snd_interpreter ctxt model args t =
  2722   case t of
  2723     Const (@{const_name snd}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
  2724       let
  2725         val size_T = size_of_type ctxt model T
  2726         val constants_U = make_constants ctxt model U
  2727       in
  2728         SOME (Node (flat (replicate size_T constants_U)), model, args)
  2729       end
  2730   | _ => NONE;
  2731 
  2732 
  2733 (* ------------------------------------------------------------------------- *)
  2734 (* PRINTERS                                                                  *)
  2735 (* ------------------------------------------------------------------------- *)
  2736 
  2737 fun stlc_printer ctxt model T intr assignment =
  2738   let
  2739     val strip_leading_quote = perhaps (try (unprefix "'"))
  2740     fun string_of_typ (Type (s, _)) = s
  2741       | string_of_typ (TFree (x, _)) = strip_leading_quote x
  2742       | string_of_typ (TVar ((x,i), _)) =
  2743           strip_leading_quote x ^ string_of_int i
  2744     fun index_from_interpretation (Leaf xs) =
  2745           find_index (Prop_Logic.eval assignment) xs
  2746       | index_from_interpretation _ =
  2747           raise REFUTE ("stlc_printer",
  2748             "interpretation for ground type is not a leaf")
  2749   in
  2750     case T of
  2751       Type ("fun", [T1, T2]) =>
  2752         let
  2753           (* create all constants of type 'T1' *)
  2754           val constants = make_constants ctxt model T1
  2755           val results =
  2756             (case intr of
  2757               Node xs => xs
  2758             | _ => raise REFUTE ("stlc_printer",
  2759               "interpretation for function type is a leaf"))
  2760           (* Term.term list *)
  2761           val pairs = map (fn (arg, result) =>
  2762             HOLogic.mk_prod
  2763               (print ctxt model T1 arg assignment,
  2764                print ctxt model T2 result assignment))
  2765             (constants ~~ results)
  2766           val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  2767           val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  2768           val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  2769           val HOLogic_insert    =
  2770             Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  2771         in
  2772           SOME (fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) pairs HOLogic_empty_set)
  2773         end
  2774     | Type (@{type_name prop}, []) =>
  2775         (case index_from_interpretation intr of
  2776           ~1 => SOME (HOLogic.mk_Trueprop (Const (@{const_name undefined}, HOLogic.boolT)))
  2777         | 0  => SOME (HOLogic.mk_Trueprop @{term True})
  2778         | 1  => SOME (HOLogic.mk_Trueprop @{term False})
  2779         | _  => raise REFUTE ("stlc_interpreter",
  2780           "illegal interpretation for a propositional value"))
  2781     | Type _  =>
  2782         if index_from_interpretation intr = (~1) then
  2783           SOME (Const (@{const_name undefined}, T))
  2784         else
  2785           SOME (Const (string_of_typ T ^
  2786             string_of_int (index_from_interpretation intr), T))
  2787     | TFree _ =>
  2788         if index_from_interpretation intr = (~1) then
  2789           SOME (Const (@{const_name undefined}, T))
  2790         else
  2791           SOME (Const (string_of_typ T ^
  2792             string_of_int (index_from_interpretation intr), T))
  2793     | TVar _  =>
  2794         if index_from_interpretation intr = (~1) then
  2795           SOME (Const (@{const_name undefined}, T))
  2796         else
  2797           SOME (Const (string_of_typ T ^
  2798             string_of_int (index_from_interpretation intr), T))
  2799   end;
  2800 
  2801 fun set_printer ctxt model T intr assignment =
  2802   (case T of
  2803     Type (@{type_name set}, [T1]) =>
  2804     let
  2805       (* create all constants of type 'T1' *)
  2806       val constants = make_constants ctxt model T1
  2807       val results = (case intr of
  2808           Node xs => xs
  2809         | _       => raise REFUTE ("set_printer",
  2810           "interpretation for set type is a leaf"))
  2811       val elements = map_filter (fn (arg, result) =>
  2812         case result of
  2813           Leaf [fmTrue, (* fmFalse *) _] =>
  2814           if Prop_Logic.eval assignment fmTrue then
  2815             SOME (print ctxt model T1 arg assignment)
  2816           else (* if Prop_Logic.eval assignment fmFalse then *)
  2817             NONE
  2818         | _ =>
  2819           raise REFUTE ("set_printer",
  2820             "illegal interpretation for a Boolean value"))
  2821         (constants ~~ results)
  2822       val HOLogic_setT1     = HOLogic.mk_setT T1
  2823       val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT1)
  2824       val HOLogic_insert    =
  2825         Const (@{const_name insert}, T1 --> HOLogic_setT1 --> HOLogic_setT1)
  2826     in
  2827       SOME (Library.foldl (fn (acc, elem) => HOLogic_insert $ elem $ acc)
  2828         (HOLogic_empty_set, elements))
  2829     end
  2830   | _ =>
  2831     NONE);
  2832 
  2833 fun IDT_printer ctxt model T intr assignment =
  2834   let
  2835     val thy = Proof_Context.theory_of ctxt
  2836   in
  2837     (case T of
  2838       Type (s, Ts) =>
  2839         (case BNF_LFP_Compat.get_info thy [] s of
  2840           SOME info =>  (* inductive datatype *)
  2841             let
  2842               val (typs, _)           = model
  2843               val index               = #index info
  2844               val descr               = #descr info
  2845               val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  2846               val typ_assoc           = dtyps ~~ Ts
  2847               (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  2848               val _ =
  2849                 if Library.exists (fn d =>
  2850                   case d of Old_Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  2851                 then
  2852                   raise REFUTE ("IDT_printer", "datatype argument (for type " ^
  2853                     Syntax.string_of_typ ctxt (Type (s, Ts)) ^ ") is not a variable")
  2854                 else ()
  2855               (* the index of the element in the datatype *)
  2856               val element =
  2857                 (case intr of
  2858                   Leaf xs => find_index (Prop_Logic.eval assignment) xs
  2859                 | Node _  => raise REFUTE ("IDT_printer",
  2860                   "interpretation is not a leaf"))
  2861             in
  2862               if element < 0 then
  2863                 SOME (Const (@{const_name undefined}, Type (s, Ts)))
  2864               else
  2865                 let
  2866                   (* takes a datatype constructor, and if for some arguments this  *)
  2867                   (* constructor generates the datatype's element that is given by *)
  2868                   (* 'element', returns the constructor (as a term) as well as the *)
  2869                   (* indices of the arguments                                      *)
  2870                   fun get_constr_args (cname, cargs) =
  2871                     let
  2872                       val cTerm      = Const (cname,
  2873                         map (typ_of_dtyp descr typ_assoc) cargs ---> Type (s, Ts))
  2874                       val (iC, _, _) = interpret ctxt (typs, []) {maxvars=0,
  2875                         def_eq=false, next_idx=1, bounds=[], wellformed=True} cTerm
  2876                       fun get_args (Leaf xs) =
  2877                             if find_index (fn x => x = True) xs = element then
  2878                               SOME []
  2879                             else
  2880                               NONE
  2881                         | get_args (Node xs) =
  2882                             let
  2883                               fun search ([], _) =
  2884                                 NONE
  2885                                 | search (x::xs, n) =
  2886                                 (case get_args x of
  2887                                   SOME result => SOME (n::result)
  2888                                 | NONE        => search (xs, n+1))
  2889                             in
  2890                               search (xs, 0)
  2891                             end
  2892                     in
  2893                       Option.map (fn args => (cTerm, cargs, args)) (get_args iC)
  2894                     end
  2895                   val (cTerm, cargs, args) =
  2896                     (* we could speed things up by computing the correct          *)
  2897                     (* constructor directly (rather than testing all              *)
  2898                     (* constructors), based on the order in which constructors    *)
  2899                     (* generate elements of datatypes; the current implementation *)
  2900                     (* of 'IDT_printer' however is independent of the internals   *)
  2901                     (* of 'IDT_constructor_interpreter'                           *)
  2902                     (case get_first get_constr_args constrs of
  2903                       SOME x => x
  2904                     | NONE   => raise REFUTE ("IDT_printer",
  2905                       "no matching constructor found for element " ^
  2906                       string_of_int element))
  2907                   val argsTerms = map (fn (d, n) =>
  2908                     let
  2909                       val dT = typ_of_dtyp descr typ_assoc d
  2910                       (* we only need the n-th element of this list, so there   *)
  2911                       (* might be a more efficient implementation that does not *)
  2912                       (* generate all constants                                 *)
  2913                       val consts = make_constants ctxt (typs, []) dT
  2914                     in
  2915                       print ctxt (typs, []) dT (nth consts n) assignment
  2916                     end) (cargs ~~ args)
  2917                 in
  2918                   SOME (list_comb (cTerm, argsTerms))
  2919                 end
  2920             end
  2921         | NONE =>  (* not an inductive datatype *)
  2922             NONE)
  2923     | _ =>  (* a (free or schematic) type variable *)
  2924         NONE)
  2925   end;
  2926 
  2927 
  2928 (* ------------------------------------------------------------------------- *)
  2929 (* use 'setup Refute.setup' in an Isabelle theory to initialize the 'Refute' *)
  2930 (* structure                                                                 *)
  2931 (* ------------------------------------------------------------------------- *)
  2932 
  2933 (* ------------------------------------------------------------------------- *)
  2934 (* Note: the interpreters and printers are used in reverse order; however,   *)
  2935 (*       an interpreter that can handle non-atomic terms ends up being       *)
  2936 (*       applied before the 'stlc_interpreter' breaks the term apart into    *)
  2937 (*       subterms that are then passed to other interpreters!                *)
  2938 (* ------------------------------------------------------------------------- *)
  2939 (* FIXME formal @{const_name} for some entries (!??) *)
  2940 val setup =
  2941    add_interpreter "stlc"    stlc_interpreter #>
  2942    add_interpreter "Pure"    Pure_interpreter #>
  2943    add_interpreter "HOLogic" HOLogic_interpreter #>
  2944    add_interpreter "set"     set_interpreter #>
  2945    add_interpreter "IDT"             IDT_interpreter #>
  2946    add_interpreter "IDT_constructor" IDT_constructor_interpreter #>
  2947    add_interpreter "IDT_recursion"   IDT_recursion_interpreter #>
  2948    add_interpreter "Finite_Set.card"    Finite_Set_card_interpreter #>
  2949    add_interpreter "Finite_Set.finite"  Finite_Set_finite_interpreter #>
  2950    add_interpreter "Nat_Orderings.less" Nat_less_interpreter #>
  2951    add_interpreter "Nat_HOL.plus"       Nat_plus_interpreter #>
  2952    add_interpreter "Nat_HOL.minus"      Nat_minus_interpreter #>
  2953    add_interpreter "Nat_HOL.times"      Nat_times_interpreter #>
  2954    add_interpreter "List.append" List_append_interpreter #>
  2955    add_interpreter "Product_Type.prod.fst" Product_Type_fst_interpreter #>
  2956    add_interpreter "Product_Type.prod.snd" Product_Type_snd_interpreter #>
  2957    add_printer "stlc" stlc_printer #>
  2958    add_printer "set" set_printer #>
  2959    add_printer "IDT"  IDT_printer;
  2960 
  2961 
  2962 
  2963 (** outer syntax commands 'refute' and 'refute_params' **)
  2964 
  2965 (* argument parsing *)
  2966 
  2967 (*optional list of arguments of the form [name1=value1, name2=value2, ...]*)
  2968 
  2969 val scan_parm = Parse.name -- (Scan.optional (@{keyword "="} |-- Parse.name) "true")
  2970 val scan_parms = Scan.optional (@{keyword "["} |-- Parse.list scan_parm --| @{keyword "]"}) [];
  2971 
  2972 
  2973 (* 'refute' command *)
  2974 
  2975 val _ =
  2976   Outer_Syntax.improper_command @{command_spec "refute"}
  2977     "try to find a model that refutes a given subgoal"
  2978     (scan_parms -- Scan.optional Parse.nat 1 >>
  2979       (fn (parms, i) =>
  2980         Toplevel.unknown_proof o
  2981         Toplevel.keep (fn state =>
  2982           let
  2983             val ctxt = Toplevel.context_of state;
  2984             val {goal = st, ...} = Proof.raw_goal (Toplevel.proof_of state);
  2985           in refute_goal ctxt parms st i; () end)));
  2986 
  2987 
  2988 (* 'refute_params' command *)
  2989 
  2990 val _ =
  2991   Outer_Syntax.command @{command_spec "refute_params"}
  2992     "show/store default parameters for the 'refute' command"
  2993     (scan_parms >> (fn parms =>
  2994       Toplevel.theory (fn thy =>
  2995         let
  2996           val thy' = fold set_default_param parms thy;
  2997           val output =
  2998             (case get_default_params (Proof_Context.init_global thy') of
  2999               [] => "none"
  3000             | new_defaults => cat_lines (map (fn (x, y) => x ^ "=" ^ y) new_defaults));
  3001           val _ = writeln ("Default parameters for 'refute':\n" ^ output);
  3002         in thy' end)));
  3003 
  3004 end;