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