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