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