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