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