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