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