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